From 806d460305656e71f69d574ca40434860f7e122d Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 23 Nov 2026 08:52:41 +1300 Subject: [PATCH 01/11] Add data stream conformance test harness Shared helpers for porting the Rust livekit-data-stream crate's tests to end-to-end C++ tests: - FfiPeer drives a room's participant through the raw FFI, so it sends exactly what another FFI-based SDK sends: one-shot sends and stream writers go through the Rust outgoing manager (data streams v2), and raw header/chunk/trailer requests send hand-built v1 packets. - RawPacketSniffer records the raw stream packets a room receives. - Text/ByteStreamCollector receive through the public C++ API and record content, info and errors. The harness only uses API that predates the FFI reader/writer port, so tests built on it compile before and after that port. Also mint an optional LIVEKIT_TOKEN_C (cpp-test-c) for tests that need a third participant, and add RoomTestAccess::roomHandleId. Co-Authored-By: Claude Opus 5.5 --- docs/testing.md | 13 +- scripts/set-test-tokens.sh | 7 +- src/tests/common/data_stream_test_utils.h | 1055 +++++++++++++++++++++ src/tests/common/room_test_access.h | 8 + 4 files changed, 1080 insertions(+), 3 deletions(-) create mode 100644 src/tests/common/data_stream_test_utils.h diff --git a/docs/testing.md b/docs/testing.md index 09525611..381cfcb5 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -76,6 +76,10 @@ export LIVEKIT_URL="ws://localhost:7880" # or wss://your-server.livek export LIVEKIT_TOKEN_A="" export LIVEKIT_TOKEN_B="" +# Optional: a third participant (same room) for data stream tests that need a +# bystander, e.g. targeted streams. Tests that need it skip when it is unset. +export LIVEKIT_TOKEN_C="" + # Optional (for stress tests) export RPC_STRESS_DURATION_SECONDS=3600 # Test duration (default: 1 hour) export RPC_STRESS_CALLER_THREADS=4 # Concurrent caller threads (default: 4) @@ -83,9 +87,10 @@ export RPC_STRESS_CALLER_THREADS=4 # Concurrent caller threads (default: ### Generating tokens for the test suites -The easiest path is to source the helper script, which mints both +The easiest path is to source the helper script, which mints the participant tokens against a local `livekit-server --dev` and exports -`LIVEKIT_TOKEN_A`, `LIVEKIT_TOKEN_B`, and `LIVEKIT_URL` for the current shell: +`LIVEKIT_TOKEN_A`, `LIVEKIT_TOKEN_B`, `LIVEKIT_TOKEN_C`, and `LIVEKIT_URL` for +the current shell: ```bash source scripts/set-test-tokens.sh @@ -103,6 +108,10 @@ export LIVEKIT_TOKEN_B="$(lk token create --api-key devkey --api-secret secret - --join --valid-for 99999h --room cpp_data_track_test \ --grant '{"canPublish":true,"canSubscribe":true,"canPublishData":true}' \ --token-only)" +export LIVEKIT_TOKEN_C="$(lk token create --api-key devkey --api-secret secret -i cpp-test-c \ + --join --valid-for 99999h --room cpp_data_track_test \ + --grant '{"canPublish":true,"canSubscribe":true,"canPublishData":true}' \ + --token-only)" ``` ## Installed SDK packaging tests diff --git a/scripts/set-test-tokens.sh b/scripts/set-test-tokens.sh index 08370f16..6b068f40 100755 --- a/scripts/set-test-tokens.sh +++ b/scripts/set-test-tokens.sh @@ -48,6 +48,8 @@ fi LIVEKIT_ROOM="cpp_data_track_test" LIVEKIT_IDENTITY_A="cpp-test-a" LIVEKIT_IDENTITY_B="cpp-test-b" +# Third participant for tests that need a bystander (e.g. targeted data streams). +LIVEKIT_IDENTITY_C="cpp-test-c" if [[ $# -ne 0 ]]; then _fail "this script is hard-coded and does not accept arguments" 2 @@ -107,22 +109,25 @@ _create_token() { LIVEKIT_TOKEN_A="$(_create_token "$LIVEKIT_IDENTITY_A")" LIVEKIT_TOKEN_B="$(_create_token "$LIVEKIT_IDENTITY_B")" +LIVEKIT_TOKEN_C="$(_create_token "$LIVEKIT_IDENTITY_C")" _apply() { export LIVEKIT_TOKEN_A export LIVEKIT_TOKEN_B + export LIVEKIT_TOKEN_C export LIVEKIT_URL } _emit_eval() { printf 'export LIVEKIT_TOKEN_A=%q\n' "$LIVEKIT_TOKEN_A" printf 'export LIVEKIT_TOKEN_B=%q\n' "$LIVEKIT_TOKEN_B" + printf 'export LIVEKIT_TOKEN_C=%q\n' "$LIVEKIT_TOKEN_C" printf 'export LIVEKIT_URL=%q\n' "$LIVEKIT_URL" } if [[ "$_sourced" -eq 1 ]]; then _apply - echo "LIVEKIT_TOKEN_A, LIVEKIT_TOKEN_B, and LIVEKIT_URL set for this shell." >&2 + echo "LIVEKIT_TOKEN_A, LIVEKIT_TOKEN_B, LIVEKIT_TOKEN_C, and LIVEKIT_URL set for this shell." >&2 else _emit_eval echo "set_test_tokens: for this shell run: source $0 or: eval \"\$(bash $0)\"" >&2 diff --git a/src/tests/common/data_stream_test_utils.h b/src/tests/common/data_stream_test_utils.h new file mode 100644 index 00000000..688aa7a6 --- /dev/null +++ b/src/tests/common/data_stream_test_utils.h @@ -0,0 +1,1055 @@ +/* + * 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. + */ + +// Shared harness for the data stream conformance tests, which port the Rust +// `livekit-data-stream` crate's unit tests to end-to-end tests against a real +// SFU. Three pieces: +// +// * FfiPeer - drives a connected Room's local participant through the +// raw FFI, bypassing the C++ data stream API. It sends +// exactly what another FFI-based SDK (Python, Unity, ...) +// would: one-shot sends and stream writers go through the +// Rust outgoing manager (so they use data streams v2: +// inline / compressed packets), and raw header / chunk / +// trailer requests send hand-built v1 packets. +// * RawPacketSniffer - records the raw stream packets a room receives +// (`stream_{header,chunk,trailer}_received` room events). +// The FFI forwards neither `inline_content` nor +// `compression` on the header, so an inline stream shows +// up as a header with no chunk or trailer, and compression +// shows up as chunk bytes that differ from the plaintext. +// * Text/ByteStreamCollector - receives streams through the public C++ API +// and records content, info, and any error. +// +// Everything here uses only API that predates the FFI reader/writer port, so +// receive-side tests built on it compile both before and after that port. + +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "data_stream.pb.h" +#include "ffi.pb.h" +#include "ffi_client.h" +#include "room.pb.h" +#include "room_test_access.h" +#include "test_common.h" + +namespace livekit::test::ds { + +using namespace std::chrono_literals; + +/// How long to wait for something that should happen. +constexpr auto kStreamTimeout = 10s; +/// How long to wait to be confident something did NOT happen (e.g. no chunk +/// packets for an inline stream, or no stream for a non-targeted participant). +constexpr auto kQuietPeriod = 1500ms; + +/// Chunk size the Rust core splits outgoing streams at (`STREAM_CHUNK_SIZE`). +constexpr std::size_t kMtu = 15'000; + +inline std::string uniqueTopic(const std::string& name) { + static std::atomic counter{0}; + return "ds_conf_" + name + "_" + std::to_string(getTimestampUs()) + "_" + std::to_string(counter++); +} + +inline std::string uniqueStreamId(const std::string& name) { + static std::atomic counter{0}; + return "sid_" + name + "_" + std::to_string(getTimestampUs()) + "_" + std::to_string(counter++); +} + +// --------------------------------------------------------------------------- +// Payload generators +// --------------------------------------------------------------------------- + +/// `n` bytes of a short repeated phrase: deflate shrinks this enormously. +inline std::string compressibleText(std::size_t n) { + static const std::string phrase = "the quick brown fox jumps over the lazy dog. "; + std::string out; + out.reserve(n); + while (out.size() < n) { + out += phrase; + } + out.resize(n); + return out; +} + +/// Deterministic pseudo-random bytes (xorshift64*): deflate cannot shrink it. +inline std::string randomBytes(std::size_t n, std::uint64_t seed = 0x9E3779B97F4A7C15ULL) { + std::string out(n, '\0'); + std::uint64_t x = seed; + for (std::size_t i = 0; i < n; ++i) { + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + out[i] = static_cast((x * 0x2545F4914F6CDD1DULL) >> 56); + } + return out; +} + +/// Deterministic pseudo-random text over 64 ASCII symbols: valid UTF-8 that +/// deflate shrinks only modestly (6 bits of entropy per 8-bit byte). +inline std::string randomText(std::size_t n, std::uint64_t seed = 0xD1B54A32D192ED03ULL) { + static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + const std::string bytes = randomBytes(n, seed); + std::string out(n, '\0'); + for (std::size_t i = 0; i < n; ++i) { + out[i] = alphabet[static_cast(bytes[i]) % 64]; + } + return out; +} + +inline std::vector toBytes(const std::string& s) { return {s.begin(), s.end()}; } +inline std::string fromBytes(const std::vector& v) { return {v.begin(), v.end()}; } + +/// True if `s` is well-formed UTF-8 (no truncated or stray sequences). +inline bool isValidUtf8(const std::string& s) { + std::size_t i = 0; + while (i < s.size()) { + const auto c = static_cast(s[i]); + std::size_t len = 0; + if (c < 0x80) { + len = 1; + } else if ((c >> 5) == 0x6) { + len = 2; + } else if ((c >> 4) == 0xE) { + len = 3; + } else if ((c >> 3) == 0x1E) { + len = 4; + } else { + return false; + } + if (i + len > s.size()) { + return false; + } + for (std::size_t k = 1; k < len; ++k) { + if ((static_cast(s[i + k]) >> 6) != 0x2) { + return false; + } + } + i += len; + } + return true; +} + +// --------------------------------------------------------------------------- +// Rooms +// --------------------------------------------------------------------------- + +/// Connects three rooms (LIVEKIT_TOKEN_A/B/C). Returns an empty vector when +/// LIVEKIT_TOKEN_C is not set so callers can skip. +inline std::vector> threeTestRooms() { + const char* token_c = std::getenv("LIVEKIT_TOKEN_C"); + if (token_c == nullptr || token_c[0] == '\0') { + return {}; + } + const auto tokens = getDataTrackTestTokens(); + const std::vector all_tokens{tokens[0], tokens[1], token_c}; + std::vector> rooms; + for (std::size_t i = 0; i < all_tokens.size(); ++i) { + auto room = std::make_unique(); + if (!room->connect(kLocalTestLiveKitUrl, all_tokens[i], RoomOptions{})) { + throw std::runtime_error("Failed to connect test room " + std::to_string(i)); + } + rooms.push_back(std::move(room)); + } + waitForParticipantVisibility(rooms); + return rooms; +} + +inline std::string identityOf(const Room& room) { return lockLocalParticipant(room)->identity(); } + +// --------------------------------------------------------------------------- +// Raw packet sniffer +// --------------------------------------------------------------------------- + +struct RawHeader { + std::string sender; + std::string stream_id; + std::string topic; + std::string mime_type; + std::int64_t timestamp = 0; + std::optional total_length; + std::map attributes; + bool is_text = false; + // Text header + int operation_type = 0; + int version = 0; + std::string reply_to_stream_id; + std::vector attached_stream_ids; + bool generated = false; + // Byte header + std::string name; +}; + +struct RawChunk { + std::string sender; + std::string stream_id; + std::uint64_t chunk_index = 0; + std::string content; +}; + +struct RawTrailer { + std::string sender; + std::string stream_id; + std::string reason; + std::map attributes; +}; + +/// Records the raw data stream packets one room receives. Packets are copied +/// field by field into plain structs (never as protobuf messages: the test +/// binary links its own copy of the generated protobuf code). +class RawPacketSniffer { +public: + explicit RawPacketSniffer(const Room& room) : state_(std::make_shared()) { + state_->room_handle = RoomTestAccess::roomHandleId(room); + // The listener owns a reference to the state, so a callback that races + // with destruction never touches freed memory. + listener_id_ = FfiClient::instance().addListener( + [state = state_](const proto::FfiEvent& event) { State::onEvent(*state, event); }); + } + + ~RawPacketSniffer() { FfiClient::instance().removeListener(listener_id_); } + + RawPacketSniffer(const RawPacketSniffer&) = delete; + RawPacketSniffer& operator=(const RawPacketSniffer&) = delete; + RawPacketSniffer(RawPacketSniffer&&) = delete; + RawPacketSniffer& operator=(RawPacketSniffer&&) = delete; + + /// Waits for the first header on `topic`. + std::optional waitForHeader(const std::string& topic, + std::chrono::milliseconds timeout = kStreamTimeout) const { + std::unique_lock lock(state_->mutex); + std::optional found; + state_->cv.wait_for(lock, timeout, [&] { + for (const auto& h : state_->headers) { + if (h.topic == topic) { + found = h; + return true; + } + } + return false; + }); + return found; + } + + /// Waits for the trailer of `stream_id`. + std::optional waitForTrailer(const std::string& stream_id, + std::chrono::milliseconds timeout = kStreamTimeout) const { + std::unique_lock lock(state_->mutex); + std::optional found; + state_->cv.wait_for(lock, timeout, [&] { + for (const auto& t : state_->trailers) { + if (t.stream_id == stream_id) { + found = t; + return true; + } + } + return false; + }); + return found; + } + + /// Waits until at least `count` chunks of `stream_id` have arrived. + bool waitForChunks(const std::string& stream_id, std::size_t count, + std::chrono::milliseconds timeout = kStreamTimeout) const { + std::unique_lock lock(state_->mutex); + return state_->cv.wait_for(lock, timeout, [&] { return countChunksLocked(stream_id) >= count; }); + } + + std::vector headers(const std::string& topic) const { + const std::scoped_lock lock(state_->mutex); + std::vector out; + for (const auto& h : state_->headers) { + if (h.topic == topic) { + out.push_back(h); + } + } + return out; + } + + std::vector chunks(const std::string& stream_id) const { + const std::scoped_lock lock(state_->mutex); + std::vector out; + for (const auto& c : state_->chunks) { + if (c.stream_id == stream_id) { + out.push_back(c); + } + } + return out; + } + + std::vector trailers(const std::string& stream_id) const { + const std::scoped_lock lock(state_->mutex); + std::vector out; + for (const auto& t : state_->trailers) { + if (t.stream_id == stream_id) { + out.push_back(t); + } + } + return out; + } + + /// Concatenated raw chunk content of `stream_id`, in arrival order. + std::string rawContent(const std::string& stream_id) const { + std::string out; + for (const auto& c : chunks(stream_id)) { + out += c.content; + } + return out; + } + +private: + struct State { + std::uint64_t room_handle = 0; + std::mutex mutex; + std::condition_variable cv; + std::vector headers; + std::vector chunks; + std::vector trailers; + + static void onEvent(State& state, const proto::FfiEvent& event) { + if (event.message_case() != proto::FfiEvent::kRoomEvent) { + return; + } + const auto& re = event.room_event(); + if (re.room_handle() != state.room_handle) { + return; + } + switch (re.message_case()) { + case proto::RoomEvent::kStreamHeaderReceived: { + const auto& ev = re.stream_header_received(); + const auto& h = ev.header(); + RawHeader out; + out.sender = ev.participant_identity(); + out.stream_id = h.stream_id(); + out.topic = h.topic(); + out.mime_type = h.mime_type(); + out.timestamp = h.timestamp(); + if (h.has_total_length()) { + out.total_length = h.total_length(); + } + for (const auto& kv : h.attributes()) { + out.attributes.emplace(kv.first, kv.second); + } + if (h.has_text_header()) { + const auto& th = h.text_header(); + out.is_text = true; + out.operation_type = static_cast(th.operation_type()); + out.version = th.version(); + out.reply_to_stream_id = th.reply_to_stream_id(); + out.attached_stream_ids.assign(th.attached_stream_ids().begin(), th.attached_stream_ids().end()); + out.generated = th.generated(); + } else if (h.has_byte_header()) { + out.name = h.byte_header().name(); + } + push(state, [&] { state.headers.push_back(std::move(out)); }); + break; + } + case proto::RoomEvent::kStreamChunkReceived: { + const auto& ev = re.stream_chunk_received(); + RawChunk out; + out.sender = ev.participant_identity(); + out.stream_id = ev.chunk().stream_id(); + out.chunk_index = ev.chunk().chunk_index(); + out.content = ev.chunk().content(); + push(state, [&] { state.chunks.push_back(std::move(out)); }); + break; + } + case proto::RoomEvent::kStreamTrailerReceived: { + const auto& ev = re.stream_trailer_received(); + RawTrailer out; + out.sender = ev.participant_identity(); + out.stream_id = ev.trailer().stream_id(); + out.reason = ev.trailer().reason(); + for (const auto& kv : ev.trailer().attributes()) { + out.attributes.emplace(kv.first, kv.second); + } + push(state, [&] { state.trailers.push_back(std::move(out)); }); + break; + } + default: + break; + } + } + + template + static void push(State& state, F&& f) { + { + const std::scoped_lock lock(state.mutex); + f(); + } + state.cv.notify_all(); + } + }; + + std::size_t countChunksLocked(const std::string& stream_id) const { + std::size_t n = 0; + for (const auto& c : state_->chunks) { + if (c.stream_id == stream_id) { + ++n; + } + } + return n; + } + + std::shared_ptr state_; + FfiClient::ListenerId listener_id_ = 0; +}; + +// --------------------------------------------------------------------------- +// FfiPeer: a remote participant driven through the raw FFI +// --------------------------------------------------------------------------- + +struct PeerTextOptions { + std::string topic; + std::map attributes; + std::vector destination_identities; + std::optional stream_id; + std::optional reply_to_stream_id; + std::vector attached_stream_ids; + std::optional operation_type; + std::optional version; + std::optional generated; + std::optional compress; + std::optional sender_identity; +}; + +struct PeerByteOptions { + std::string topic; + std::map attributes; + std::vector destination_identities; + std::optional stream_id; + std::optional name; + std::optional mime_type; + std::optional total_length; + std::optional compress; + std::optional sender_identity; +}; + +/// A raw v1 header. Field meaning matches `DataStream.Header` on the wire. +struct PeerRawHeader { + std::string stream_id; + std::string topic; + std::string mime_type = "text/plain"; + std::optional total_length; + std::map attributes; + bool is_text = true; + std::string name; // byte streams only +}; + +/// Outcome of an FFI request that completes with an async callback. +struct PeerResult { + bool ok = false; + std::string error; + std::string stream_id; + std::uint64_t writer_handle = 0; +}; + +class FfiPeer { +public: + explicit FfiPeer(const Room& room) + : participant_handle_(lockLocalParticipant(room)->ffiHandleId()), identity_(identityOf(room)) {} + + const std::string& identity() const { return identity_; } + + // ---- One-shot sends (Rust outgoing manager: v2 inline / compressed) ---- + + PeerResult sendText(const std::string& text, const PeerTextOptions& opts) const { + proto::FfiRequest req; + auto* r = req.mutable_send_text(); + const auto id = nextAsyncId(); + r->set_local_participant_handle(participant_handle_); + r->set_text(text); + r->set_request_async_id(id); + fillTextOptions(*r->mutable_options(), opts); + return call(req, id, [](const proto::FfiEvent& e, std::uint64_t async_id) -> std::optional { + if (e.message_case() != proto::FfiEvent::kSendText || e.send_text().async_id() != async_id) { + return std::nullopt; + } + PeerResult res; + if (e.send_text().has_info()) { + res.ok = true; + res.stream_id = e.send_text().info().stream_id(); + } else { + res.error = e.send_text().error().description(); + } + return res; + }); + } + + PeerResult sendBytes(const std::string& bytes, const PeerByteOptions& opts) const { + proto::FfiRequest req; + auto* r = req.mutable_send_bytes(); + const auto id = nextAsyncId(); + r->set_local_participant_handle(participant_handle_); + r->set_bytes(bytes); + r->set_request_async_id(id); + fillByteOptions(*r->mutable_options(), opts); + return call(req, id, [](const proto::FfiEvent& e, std::uint64_t async_id) -> std::optional { + if (e.message_case() != proto::FfiEvent::kSendBytes || e.send_bytes().async_id() != async_id) { + return std::nullopt; + } + PeerResult res; + if (e.send_bytes().has_info()) { + res.ok = true; + res.stream_id = e.send_bytes().info().stream_id(); + } else { + res.error = e.send_bytes().error().description(); + } + return res; + }); + } + + // ---- Stream writers (Rust outgoing manager: chunked, never inline) ---- + + PeerResult openText(const PeerTextOptions& opts) const { + proto::FfiRequest req; + auto* r = req.mutable_text_stream_open(); + const auto id = nextAsyncId(); + r->set_local_participant_handle(participant_handle_); + r->set_request_async_id(id); + fillTextOptions(*r->mutable_options(), opts); + return call(req, id, [](const proto::FfiEvent& e, std::uint64_t async_id) -> std::optional { + if (e.message_case() != proto::FfiEvent::kTextStreamOpen || e.text_stream_open().async_id() != async_id) { + return std::nullopt; + } + PeerResult res; + if (e.text_stream_open().has_writer()) { + res.ok = true; + res.writer_handle = e.text_stream_open().writer().handle().id(); + res.stream_id = e.text_stream_open().writer().info().stream_id(); + } else { + res.error = e.text_stream_open().error().description(); + } + return res; + }); + } + + PeerResult writeText(std::uint64_t writer_handle, const std::string& text) const { + proto::FfiRequest req; + auto* r = req.mutable_text_stream_write(); + const auto id = nextAsyncId(); + r->set_writer_handle(writer_handle); + r->set_text(text); + r->set_request_async_id(id); + return call(req, id, [](const proto::FfiEvent& e, std::uint64_t async_id) -> std::optional { + if (e.message_case() != proto::FfiEvent::kTextStreamWriterWrite || + e.text_stream_writer_write().async_id() != async_id) { + return std::nullopt; + } + return errorResult(e.text_stream_writer_write().has_error(), e.text_stream_writer_write().error().description()); + }); + } + + PeerResult closeText(std::uint64_t writer_handle, const std::string& reason = "", + const std::map& attributes = {}) const { + proto::FfiRequest req; + auto* r = req.mutable_text_stream_close(); + const auto id = nextAsyncId(); + r->set_writer_handle(writer_handle); + if (!reason.empty()) { + r->set_reason(reason); + } + for (const auto& kv : attributes) { + (*r->mutable_attributes())[kv.first] = kv.second; + } + r->set_request_async_id(id); + return call(req, id, [](const proto::FfiEvent& e, std::uint64_t async_id) -> std::optional { + if (e.message_case() != proto::FfiEvent::kTextStreamWriterClose || + e.text_stream_writer_close().async_id() != async_id) { + return std::nullopt; + } + return errorResult(e.text_stream_writer_close().has_error(), e.text_stream_writer_close().error().description()); + }); + } + + PeerResult openBytes(const PeerByteOptions& opts) const { + proto::FfiRequest req; + auto* r = req.mutable_byte_stream_open(); + const auto id = nextAsyncId(); + r->set_local_participant_handle(participant_handle_); + r->set_request_async_id(id); + fillByteOptions(*r->mutable_options(), opts); + return call(req, id, [](const proto::FfiEvent& e, std::uint64_t async_id) -> std::optional { + if (e.message_case() != proto::FfiEvent::kByteStreamOpen || e.byte_stream_open().async_id() != async_id) { + return std::nullopt; + } + PeerResult res; + if (e.byte_stream_open().has_writer()) { + res.ok = true; + res.writer_handle = e.byte_stream_open().writer().handle().id(); + res.stream_id = e.byte_stream_open().writer().info().stream_id(); + } else { + res.error = e.byte_stream_open().error().description(); + } + return res; + }); + } + + PeerResult writeBytes(std::uint64_t writer_handle, const std::string& bytes) const { + proto::FfiRequest req; + auto* r = req.mutable_byte_stream_write(); + const auto id = nextAsyncId(); + r->set_writer_handle(writer_handle); + r->set_bytes(bytes); + r->set_request_async_id(id); + return call(req, id, [](const proto::FfiEvent& e, std::uint64_t async_id) -> std::optional { + if (e.message_case() != proto::FfiEvent::kByteStreamWriterWrite || + e.byte_stream_writer_write().async_id() != async_id) { + return std::nullopt; + } + return errorResult(e.byte_stream_writer_write().has_error(), e.byte_stream_writer_write().error().description()); + }); + } + + PeerResult closeBytes(std::uint64_t writer_handle, const std::string& reason = "", + const std::map& attributes = {}) const { + proto::FfiRequest req; + auto* r = req.mutable_byte_stream_close(); + const auto id = nextAsyncId(); + r->set_writer_handle(writer_handle); + if (!reason.empty()) { + r->set_reason(reason); + } + for (const auto& kv : attributes) { + (*r->mutable_attributes())[kv.first] = kv.second; + } + r->set_request_async_id(id); + return call(req, id, [](const proto::FfiEvent& e, std::uint64_t async_id) -> std::optional { + if (e.message_case() != proto::FfiEvent::kByteStreamWriterClose || + e.byte_stream_writer_close().async_id() != async_id) { + return std::nullopt; + } + return errorResult(e.byte_stream_writer_close().has_error(), e.byte_stream_writer_close().error().description()); + }); + } + + // ---- Hand-built v1 packets ---- + + PeerResult sendRawHeader(const PeerRawHeader& h, const std::vector& destinations = {}) const { + proto::FfiRequest req; + auto* r = req.mutable_send_stream_header(); + const auto id = nextAsyncId(); + r->set_local_participant_handle(participant_handle_); + r->set_sender_identity(identity_); + r->set_request_async_id(id); + for (const auto& d : destinations) { + r->add_destination_identities(d); + } + auto* header = r->mutable_header(); + header->set_stream_id(h.stream_id); + header->set_timestamp(static_cast(getTimestampUs() / 1000)); + header->set_mime_type(h.mime_type); + header->set_topic(h.topic); + if (h.total_length) { + header->set_total_length(*h.total_length); + } + for (const auto& kv : h.attributes) { + (*header->mutable_attributes())[kv.first] = kv.second; + } + if (h.is_text) { + header->mutable_text_header()->set_operation_type(proto::DataStream::CREATE); + } else { + header->mutable_byte_header()->set_name(h.name); + } + return call(req, id, [](const proto::FfiEvent& e, std::uint64_t async_id) -> std::optional { + if (e.message_case() != proto::FfiEvent::kSendStreamHeader || e.send_stream_header().async_id() != async_id) { + return std::nullopt; + } + return errorResult(e.send_stream_header().has_error(), e.send_stream_header().error()); + }); + } + + PeerResult sendRawChunk(const std::string& stream_id, std::uint64_t chunk_index, const std::string& content, + const std::vector& destinations = {}) const { + proto::FfiRequest req; + auto* r = req.mutable_send_stream_chunk(); + const auto id = nextAsyncId(); + r->set_local_participant_handle(participant_handle_); + r->set_sender_identity(identity_); + r->set_request_async_id(id); + for (const auto& d : destinations) { + r->add_destination_identities(d); + } + auto* chunk = r->mutable_chunk(); + chunk->set_stream_id(stream_id); + chunk->set_chunk_index(chunk_index); + chunk->set_content(content); + return call(req, id, [](const proto::FfiEvent& e, std::uint64_t async_id) -> std::optional { + if (e.message_case() != proto::FfiEvent::kSendStreamChunk || e.send_stream_chunk().async_id() != async_id) { + return std::nullopt; + } + return errorResult(e.send_stream_chunk().has_error(), e.send_stream_chunk().error()); + }); + } + + PeerResult sendRawTrailer(const std::string& stream_id, const std::string& reason = "", + const std::map& attributes = {}, + const std::vector& destinations = {}) const { + proto::FfiRequest req; + auto* r = req.mutable_send_stream_trailer(); + const auto id = nextAsyncId(); + r->set_local_participant_handle(participant_handle_); + r->set_sender_identity(identity_); + r->set_request_async_id(id); + for (const auto& d : destinations) { + r->add_destination_identities(d); + } + auto* trailer = r->mutable_trailer(); + trailer->set_stream_id(stream_id); + trailer->set_reason(reason); + for (const auto& kv : attributes) { + (*trailer->mutable_attributes())[kv.first] = kv.second; + } + return call(req, id, [](const proto::FfiEvent& e, std::uint64_t async_id) -> std::optional { + if (e.message_case() != proto::FfiEvent::kSendStreamTrailer || e.send_stream_trailer().async_id() != async_id) { + return std::nullopt; + } + return errorResult(e.send_stream_trailer().has_error(), e.send_stream_trailer().error()); + }); + } + +private: + using Extract = std::function(const proto::FfiEvent&, std::uint64_t)>; + + static std::uint64_t nextAsyncId() { + // Far above FfiClient's own counter (which starts at 1) so ids never collide. + static std::atomic next{std::uint64_t{1} << 62}; + return next++; + } + + static PeerResult errorResult(bool has_error, const std::string& error) { + PeerResult res; + res.ok = !has_error; + if (has_error) { + res.error = error; + } + return res; + } + + static void fillTextOptions(proto::StreamTextOptions& o, const PeerTextOptions& opts) { + o.set_topic(opts.topic); + for (const auto& kv : opts.attributes) { + (*o.mutable_attributes())[kv.first] = kv.second; + } + for (const auto& d : opts.destination_identities) { + o.add_destination_identities(d); + } + if (opts.stream_id) { + o.set_id(*opts.stream_id); + } + if (opts.reply_to_stream_id) { + o.set_reply_to_stream_id(*opts.reply_to_stream_id); + } + for (const auto& a : opts.attached_stream_ids) { + o.add_attached_stream_ids(a); + } + if (opts.operation_type) { + o.set_operation_type(static_cast(*opts.operation_type)); + } + if (opts.version) { + o.set_version(*opts.version); + } + if (opts.generated) { + o.set_generated(*opts.generated); + } + if (opts.compress) { + o.set_compress(*opts.compress); + } + if (opts.sender_identity) { + o.set_sender_identity(*opts.sender_identity); + } + } + + static void fillByteOptions(proto::StreamByteOptions& o, const PeerByteOptions& opts) { + o.set_topic(opts.topic); + for (const auto& kv : opts.attributes) { + (*o.mutable_attributes())[kv.first] = kv.second; + } + for (const auto& d : opts.destination_identities) { + o.add_destination_identities(d); + } + if (opts.stream_id) { + o.set_id(*opts.stream_id); + } + if (opts.name) { + o.set_name(*opts.name); + } + if (opts.mime_type) { + o.set_mime_type(*opts.mime_type); + } + if (opts.total_length) { + o.set_total_length(*opts.total_length); + } + if (opts.compress) { + o.set_compress(*opts.compress); + } + if (opts.sender_identity) { + o.set_sender_identity(*opts.sender_identity); + } + } + + /// Sends `req` and waits for the callback `extract` recognizes. + static PeerResult call(const proto::FfiRequest& req, std::uint64_t async_id, const Extract& extract) { + struct Waiter { + std::mutex mutex; + std::condition_variable cv; + std::optional result; + }; + auto waiter = std::make_shared(); + const auto listener = FfiClient::instance().addListener([waiter, extract, async_id](const proto::FfiEvent& e) { + auto res = extract(e, async_id); + if (!res) { + return; + } + { + const std::scoped_lock lock(waiter->mutex); + waiter->result = std::move(res); + } + waiter->cv.notify_all(); + }); + + PeerResult out; + try { + (void)FfiClient::instance().sendRequest(req); + std::unique_lock lock(waiter->mutex); + if (waiter->cv.wait_for(lock, 30s, [&] { return waiter->result.has_value(); })) { + out = *waiter->result; + } else { + out.error = "timed out waiting for the FFI callback"; + } + } catch (const std::exception& e) { + out.error = e.what(); + } + FfiClient::instance().removeListener(listener); + return out; + } + + std::uint64_t participant_handle_; + std::string identity_; +}; + +// --------------------------------------------------------------------------- +// Receive side: public C++ API +// --------------------------------------------------------------------------- + +/// One stream as received through the public C++ API. +template +struct ReceivedStream { + std::string sender; + Info info; + std::string content; + std::size_t chunk_count = 0; + bool errored = false; + std::string error; +}; + +/// Registers a stream handler on `topic` and reads every stream that arrives +/// on its own thread. Readers that never end (e.g. a stream the SDK failed to +/// decode) leave their thread blocked; such threads are detached on +/// destruction, since the reader cannot be unblocked without API that only +/// exists after the FFI reader port. +template +class StreamCollector { +public: + StreamCollector() : state_(std::make_shared()) {} + + ~StreamCollector() { + if (room_ != nullptr) { + unregister(*room_, topic_); + } + std::vector threads; + { + const std::scoped_lock lock(state_->mutex); + threads.swap(state_->threads); + } + for (auto& t : threads) { + // Give readers a moment to finish, then detach the stragglers. + if (waitDone(t.get_id(), 2s)) { + t.join(); + } else { + t.detach(); + } + } + } + + StreamCollector(const StreamCollector&) = delete; + StreamCollector& operator=(const StreamCollector&) = delete; + StreamCollector(StreamCollector&&) = delete; + StreamCollector& operator=(StreamCollector&&) = delete; + + void registerOn(Room& room, const std::string& topic) { + room_ = &room; + topic_ = topic; + registerHandler(room, topic, [state = state_](std::shared_ptr reader, const std::string& identity) { + const std::scoped_lock lock(state->mutex); + state->threads.emplace_back([state, reader, identity] { read(*state, reader, identity); }); + }); + } + + /// Waits until `count` streams have finished (successfully or with an error). + bool waitFor(std::size_t count, std::chrono::milliseconds timeout = kStreamTimeout) const { + std::unique_lock lock(state_->mutex); + return state_->cv.wait_for(lock, timeout, [&] { return state_->finished.size() >= count; }); + } + + /// Waits until `count` streams have been opened (handler invoked). + bool waitForOpened(std::size_t count, std::chrono::milliseconds timeout = kStreamTimeout) const { + std::unique_lock lock(state_->mutex); + return state_->cv.wait_for(lock, timeout, [&] { return state_->opened >= count; }); + } + + std::size_t openedCount() const { + const std::scoped_lock lock(state_->mutex); + return state_->opened; + } + + std::vector> streams() const { + const std::scoped_lock lock(state_->mutex); + return state_->finished; + } + + /// The single finished stream; fails the test if there is not exactly one. + ReceivedStream only() const { + auto all = streams(); + EXPECT_EQ(all.size(), 1U); + return all.empty() ? ReceivedStream{} : all.front(); + } + +private: + struct State { + std::mutex mutex; + std::condition_variable cv; + std::vector threads; + std::vector done_threads; + std::vector> finished; + std::size_t opened = 0; + }; + + static void read(State& state, const std::shared_ptr& reader, const std::string& identity) { + { + const std::scoped_lock lock(state.mutex); + ++state.opened; + } + state.cv.notify_all(); + + ReceivedStream out; + out.sender = identity; + try { + Chunk chunk; + while (reader->readNext(chunk)) { + out.content.append(chunk.begin(), chunk.end()); + ++out.chunk_count; + } + } catch (const std::exception& e) { + out.errored = true; + out.error = e.what(); + } + // Read info after the stream ends so trailer attributes are included. + out.info = reader->info(); + { + const std::scoped_lock lock(state.mutex); + state.finished.push_back(std::move(out)); + state.done_threads.push_back(std::this_thread::get_id()); + } + state.cv.notify_all(); + } + + bool waitDone(std::thread::id id, std::chrono::milliseconds timeout) const { + std::unique_lock lock(state_->mutex); + return state_->cv.wait_for(lock, timeout, [&] { + for (const auto& d : state_->done_threads) { + if (d == id) { + return true; + } + } + return false; + }); + } + + using Chunk = std::conditional_t, std::string, std::vector>; + + template + static void registerHandler(Room& room, const std::string& topic, H handler) { + if constexpr (std::is_same_v) { + room.registerTextStreamHandler(topic, std::move(handler)); + } else { + room.registerByteStreamHandler(topic, std::move(handler)); + } + } + + static void unregister(Room& room, const std::string& topic) { + if constexpr (std::is_same_v) { + room.unregisterTextStreamHandler(topic); + } else { + room.unregisterByteStreamHandler(topic); + } + } + + std::shared_ptr state_; + Room* room_ = nullptr; + std::string topic_; +}; + +using TextStreamCollector = StreamCollector; +using ByteStreamCollector = StreamCollector; + +/// Base fixture: two connected rooms (A sends, B receives) per test. +class DataStreamConformanceTest : public LiveKitTestBase { +protected: + void SetUp() override { + LiveKitTestBase::SetUp(); + skipIfNotConfigured(); + if (IsSkipped()) { + return; + } + rooms_ = testRooms(2); + } + + void TearDown() override { + rooms_.clear(); + LiveKitTestBase::TearDown(); + } + + Room& senderRoom() { return *rooms_[0]; } + Room& receiverRoom() { return *rooms_[1]; } + std::string senderIdentity() { return identityOf(senderRoom()); } + std::string receiverIdentity() { return identityOf(receiverRoom()); } + + std::vector> rooms_; +}; + +} // namespace livekit::test::ds diff --git a/src/tests/common/room_test_access.h b/src/tests/common/room_test_access.h index 9509b00c..bb1c4baa 100644 --- a/src/tests/common/room_test_access.h +++ b/src/tests/common/room_test_access.h @@ -18,6 +18,7 @@ #include +#include #include #include #include @@ -33,6 +34,13 @@ struct RoomTestAccess { return room.listener_id_; } + /// FFI handle id of the connected room, used to match `room_event`s to this + /// room when several rooms share the process. Returns 0 when disconnected. + static std::uint64_t roomHandleId(const Room& room) { + const std::scoped_lock guard(room.lock_); + return room.room_handle_ ? room.room_handle_->get() : 0; + } + static void simulateScenario(Room& room, proto::SimulateScenarioKind scenario) { std::shared_ptr handle; { From 410f0123811b7f592179b632c7c66146182b991d Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 23 Nov 2026 08:52:42 +1300 Subject: [PATCH 02/11] Add receive-side conformance tests for v1 data streams Ports the incoming-manager tests that a v1 (multi-packet, uncompressed) sender can reproduce: round trips, trailer attribute merging, too few / too many bytes against total_length, duplicate and empty chunks, chunk gaps, trailer reasons, orphan packets, remote stream writers, and sender or receiver disconnects mid-stream. On main, 12 of these 17 tests fail: the C++ receive path appends duplicate chunks, never surfaces length/gap/reason errors, and leaves streams open when a participant disconnects. Co-Authored-By: Claude Opus 5.5 --- ...est_data_stream_conformance_receive_v1.cpp | 452 ++++++++++++++++++ 1 file changed, 452 insertions(+) create mode 100644 src/tests/integration/test_data_stream_conformance_receive_v1.cpp diff --git a/src/tests/integration/test_data_stream_conformance_receive_v1.cpp b/src/tests/integration/test_data_stream_conformance_receive_v1.cpp new file mode 100644 index 00000000..8e9c899a --- /dev/null +++ b/src/tests/integration/test_data_stream_conformance_receive_v1.cpp @@ -0,0 +1,452 @@ +/* + * 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. + */ + +// Receive-side data stream conformance, v1 (multi-packet, uncompressed) +// streams: a remote participant sends streams exactly as another SDK would, +// and the C++ SDK must receive them correctly. Covers hand-built v1 packets, +// remote stream writers, and participant disconnects mid-stream. +// +// 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: it drives the sender room's participant through +// the raw FFI, so its one-shot sends go through the Rust outgoing manager and +// use data streams v2 (inline and compressed packets) just like the Python or +// Rust SDKs, and its raw requests send hand-built v1 packets. The C++ side +// receives through the public API (stream handlers + readers) only. +// +// See data_stream_conformance.md for the full Rust-test -> C++-test mapping, +// including the Rust tests that cannot be expressed from the C++ layer. +// +// Run with: +// ./build-debug/bin/livekit_integration_tests --gtest_filter=DataStreamReceiveV1* + +#include + +#include +#include +#include + +#include "../common/data_stream_test_utils.h" + +namespace livekit::test::ds { + +class DataStreamReceiveV1Test : public DataStreamConformanceTest {}; + +// --------------------------------------------------------------------------- +// v1 multi-packet streams (hand-built header / chunk / trailer packets) +// --------------------------------------------------------------------------- + +// Rust: v1_text_stream_round_trips +TEST_F(DataStreamReceiveV1Test, V1TextStreamRoundTrips) { + const auto topic = uniqueTopic("v1_text"); + const auto sid = uniqueStreamId("v1_text"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + ASSERT_TRUE(peer.sendRawHeader({sid, topic, "text/plain", 11, {{"foo", "bar"}}}).ok); + ASSERT_TRUE(peer.sendRawChunk(sid, 0, "hello world").ok); + ASSERT_TRUE(peer.sendRawTrailer(sid).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, "hello world"); + EXPECT_EQ(s.sender, peer.identity()); + EXPECT_EQ(s.info.stream_id, sid); + EXPECT_EQ(s.info.topic, topic); + EXPECT_EQ(s.info.mime_type, "text/plain"); + ASSERT_TRUE(s.info.size.has_value()); + EXPECT_EQ(*s.info.size, 11U); + EXPECT_EQ(s.info.attributes.at("foo"), "bar"); +} + +// Rust: v1_byte_stream_round_trips +TEST_F(DataStreamReceiveV1Test, V1ByteStreamRoundTrips) { + const auto topic = uniqueTopic("v1_bytes"); + const auto sid = uniqueStreamId("v1_bytes"); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerRawHeader header{sid, topic, "application/octet-stream", 4}; + header.is_text = false; + header.name = "file"; + ASSERT_TRUE(peer.sendRawHeader(header).ok); + ASSERT_TRUE(peer.sendRawChunk(sid, 0, std::string("\x01\x02\x03\x04", 4)).ok); + ASSERT_TRUE(peer.sendRawTrailer(sid).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, std::string("\x01\x02\x03\x04", 4)); + EXPECT_EQ(s.info.name, "file"); + EXPECT_EQ(s.info.mime_type, "application/octet-stream"); +} + +// Rust: v1_merges_trailer_attributes, v1_trailer_attributes_merged_after_close +TEST_F(DataStreamReceiveV1Test, V1TrailerAttributesMergedAfterClose) { + const auto topic = uniqueTopic("v1_trailer_attrs"); + const auto sid = uniqueStreamId("v1_trailer_attrs"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + ASSERT_TRUE(peer.sendRawHeader({sid, topic, "text/plain", 11, {{"foo", "bar"}, {"baz", "quux"}}}).ok); + ASSERT_TRUE(peer.sendRawChunk(sid, 0, "hello world").ok); + ASSERT_TRUE(peer.sendRawTrailer(sid, "", {{"hello", "world"}, {"foo", "updated"}}).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, "hello world"); + const std::map expected{{"baz", "quux"}, {"hello", "world"}, {"foo", "updated"}}; + EXPECT_EQ(s.info.attributes, expected) << "trailer attributes are merged over the header's"; +} + +// Rust: v1_errors_when_too_few_bytes +TEST_F(DataStreamReceiveV1Test, V1ErrorsWhenTooFewBytes) { + const auto topic = uniqueTopic("v1_too_few"); + const auto sid = uniqueStreamId("v1_too_few"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + ASSERT_TRUE(peer.sendRawHeader({sid, topic, "text/plain", 5}).ok); + ASSERT_TRUE(peer.sendRawChunk(sid, 0, "x").ok); + ASSERT_TRUE(peer.sendRawTrailer(sid).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_TRUE(s.errored) << "a stream shorter than its declared total_length must fail"; + EXPECT_NE(s.error.find("incomplete"), std::string::npos) << s.error; +} + +// Rust: v1_errors_when_too_many_bytes +TEST_F(DataStreamReceiveV1Test, V1ErrorsWhenTooManyBytes) { + const auto topic = uniqueTopic("v1_too_many"); + const auto sid = uniqueStreamId("v1_too_many"); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerRawHeader header{sid, topic, "application/octet-stream", 3}; + header.is_text = false; + ASSERT_TRUE(peer.sendRawHeader(header).ok); + ASSERT_TRUE(peer.sendRawChunk(sid, 0, std::string("\x01\x02\x03\x04\x05", 5)).ok); + ASSERT_TRUE(peer.sendRawTrailer(sid).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_TRUE(s.errored) << "a stream longer than its declared total_length must fail"; + EXPECT_NE(s.error.find("exceeded total length"), std::string::npos) << s.error; +} + +// Rust: v1_duplicate_chunk_dropped +TEST_F(DataStreamReceiveV1Test, V1DuplicateChunkDropped) { + const auto topic = uniqueTopic("v1_dup"); + const auto sid = uniqueStreamId("v1_dup"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + ASSERT_TRUE(peer.sendRawHeader({sid, topic, "text/plain", 10}).ok); + ASSERT_TRUE(peer.sendRawChunk(sid, 0, "hello").ok); + ASSERT_TRUE(peer.sendRawChunk(sid, 0, "hello").ok); + ASSERT_TRUE(peer.sendRawChunk(sid, 1, "world").ok); + ASSERT_TRUE(peer.sendRawTrailer(sid).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, "helloworld"); +} + +// Rust: empty_chunks_are_ignored +TEST_F(DataStreamReceiveV1Test, EmptyChunksAreIgnored) { + const auto topic = uniqueTopic("v1_empty_chunk"); + const auto sid = uniqueStreamId("v1_empty_chunk"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + ASSERT_TRUE(peer.sendRawHeader({sid, topic, "text/plain", 11}).ok); + ASSERT_TRUE(peer.sendRawChunk(sid, 0, "").ok); + ASSERT_TRUE(peer.sendRawChunk(sid, 1, "hello world").ok); + ASSERT_TRUE(peer.sendRawTrailer(sid).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, "hello world"); +} + +// Rust: error_close_emits_stream_closed (MissedChunk) +TEST_F(DataStreamReceiveV1Test, V1MissedChunkErrors) { + const auto topic = uniqueTopic("v1_gap"); + const auto sid = uniqueStreamId("v1_gap"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + ASSERT_TRUE(peer.sendRawHeader({sid, topic, "text/plain", 10}).ok); + ASSERT_TRUE(peer.sendRawChunk(sid, 5, "hello").ok); + ASSERT_TRUE(peer.sendRawTrailer(sid).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_TRUE(s.errored) << "a chunk index gap must fail the stream"; + EXPECT_NE(s.error.find("chunk index"), std::string::npos) << s.error; +} + +// Rust: trailer_with_reason_errors_abnormal_end +TEST_F(DataStreamReceiveV1Test, V1TrailerWithReasonErrorsAbnormalEnd) { + const auto topic = uniqueTopic("v1_reason"); + const auto sid = uniqueStreamId("v1_reason"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + ASSERT_TRUE(peer.sendRawHeader({sid, topic, "text/plain", 10}).ok); + ASSERT_TRUE(peer.sendRawChunk(sid, 0, "hello").ok); + ASSERT_TRUE(peer.sendRawTrailer(sid, "cancelled").ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_TRUE(s.errored) << "a trailer with a reason ends the stream abnormally"; + EXPECT_NE(s.error.find("stream closed abnormally: cancelled"), std::string::npos) + << "the reason takes precedence over Incomplete: " << s.error; +} + +// Rust: chunk_for_an_unopened_stream_reports_no_topic, +// trailer_for_unopened_stream_emits_no_stream_closed +TEST_F(DataStreamReceiveV1Test, OrphanChunkAndTrailerAreIgnored) { + const auto topic = uniqueTopic("orphans"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + ASSERT_TRUE(peer.sendRawChunk(uniqueStreamId("never_opened"), 0, "hi").ok); + ASSERT_TRUE(peer.sendRawTrailer(uniqueStreamId("never_opened")).ok); + PeerTextOptions opts; + opts.topic = topic; + ASSERT_TRUE(peer.sendText("hi", opts).ok); + + ASSERT_TRUE(collector.waitFor(1)); + std::this_thread::sleep_for(kQuietPeriod); + ASSERT_EQ(collector.streams().size(), 1U) << "orphan packets must not open a stream"; + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, "hi"); +} + +// --------------------------------------------------------------------------- +// Remote stream writers (chunked, uncompressed, incremental) +// --------------------------------------------------------------------------- + +// Rust: v1_merges_trailer_attributes via a writer (close_with_options), +// progress_reports_completion_uncompressed_bytes (three writes) +TEST_F(DataStreamReceiveV1Test, RemoteTextWriterRoundTripsWithTrailerAttributes) { + const auto topic = uniqueTopic("remote_writer"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerTextOptions opts; + opts.topic = topic; + opts.attributes = {{"foo", "bar"}}; + const auto writer = peer.openText(opts); + ASSERT_TRUE(writer.ok) << writer.error; + ASSERT_TRUE(peer.writeText(writer.writer_handle, "hello ").ok); + ASSERT_TRUE(peer.writeText(writer.writer_handle, "streaming ").ok); + ASSERT_TRUE(peer.writeText(writer.writer_handle, "world").ok); + ASSERT_TRUE(peer.closeText(writer.writer_handle, "", {{"result", "ok"}, {"foo", "updated"}}).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, "hello streaming world"); + EXPECT_EQ(s.info.stream_id, writer.stream_id); + const std::map expected{{"foo", "updated"}, {"result", "ok"}}; + EXPECT_EQ(s.info.attributes, expected); +} + +// Rust: trailer_with_reason_errors_abnormal_end via a writer (close_with_reason) +TEST_F(DataStreamReceiveV1Test, RemoteWriterCloseWithReasonErrorsAbnormalEnd) { + const auto topic = uniqueTopic("remote_reason"); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerByteOptions opts; + opts.topic = topic; + opts.name = "upload.bin"; + const auto writer = peer.openBytes(opts); + ASSERT_TRUE(writer.ok) << writer.error; + ASSERT_TRUE(peer.writeBytes(writer.writer_handle, "partial").ok); + ASSERT_TRUE(peer.closeBytes(writer.writer_handle, "aborted", {{"cause", "cancelled"}}).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_TRUE(s.errored) << "a close reason ends the stream abnormally"; + EXPECT_NE(s.error.find("aborted"), std::string::npos) << s.error; +} + +// Rust: v1_errors_when_too_few_bytes via a writer (declared total_length) +TEST_F(DataStreamReceiveV1Test, RemoteWriterTooFewBytesErrors) { + const auto topic = uniqueTopic("remote_too_few"); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerByteOptions opts; + opts.topic = topic; + opts.name = "short.bin"; + opts.total_length = 5; + const auto writer = peer.openBytes(opts); + ASSERT_TRUE(writer.ok) << writer.error; + ASSERT_TRUE(peer.writeBytes(writer.writer_handle, "x").ok); + ASSERT_TRUE(peer.closeBytes(writer.writer_handle).ok); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_TRUE(s.errored) << "a stream shorter than its declared total_length must fail"; + EXPECT_NE(s.error.find("incomplete"), std::string::npos) << s.error; +} + +// Rust: v1_errors_when_too_many_bytes via a writer (declared total_length) +TEST_F(DataStreamReceiveV1Test, RemoteWriterTooManyBytesErrors) { + const auto topic = uniqueTopic("remote_too_many"); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerByteOptions opts; + opts.topic = topic; + opts.name = "long.bin"; + opts.total_length = 3; + const auto writer = peer.openBytes(opts); + ASSERT_TRUE(writer.ok) << writer.error; + ASSERT_TRUE(peer.writeBytes(writer.writer_handle, "12345").ok); + (void)peer.closeBytes(writer.writer_handle); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_TRUE(s.errored) << "a stream longer than its declared total_length must fail"; + EXPECT_NE(s.error.find("exceeded total length"), std::string::npos) << s.error; +} + +// --------------------------------------------------------------------------- +// Disconnects +// --------------------------------------------------------------------------- + +// Rust: errors_open_streams_on_sender_disconnect, abort_emits_stream_closed +TEST_F(DataStreamReceiveV1Test, SenderDisconnectErrorsOpenStreams) { + const auto topic = uniqueTopic("sender_gone"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerTextOptions opts; + opts.topic = topic; + const auto writer = peer.openText(opts); + ASSERT_TRUE(writer.ok) << writer.error; + ASSERT_TRUE(peer.writeText(writer.writer_handle, "hello").ok); + ASSERT_TRUE(collector.waitForOpened(1)); + + // The sender leaves mid-stream. + rooms_[0].reset(); + + ASSERT_TRUE(collector.waitFor(1)) << "a stream whose sender disconnected must end"; + const auto s = collector.only(); + EXPECT_TRUE(s.errored) << "a stream whose sender disconnected must end with an error"; + EXPECT_NE(s.error.find("unexpectedly disconnected"), std::string::npos) << s.error; +} + +// Rust: shutdown_errors_open_streams, dropping_all_inputs_errors_open_streams +TEST_F(DataStreamReceiveV1Test, ReceiverDisconnectErrorsOpenStreams) { + const auto text_topic = uniqueTopic("receiver_gone_text"); + const auto byte_topic = uniqueTopic("receiver_gone_bytes"); + TextStreamCollector text_collector; + text_collector.registerOn(receiverRoom(), text_topic); + ByteStreamCollector byte_collector; + byte_collector.registerOn(receiverRoom(), byte_topic); + FfiPeer peer(senderRoom()); + + PeerTextOptions text_opts; + text_opts.topic = text_topic; + const auto text_writer = peer.openText(text_opts); + ASSERT_TRUE(text_writer.ok) << text_writer.error; + ASSERT_TRUE(peer.writeText(text_writer.writer_handle, "hello").ok); + PeerByteOptions byte_opts; + byte_opts.topic = byte_topic; + byte_opts.name = "pending.bin"; + const auto byte_writer = peer.openBytes(byte_opts); + ASSERT_TRUE(byte_writer.ok) << byte_writer.error; + ASSERT_TRUE(peer.writeBytes(byte_writer.writer_handle, "hello").ok); + ASSERT_TRUE(text_collector.waitForOpened(1)); + ASSERT_TRUE(byte_collector.waitForOpened(1)); + + // The receiver leaves while both streams are open. + (void)receiverRoom().disconnect(); + + ASSERT_TRUE(text_collector.waitFor(1)) << "open text stream must end when the receiver disconnects"; + ASSERT_TRUE(byte_collector.waitFor(1)) << "open byte stream must end when the receiver disconnects"; + EXPECT_TRUE(text_collector.only().errored); + EXPECT_TRUE(byte_collector.only().errored); + + (void)peer.closeText(text_writer.writer_handle); + (void)peer.closeBytes(byte_writer.writer_handle); +} + +// Rust: abort_only_affects_matching_sender +TEST_F(DataStreamReceiveV1Test, SenderDisconnectOnlyAffectsItsOwnStreams) { + rooms_.clear(); + auto rooms = threeTestRooms(); + if (rooms.empty()) { + GTEST_SKIP() << "LIVEKIT_TOKEN_C not set"; + } + const auto topic = uniqueTopic("abort_scope"); + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + FfiPeer leaving(*rooms[0]); + FfiPeer staying(*rooms[2]); + + PeerTextOptions opts; + opts.topic = topic; + const auto leaving_writer = leaving.openText(opts); + const auto staying_writer = staying.openText(opts); + ASSERT_TRUE(leaving_writer.ok && staying_writer.ok); + ASSERT_TRUE(leaving.writeText(leaving_writer.writer_handle, "doomed").ok); + ASSERT_TRUE(staying.writeText(staying_writer.writer_handle, "hello").ok); + ASSERT_TRUE(collector.waitForOpened(2)); + + rooms[0].reset(); + ASSERT_TRUE(collector.waitFor(1)); + ASSERT_TRUE(staying.closeText(staying_writer.writer_handle).ok); + ASSERT_TRUE(collector.waitFor(2)); + + for (const auto& s : collector.streams()) { + if (s.sender == staying.identity()) { + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, "hello"); + } else { + EXPECT_TRUE(s.errored) << "the departed sender's stream must end with an error"; + } + } +} + +} // namespace livekit::test::ds From c9aead9f87a7ef4fd2c99c9ca879210635473ebc Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 23 Nov 2026 08:52:42 +1300 Subject: [PATCH 03/11] Add receive-side conformance tests for v2 data streams Ports the incoming-manager tests for data streams v2 as sent by other SDKs: inline streams (compressed and uncompressed, empty, large but highly compressible), multi-packet compressed text and byte streams, UTF-8 reframing of decompressed text, and text streams with attachments. All 10 fail on main: inline streams are never delivered and compressed chunks are delivered as raw deflate bytes. Co-Authored-By: Claude Opus 5.5 --- ...est_data_stream_conformance_receive_v2.cpp | 391 ++++++++++++++++++ 1 file changed, 391 insertions(+) create mode 100644 src/tests/integration/test_data_stream_conformance_receive_v2.cpp diff --git a/src/tests/integration/test_data_stream_conformance_receive_v2.cpp b/src/tests/integration/test_data_stream_conformance_receive_v2.cpp new file mode 100644 index 00000000..d66915ae --- /dev/null +++ b/src/tests/integration/test_data_stream_conformance_receive_v2.cpp @@ -0,0 +1,391 @@ +/* + * 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. + */ + +// Receive-side data stream conformance, v2 streams: a remote participant +// sends inline (single-packet) and compressed streams exactly as another SDK +// would, and the C++ SDK must receive them correctly. +// +// 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: it drives the sender room's participant through +// the raw FFI, so its one-shot sends go through the Rust outgoing manager and +// use data streams v2 (inline and compressed packets) just like the Python or +// Rust SDKs, and its raw requests send hand-built v1 packets. The C++ side +// receives through the public API (stream handlers + readers) only. +// +// See data_stream_conformance.md for the full Rust-test -> C++-test mapping, +// including the Rust tests that cannot be expressed from the C++ layer. +// +// Run with: +// ./build-debug/bin/livekit_integration_tests --gtest_filter=DataStreamReceiveV2* + +#include + +#include +#include +#include +#include +#include + +#include "../common/data_stream_test_utils.h" + +namespace livekit::test::ds { + +namespace { + +/// Expects the stream on `topic` to have arrived as a single inline header +/// packet: a header and no chunk or trailer packets. +void expectInline(const RawPacketSniffer& sniffer, const std::string& topic) { + const auto header = sniffer.waitForHeader(topic); + ASSERT_TRUE(header.has_value()) << "no raw header received"; + // Any chunk or trailer would have arrived with (before) the reader's end. + std::this_thread::sleep_for(300ms); + EXPECT_TRUE(sniffer.chunks(header->stream_id).empty()) << "inline stream must not send chunk packets"; + EXPECT_TRUE(sniffer.trailers(header->stream_id).empty()) << "inline stream must not send a trailer packet"; +} + +/// Expects the stream on `topic` to have arrived as compressed chunk packets: +/// raw chunk bytes that are not the plaintext and are smaller than it. +void expectCompressedChunks(const RawPacketSniffer& sniffer, const std::string& topic, const std::string& plaintext) { + const auto header = sniffer.waitForHeader(topic); + ASSERT_TRUE(header.has_value()) << "no raw header received"; + ASSERT_TRUE(sniffer.waitForTrailer(header->stream_id).has_value()) << "no raw trailer received"; + const auto chunks = sniffer.chunks(header->stream_id); + EXPECT_GE(chunks.size(), 2U); + const auto raw = sniffer.rawContent(header->stream_id); + EXPECT_NE(raw, plaintext) << "chunk content should be compressed"; + EXPECT_LT(raw.size(), plaintext.size()); + ASSERT_TRUE(header->total_length.has_value()); + EXPECT_EQ(*header->total_length, plaintext.size()) << "total_length is the uncompressed length"; +} + +/// Text of pseudo-random CJK ideographs (3 bytes each in UTF-8): high +/// entropy, so it compresses only modestly and is sent as compressed chunks, +/// and chunk boundaries of the compressed stream fall mid-character. +std::string randomCjkText(std::size_t approx_bytes) { + const std::string seed_bytes = randomBytes(approx_bytes / 3 * 2, 0xC0FFEE); + std::string out; + out.reserve(approx_bytes + 3); + for (std::size_t i = 0; i + 1 < seed_bytes.size(); i += 2) { + const auto v = static_cast(static_cast(seed_bytes[i])) << 8 | + static_cast(seed_bytes[i + 1]); + const std::uint32_t cp = 0x4E00 + (v % 0x5000); // CJK Unified Ideographs + out += static_cast(0xE0 | (cp >> 12)); + out += static_cast(0x80 | ((cp >> 6) & 0x3F)); + out += static_cast(0x80 | (cp & 0x3F)); + } + return out; +} + +} // namespace + +class DataStreamReceiveV2Test : public DataStreamConformanceTest {}; + +// --------------------------------------------------------------------------- +// v2 inline streams (single header packet carrying the payload) +// --------------------------------------------------------------------------- + +// Rust: v2_inline_uncompressed_text, inline_stream_emits_stream_closed, +// inline_streams_are_never_counted +TEST_F(DataStreamReceiveV2Test, V2InlineUncompressedText) { + const auto topic = uniqueTopic("v2_inline_text"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerTextOptions opts; + opts.topic = topic; + opts.attributes = {{"foo", "bar"}}; + // "inline hello" does not shrink under deflate, so it is inlined raw. + ASSERT_TRUE(peer.sendText("inline hello", opts).ok); + + ASSERT_TRUE(collector.waitFor(1)) << "inline v2 stream was never delivered"; + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, "inline hello"); + EXPECT_EQ(s.sender, peer.identity()); + EXPECT_EQ(s.info.attributes.at("foo"), "bar"); + ASSERT_TRUE(s.info.size.has_value()); + EXPECT_EQ(*s.info.size, 12U); + expectInline(sniffer, topic); +} + +// Rust: v2_inline_uncompressed_byte +TEST_F(DataStreamReceiveV2Test, V2InlineUncompressedByte) { + const auto topic = uniqueTopic("v2_inline_bytes"); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerByteOptions opts; + opts.topic = topic; + opts.name = "file"; + ASSERT_TRUE(peer.sendBytes(std::string("\x01\x02\x03", 3), opts).ok); + + ASSERT_TRUE(collector.waitFor(1)) << "inline v2 stream was never delivered"; + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, std::string("\x01\x02\x03", 3)); + EXPECT_EQ(s.info.name, "file"); + expectInline(sniffer, topic); +} + +// Rust: v2_inline_compressed_text +TEST_F(DataStreamReceiveV2Test, V2InlineCompressedText) { + const auto topic = uniqueTopic("v2_inline_ztext"); + const std::string text = "hello hello compressible world"; + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerTextOptions opts; + opts.topic = topic; + opts.attributes = {{"foo", "bar"}}; + ASSERT_TRUE(peer.sendText(text, opts).ok); + + ASSERT_TRUE(collector.waitFor(1)) << "compressed inline v2 stream was never delivered"; + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, text); + EXPECT_EQ(s.info.attributes.at("foo"), "bar"); + expectInline(sniffer, topic); +} + +// Rust: v2_inline_compressed_byte +TEST_F(DataStreamReceiveV2Test, V2InlineCompressedByte) { + const auto topic = uniqueTopic("v2_inline_zbytes"); + std::string payload(2000, '\0'); + for (std::size_t i = 0; i < payload.size(); ++i) { + payload[i] = static_cast(i % 7); + } + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerByteOptions opts; + opts.topic = topic; + ASSERT_TRUE(peer.sendBytes(payload, opts).ok); + + ASSERT_TRUE(collector.waitFor(1)) << "compressed inline v2 stream was never delivered"; + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, payload); + expectInline(sniffer, topic); +} + +// Rust: v2_inline_zero_length_text (and v2_empty_text_sends_single_inline_packet +// from the sending side) +TEST_F(DataStreamReceiveV2Test, V2InlineZeroLengthText) { + const auto topic = uniqueTopic("v2_inline_empty"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerTextOptions opts; + opts.topic = topic; + ASSERT_TRUE(peer.sendText("", opts).ok); + + ASSERT_TRUE(collector.waitFor(1)) << "empty inline v2 stream was never delivered"; + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, ""); + ASSERT_TRUE(s.info.size.has_value()); + EXPECT_EQ(*s.info.size, 0U); + expectInline(sniffer, topic); +} + +// Rust: v2_large_highly_compressible_text_still_inlines (receiving side) +TEST_F(DataStreamReceiveV2Test, V2LargeHighlyCompressibleTextInlines) { + const auto topic = uniqueTopic("v2_inline_large"); + std::string text; + for (int i = 0; i < 20'000; ++i) { + text += "hello world"; + } + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerTextOptions opts; + opts.topic = topic; + ASSERT_TRUE(peer.sendText(text, opts).ok); + + ASSERT_TRUE(collector.waitFor(1)) << "large compressed inline v2 stream was never delivered"; + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content.size(), text.size()); + EXPECT_EQ(s.content, text); + expectInline(sniffer, topic); +} + +// --------------------------------------------------------------------------- +// v2 multi-packet compressed streams +// --------------------------------------------------------------------------- + +// Rust: v2_multipacket_compressed_text, progress_reports_completion_compressed_text +TEST_F(DataStreamReceiveV2Test, V2MultipacketCompressedText) { + const auto topic = uniqueTopic("v2_multi_ztext"); + const auto text = randomText(60'000); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerTextOptions opts; + opts.topic = topic; + ASSERT_TRUE(peer.sendText(text, opts).ok); + + ASSERT_TRUE(collector.waitFor(1)) << "compressed multi-packet v2 stream was never delivered"; + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content.size(), text.size()); + EXPECT_EQ(s.content, text) << "compressed chunks must be decompressed before delivery"; + expectCompressedChunks(sniffer, topic, text); +} + +// Rust: v2_multipacket_compressed_byte_stream +TEST_F(DataStreamReceiveV2Test, V2MultipacketCompressedByteStream) { + const auto topic = uniqueTopic("v2_multi_zbytes"); + const auto payload = randomText(60'000); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerByteOptions opts; + opts.topic = topic; + ASSERT_TRUE(peer.sendBytes(payload, opts).ok); + + ASSERT_TRUE(collector.waitFor(1)) << "compressed multi-packet v2 stream was never delivered"; + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content.size(), payload.size()); + EXPECT_EQ(s.content, payload) << "compressed chunks must be decompressed before delivery"; + expectCompressedChunks(sniffer, topic, payload); +} + +// Rust: v2_compressed_text_reframes_multibyte_utf8. The Rust test hand-splits +// a compressed stream; here the payload is high-entropy multibyte text, so the +// sender emits several compressed chunks whose boundaries fall mid-character +// once decompressed. Every chunk the reader delivers must be valid UTF-8. +TEST_F(DataStreamReceiveV2Test, V2CompressedTextReframesMultibyteUtf8) { + const auto topic = uniqueTopic("v2_utf8"); + const auto text = randomCjkText(60'000); + ASSERT_TRUE(isValidUtf8(text)); + RawPacketSniffer sniffer(receiverRoom()); + // Collect chunks individually to check each is valid UTF-8. + std::mutex mutex; + std::condition_variable cv; + std::vector chunks; + bool done = false; + std::string error; + std::thread reader_thread; + receiverRoom().registerTextStreamHandler(topic, [&](std::shared_ptr reader, const std::string&) { + reader_thread = std::thread([&, reader] { + std::vector local; + std::string local_error; + try { + std::string chunk; + while (reader->readNext(chunk)) { + local.push_back(chunk); + } + } catch (const std::exception& e) { + local_error = e.what(); + } + const std::scoped_lock lock(mutex); + chunks = std::move(local); + error = std::move(local_error); + done = true; + cv.notify_all(); + }); + }); + FfiPeer peer(senderRoom()); + + PeerTextOptions opts; + opts.topic = topic; + ASSERT_TRUE(peer.sendText(text, opts).ok); + + bool finished = false; + { + std::unique_lock lock(mutex); + finished = cv.wait_for(lock, kStreamTimeout, [&] { return done; }); + } + receiverRoom().unregisterTextStreamHandler(topic); + if (!finished) { + if (reader_thread.joinable()) { + reader_thread.detach(); + } + FAIL() << "compressed multibyte v2 stream was never delivered"; + } + reader_thread.join(); + EXPECT_TRUE(error.empty()) << error; + std::string joined; + for (const auto& c : chunks) { + EXPECT_TRUE(isValidUtf8(c)) << "a delivered chunk split a multibyte character"; + joined += c; + } + EXPECT_EQ(joined, text); + expectCompressedChunks(sniffer, topic, text); +} + +// Rust: text_stream_with_attachments_round_trips (and +// v2_send_text_with_attachments_never_inlines from the sending side) +TEST_F(DataStreamReceiveV2Test, TextStreamWithAttachmentsRoundTrips) { + const auto text_topic = uniqueTopic("attach_text"); + const auto byte_topic = uniqueTopic("attach_bytes"); + const auto attachment_id = uniqueStreamId("att"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector text_collector; + text_collector.registerOn(receiverRoom(), text_topic); + ByteStreamCollector byte_collector; + byte_collector.registerOn(receiverRoom(), byte_topic); + FfiPeer peer(senderRoom()); + + PeerTextOptions text_opts; + text_opts.topic = text_topic; + text_opts.attached_stream_ids = {attachment_id}; + ASSERT_TRUE(peer.sendText("hello world", text_opts).ok); + PeerByteOptions byte_opts; + byte_opts.topic = byte_topic; + byte_opts.stream_id = attachment_id; + ASSERT_TRUE(peer.sendBytes(std::string("\x01\x02\x03", 3), byte_opts).ok); + + ASSERT_TRUE(text_collector.waitFor(1)) << "text stream with attachments was never delivered"; + const auto t = text_collector.only(); + EXPECT_FALSE(t.errored) << t.error; + EXPECT_EQ(t.content, "hello world"); + EXPECT_EQ(t.info.attachments, std::vector{attachment_id}); + + ASSERT_TRUE(byte_collector.waitFor(1)) << "attachment byte stream was never delivered"; + const auto b = byte_collector.only(); + EXPECT_FALSE(b.errored) << b.error; + EXPECT_EQ(b.info.stream_id, attachment_id); + EXPECT_EQ(b.content, std::string("\x01\x02\x03", 3)); + + // A text stream with attachments is never inlined. + const auto header = sniffer.waitForHeader(text_topic); + ASSERT_TRUE(header.has_value()); + EXPECT_EQ(header->attached_stream_ids, std::vector{attachment_id}); + EXPECT_TRUE(sniffer.waitForTrailer(header->stream_id).has_value()); + EXPECT_FALSE(sniffer.chunks(header->stream_id).empty()); +} + +} // namespace livekit::test::ds From 329a23ed7c072d4fe5d381824d5ddef8bae77ebb Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Fri, 20 Nov 2026 13:18:00 +1300 Subject: [PATCH 04/11] Port data stream receive path to FFI readers; add sendText/sendBytes/sendFile Incoming data streams were rebuilt from the low-level stream_header/chunk/ trailer events. Since livekit-ffi 0.15.0 always advertises data streams v2, modern senders send C++ participants single-packet and deflate-compressed streams, which that path can't read: inline streams hang readAll() forever and compressed chunks arrive as raw deflate bytes. The FFI also handed C++ an owned reader handle for every incoming stream, which C++ ignored, so every stream's content stayed buffered in the FFI for the life of the process. Receive: - Room consumes text/byte_stream_opened: unhandled topics drop the reader handle; handled topics start read_incremental and route the resulting *_stream_reader_events (keyed by reader handle) to the reader. The low-level stream_*_received events are now ignored. - Readers surface abnormal ends (sender close reason, size limit, disconnect) as DataStreamError after draining buffered chunks, merge end-of-stream attributes into info() on the reading thread, gain close(), and ByteStreamReader gains readAll(). Room shutdown wakes blocked readers. - RoomOptions::data_stream.max_payload_byte_length sets the receive limit. Send: - LocalParticipant::sendText / sendBytes / sendFile use the FFI one-shot sends (compression and single-packet delivery when recipients support them). They throw DataStreamError on failure and refuse to reach the FFI once the room has disconnected, since the FFI panics there. TextStreamOpenedEvent / ByteStreamOpenedEvent::reader_handle stays 0 and is documented as deprecated. Existing writers are unchanged (v1 framing is still accepted by FFI readers). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 4 +- CMakeLists.txt | 2 + README.md | 4 +- include/livekit/data_stream.h | 249 +++++++++-- include/livekit/local_participant.h | 56 +++ include/livekit/room.h | 42 +- include/livekit/room_event_types.h | 12 +- src/data_stream.cpp | 178 +++++--- src/data_stream_proto_converter.cpp | 111 +++++ src/data_stream_proto_converter.h | 45 ++ src/ffi_client.cpp | 148 +++++++ src/ffi_client.h | 23 +- src/local_participant.cpp | 47 +++ src/room.cpp | 317 ++++++++------ src/room_proto_converter.cpp | 11 +- src/tests/integration/test_data_streams.cpp | 435 +++++++++++++++++++- src/tests/unit/test_data_stream.cpp | 307 ++++++++++++++ 17 files changed, 1758 insertions(+), 233 deletions(-) create mode 100644 src/data_stream_proto_converter.cpp create mode 100644 src/data_stream_proto_converter.h diff --git a/AGENTS.md b/AGENTS.md index d9daf703..9901a51a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,7 +56,7 @@ The SDK has three categories of threads: 1. Completes any pending async `std::promise` matched by `async_id`. 2. Invokes all registered `FfiClient` listeners (including `Room::onEvent`). -All `RoomDelegate` callbacks and stream handler callbacks (e.g., `registerTextStreamHandler`) are invoked on this FFI callback thread. **Handlers must not block**; spawn a background thread if synchronous work is needed. +All `RoomDelegate` callbacks and stream handler callbacks (e.g., `registerTextStreamHandler`) are invoked on this FFI callback thread. **Handlers must not block**; spawn a background thread if synchronous work is needed. Incoming data stream chunks are also delivered to `TextStreamReader` / `ByteStreamReader` on this thread (routed by `Room` from `*_stream_reader_event`s keyed by reader handle), so a stream handler must never call `readNext()` / `readAll()` inline; readers log a warning if they would block on the FFI callback thread. **Per-subscription reader threads** — `SubscriptionThreadDispatcher` creates a dedicated `std::thread` for each active audio, video, or data track subscription. These threads block on `AudioStream::read()`, `VideoStream::read()`, or `DataTrackStream::read()` and invoke the registered `AudioFrameCallback`, `VideoFrameCallback`, or `DataFrameCallback` on that reader thread — not on the FFI callback thread. A hard limit of 20 concurrent reader threads is enforced. @@ -76,6 +76,8 @@ 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()`. | +| `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_`. | ### Directory Layout diff --git a/CMakeLists.txt b/CMakeLists.txt index 00d4bd32..17a1fcef 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -422,6 +422,8 @@ add_library(livekit SHARED src/audio_stream.cpp src/data_track_frame.cpp src/data_stream.cpp + src/data_stream_proto_converter.cpp + src/data_stream_proto_converter.h src/data_track_error.cpp src/data_track_schema.cpp src/data_track_stream.cpp diff --git a/README.md b/README.md index 243e1d3a..4bf10eb8 100644 --- a/README.md +++ b/README.md @@ -226,7 +226,9 @@ token source helpers for endpoint, development token server, and custom backends - Dynamic token sourcing (literal, custom, endpoint, development token server, caching) - Receive remote audio/video tracks - Publish local audio/video tracks -- Data tracks (low-level) and data streams (high-level) +- Data tracks (low-level) and data streams (high-level): one-shot `sendText` / + `sendBytes` / `sendFile` with compression, incremental writers, and + per-topic stream handlers - 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 173b8b0d..8d02b41c 100644 --- a/include/livekit/data_stream.h +++ b/include/livekit/data_stream.h @@ -24,6 +24,7 @@ #include #include #include +#include #include #include @@ -38,6 +39,100 @@ class LocalParticipant; /// channels. constexpr std::size_t kStreamChunkSize = 15'000; // 15 KB +/// @brief Error raised by data stream operations. +/// +/// Thrown by the one-shot send APIs (for example +/// 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 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 +/// `catch (const std::runtime_error&)` handlers keep working. +class LIVEKIT_API DataStreamError : public std::runtime_error { +public: + /// @brief Construct an error with a description. + /// @param message Human-readable error description. + explicit DataStreamError(const std::string& message); +}; + +/// @brief Options for a one-shot text send or an incremental text stream. +/// +/// Used by LocalParticipant::sendText(). +struct StreamTextOptions { + /// Application-defined topic. Required; receivers route streams to handlers + /// registered with Room::registerTextStreamHandler() by topic. + std::string topic; + + /// Arbitrary key/value attributes sent with the stream header. + std::map attributes; + + /// Identities of the participants that should receive the stream. Empty + /// means every participant in the room. + std::vector destination_identities; + + /// Stream id to use. A unique id is generated when unset. + std::optional stream_id; + + /// Id of the stream this stream replies to, if any. + std::optional reply_to_stream_id; + + /// Ids of other streams (for example files) attached to this text stream. + std::vector attached_stream_ids; + + /// Compress the payload when every recipient supports compression. + /// + /// Only one-shot sends compress; incremental writers ignore this flag. + bool compress = true; + + /// Identity to send as. Leave unset to send as the local participant; + /// setting it requires the impersonation permission. + std::optional sender_identity; +}; + +/// @brief Options for a one-shot byte/file send or an incremental byte stream. +/// +/// Used by LocalParticipant::sendBytes() and LocalParticipant::sendFile(). +struct StreamByteOptions { + /// Application-defined topic. Required; receivers route streams to handlers + /// registered with Room::registerByteStreamHandler() by topic. + std::string topic; + + /// Arbitrary key/value attributes sent with the stream header. + std::map attributes; + + /// Identities of the participants that should receive the stream. Empty + /// means every participant in the room. + std::vector destination_identities; + + /// Stream id to use. A unique id is generated when unset. + std::optional stream_id; + + /// Name of the payload (for example a file name). When unset, sendBytes() + /// uses the SDK default ("unknown") and sendFile() uses the file's basename. + std::optional name; + + /// MIME type of the payload. When unset, the SDK picks a default + /// ("application/octet-stream" for bytes; derived from the file for + /// sendFile()). + std::optional mime_type; + + /// Total payload size in bytes, if known. Only meaningful for incremental + /// writers; one-shot sends always know their size. + std::optional total_length; + + /// Compress the payload when every recipient supports compression. + /// + /// Only one-shot sends compress; incremental writers ignore this flag. Turn + /// it off for payloads that are already compressed (images, video, archives). + bool compress = true; + + /// Identity to send as. Leave unset to send as the local participant; + /// setting it requires the impersonation permission. + std::optional sender_identity; +}; + /// Base metadata for any stream (text or bytes). struct BaseStreamInfo { /// Unique identifier for this stream. @@ -77,80 +172,156 @@ struct ByteStreamInfo : BaseStreamInfo { // - TextStreamReader: yields UTF-8 text chunks (std::string) // - ByteStreamReader: yields raw bytes (std::vector) -/// Reader for incoming text streams. -/// Created internally by the SDK when a text stream header is received. +/// @brief Reader for incoming text streams. +/// +/// Created by the SDK when a remote participant opens a text stream on a topic +/// with a handler registered via Room::registerTextStreamHandler(). The SDK +/// decompresses and reassembles the stream; each chunk is valid UTF-8. +/// +/// 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. class LIVEKIT_API TextStreamReader { public: - /// Construct a reader from initial stream metadata. + /// @brief Construct a detached reader from stream metadata. + /// + /// A reader built this way is not connected to any incoming stream and + /// never receives data. Readers for real streams are created by the SDK. + /// @param info Stream metadata. explicit TextStreamReader(TextStreamInfo info); + ~TextStreamReader(); TextStreamReader(const TextStreamReader&) = delete; TextStreamReader& operator=(const TextStreamReader&) = delete; - /// Blocking read of next text chunk. - /// Returns false when the stream has ended. + /// @brief Blocking read of the next text chunk. + /// + /// When the stream ends normally, any final attributes the sender attached + /// on close are merged into info().attributes before this returns false. + /// + /// @param out Receives the next chunk. + /// @return True if a chunk was read; false when the stream has ended or + /// close() was called. + /// @throws DataStreamError if the stream ended abnormally (for example the + /// sender closed it with a reason, it exceeded the receive size + /// limit, or the room disconnected mid-stream). Chunks received + /// before the error are returned first. bool readNext(std::string& out); - /// Convenience: read entire stream into a single string. - /// Blocks until the stream is closed. + /// @brief Read the entire stream into a single string. + /// + /// Blocks until the stream ends. + /// + /// @return The concatenated text. + /// @throws DataStreamError if the stream ended abnormally. std::string readAll(); - /// Metadata associated with this stream. + /// @brief Stop reading early. + /// + /// Discards buffered chunks and wakes any thread blocked in readNext() or + /// readAll(), which then return the end of the stream. Idempotent. + void close(); + + /// @brief Metadata associated with this stream. + /// + /// Attributes the sender attached when closing the stream are merged in + /// once readNext() or readAll() has reached the end of the stream, on the + /// reading thread. Don't call this concurrently with readNext() from + /// another thread. + /// + /// @return Stream metadata. const TextStreamInfo& info() const noexcept { return info_; } private: friend class Room; + friend struct DataStreamReaderTestAccess; + struct Impl; - /// Called by the Room when a new chunk arrives. - void onChunkUpdate(const std::string& text); + /// Called by the Room when a chunk arrives. + void onChunkReceived(std::string text); - /// Called by the Room when the stream is closed. - /// Additional trailer attributes are merged into info().attributes. - void onStreamClose(const std::map& trailer_attrs); + /// Called by the Room when the stream ends. @p error is set when the stream + /// ended abnormally. + void onStreamEnded(const std::map& attributes, std::optional error); TextStreamInfo info_; - - // Queue of text chunks; empty string with closed_==true means EOS. - std::deque queue_; - bool closed_ = false; - - std::mutex mutex_; - std::condition_variable cv_; + std::unique_ptr impl_; }; -/// Reader for incoming byte streams. +/// @brief Reader for incoming byte streams. +/// +/// Created by the SDK when a remote participant opens a byte stream on a topic +/// with a handler registered via Room::registerByteStreamHandler(). The SDK +/// decompresses and reassembles 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. class LIVEKIT_API ByteStreamReader { public: - /// Construct a reader from initial stream metadata. + /// @brief Construct a detached reader from stream metadata. + /// + /// A reader built this way is not connected to any incoming stream and + /// never receives data. Readers for real streams are created by the SDK. + /// @param info Stream metadata. explicit ByteStreamReader(ByteStreamInfo info); + ~ByteStreamReader(); ByteStreamReader(const ByteStreamReader&) = delete; ByteStreamReader& operator=(const ByteStreamReader&) = delete; - /// Blocking read of next byte chunk. - /// Returns false when the stream has ended. + /// @brief Blocking read of the next byte chunk. + /// + /// When the stream ends normally, any final attributes the sender attached + /// on close are merged into info().attributes before this returns false. + /// + /// @param out Receives the next chunk. + /// @return True if a chunk was read; false when the stream has ended or + /// close() was called. + /// @throws DataStreamError if the stream ended abnormally (for example the + /// sender closed it with a reason, it exceeded the receive size + /// limit, or the room disconnected mid-stream). Chunks received + /// before the error are returned first. bool readNext(std::vector& out); - /// Metadata associated with this stream. + /// @brief Read the entire stream into a single buffer. + /// + /// Blocks until the stream ends. + /// + /// @return The concatenated bytes. + /// @throws DataStreamError if the stream ended abnormally. + std::vector readAll(); + + /// @brief Stop reading early. + /// + /// Discards buffered chunks and wakes any thread blocked in readNext() or + /// readAll(), which then return the end of the stream. Idempotent. + void close(); + + /// @brief Metadata associated with this stream. + /// + /// Attributes the sender attached when closing the stream are merged in + /// once readNext() or readAll() has reached the end of the stream, on the + /// reading thread. Don't call this concurrently with readNext() from + /// another thread. + /// + /// @return Stream metadata. const ByteStreamInfo& info() const noexcept { return info_; } private: friend class Room; + friend struct DataStreamReaderTestAccess; + struct Impl; - /// Called by the Room when a new chunk arrives. - void onChunkUpdate(const std::vector& bytes); + /// Called by the Room when a chunk arrives. + void onChunkReceived(std::vector bytes); - /// Called by the Room when the stream is closed. - /// Additional trailer attributes are merged into info().attributes. - void onStreamClose(const std::map& trailer_attrs); + /// Called by the Room when the stream ends. @p error is set when the stream + /// ended abnormally. + void onStreamEnded(const std::map& attributes, std::optional error); ByteStreamInfo info_; - - std::deque> queue_; - bool closed_ = false; - - std::mutex mutex_; - std::condition_variable cv_; + std::unique_ptr impl_; }; /// Base class for sending data streams. @@ -267,7 +438,8 @@ class LIVEKIT_API ByteStreamWriter : public BaseStreamWriter { /// /// The TextStreamReader is provided as a shared_ptr to ensure it remains /// alive for the duration of asynchronous reads (for example, when the -/// user spawns a background thread to consume the stream). +/// user spawns a background thread to consume the stream). The handler runs on +/// the SDK event thread and must not read from the stream itself. using TextStreamHandler = std::function, const std::string& participant_identity)>; @@ -275,7 +447,8 @@ using TextStreamHandler = /// /// The ByteStreamReader is provided as a shared_ptr to ensure it remains /// alive for the duration of asynchronous reads (for example, file writes -/// or background processing). +/// or background processing). The handler runs on the SDK event thread and +/// must not read from the stream itself. using ByteStreamHandler = std::function, const std::string& participant_identity)>; diff --git a/include/livekit/local_participant.h b/include/livekit/local_participant.h index 557205b0..c9ff7c10 100644 --- a/include/livekit/local_participant.h +++ b/include/livekit/local_participant.h @@ -27,6 +27,7 @@ #include #include +#include "livekit/data_stream.h" #include "livekit/data_track_error.h" #include "livekit/data_track_options.h" #include "livekit/data_track_schema.h" @@ -93,6 +94,49 @@ class LIVEKIT_API LocalParticipant : public Participant { void publishData(const std::vector& payload, bool reliable = true, const std::vector& destination_identities = {}, const std::string& topic = {}); + /// @brief Send a complete text message as a data stream. + /// + /// Blocks until the SDK reports the send complete. When every recipient + /// supports it, small messages go out as a single packet and the payload is + /// compressed (unless @c options.compress is false). Receivers get the + /// message through Room::registerTextStreamHandler() on @c options.topic. + /// + /// @param text UTF-8 text to send. + /// @param options Topic (required), destinations, attributes, and so on. + /// @return Metadata of the sent stream, including its stream id. + /// @throws DataStreamError if the send fails, or if the room is no longer + /// connected or the SDK isn't initialized. + TextStreamInfo sendText(const std::string& text, const StreamTextOptions& options); + + /// @brief Send a complete in-memory buffer as a byte data stream. + /// + /// Blocks until the SDK reports the send complete. When every recipient + /// supports it, small payloads go out as a single packet and the payload is + /// compressed (unless @c options.compress is false). Receivers get the data + /// through Room::registerByteStreamHandler() on @c options.topic. + /// + /// @param data Bytes to send. + /// @param options Topic (required), name, MIME type, destinations, and so on. + /// @return Metadata of the sent stream, including its stream id. + /// @throws DataStreamError if the send fails, or if the room is no longer + /// connected or the SDK isn't initialized. + ByteStreamInfo sendBytes(const std::vector& data, const StreamByteOptions& options); + + /// @brief Send a local file as a byte data stream. + /// + /// The SDK reads the file itself (in this process). Blocks until the send + /// completes. When @c options.name is unset, the file's basename is used. + /// When @c options.mime_type is unset, the SDK picks one from the file. + /// Consider setting @c options.compress to false for files that are + /// already compressed, such as images. + /// + /// @param path Path of the file to send (UTF-8). + /// @param options Topic (required), name, MIME type, destinations, and so on. + /// @return Metadata of the sent stream, including its stream id. + /// @throws DataStreamError if the file can't be read or the send fails, or + /// if the room is no longer connected or the SDK isn't initialized. + ByteStreamInfo sendFile(const std::string& path, const StreamByteOptions& options); + /// Publish a SIP DTMF (phone keypad) tone into the room. /// /// Only meaningful when a SIP trunk is bridging a phone call into the @@ -302,8 +346,20 @@ class LIVEKIT_API LocalParticipant : public Participant { /// prune expired @c weak_ptr entries. mutable TrackMap published_tracks_by_sid_; + /// Marks the participant as disconnected so data stream sends fail fast in + /// C++ instead of reaching an FFI participant whose session is gone. + void markDisconnected() noexcept { disconnected_.store(true, std::memory_order_release); } + + /// Returns the FFI handle id for a data stream operation, or throws + /// DataStreamError if the participant can no longer send. + std::uint64_t dataStreamHandle(const char* operation) const; + std::unordered_map rpc_handlers_; + /// Set once the room disconnects. Guarded by an atomic rather than + /// Room::lock_ so send paths never need the room lock. + std::atomic disconnected_{false}; + // Shared state for RPC invocation tracking. Using shared_ptr so the state // can outlive the LocalParticipant if there are in-flight invocations when // the participant is destroyed. diff --git a/include/livekit/room.h b/include/livekit/room.h index 382006bb..a3ac4b10 100644 --- a/include/livekit/room.h +++ b/include/livekit/room.h @@ -38,7 +38,9 @@ class RoomDelegate; struct RoomInfoData; namespace proto { class FfiEvent; -} +class TextStreamOpened; +class ByteStreamOpened; +} // namespace proto struct E2EEOptions; class E2EEManager; @@ -71,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. @@ -125,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. @@ -267,9 +281,11 @@ class LIVEKIT_API Room { /// - Only one handler may be registered per topic. /// - If no handler is registered for a topic, incoming streams with that /// topic are ignored. - /// - The handler is invoked on the Room event thread. The handler must - /// not block; spawn a background thread if synchronous reading is - /// required. + /// - The handler is invoked on the SDK event thread, which also delivers + /// the stream's chunks. The handler must not block: never call + /// TextStreamReader::readNext() or readAll() inside it. Hand the reader + /// to a background thread instead. + /// - Reading throws DataStreamError if the stream ends abnormally. /// /// @throws std::runtime_error if a handler is already registered for the topic. void registerTextStreamHandler(const std::string& topic, TextStreamHandler handler); @@ -292,6 +308,11 @@ class LIVEKIT_API Room { /// topic are ignored. /// - The ByteStreamReader remains valid as long as the shared_ptr is held, /// preventing lifetime-related crashes when reading asynchronously. + /// - The handler is invoked on the SDK event thread, which also delivers + /// the stream's chunks. The handler must not block: never call + /// ByteStreamReader::readNext() or readAll() inside it. Hand the reader + /// to a background thread instead. + /// - Reading throws DataStreamError if the stream ends abnormally. /// /// @throws std::runtime_error if a handler is already registered for the topic. void registerByteStreamHandler(const std::string& topic, ByteStreamHandler handler); @@ -357,8 +378,12 @@ class LIVEKIT_API Room { // Data stream std::unordered_map text_stream_handlers_; std::unordered_map byte_stream_handlers_; - std::unordered_map> text_stream_readers_; - std::unordered_map> byte_stream_readers_; + // 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>; + TextStreamReaderMap text_stream_readers_; + ByteStreamReaderMap byte_stream_readers_; // The E2EE manager is owned by the room and is not shared with other objects. // It is a shared_ptr just to utilize the weak_ptr interface for the e2eeManager() accessor. std::shared_ptr e2ee_manager_; @@ -368,6 +393,11 @@ class LIVEKIT_API Room { int listener_id_{0}; void onEvent(const proto::FfiEvent& event); + void onTextStreamOpened(const proto::TextStreamOpened& opened, RoomDelegate* delegate); + void onByteStreamOpened(const proto::ByteStreamOpened& opened, RoomDelegate* delegate); + bool dispatchStreamReaderEvent(const proto::FfiEvent& event); + // Gives every reader a terminal "disconnected" error so blocked reads wake. + static void endStreamReaders(const TextStreamReaderMap& text_readers, const ByteStreamReaderMap& byte_readers); // Shared shutdown path for explicit disconnect, server disconnect, EOS, and destruction. bool shutdown(bool disconnect_ffi, DisconnectReason reason, bool notify_delegate); diff --git a/include/livekit/room_event_types.h b/include/livekit/room_event_types.h index 10fdffce..3e55482a 100644 --- a/include/livekit/room_event_types.h +++ b/include/livekit/room_event_types.h @@ -664,7 +664,11 @@ struct DataChannelBufferedAmountLowThresholdChangedEvent { /// Fired when a high-level byte stream reader is opened. struct ByteStreamOpenedEvent { - /// Handle to the underlying byte stream reader. + /// Always 0. + /// + /// @deprecated The reader handle is owned and consumed by the + /// ByteStreamReader the SDK passes to the handler registered with + /// Room::registerByteStreamHandler(); use that reader instead. std::uint64_t reader_handle = 0; /// Identity of the participant that opened the stream. @@ -673,7 +677,11 @@ struct ByteStreamOpenedEvent { /// Fired when a high-level text stream reader is opened. struct TextStreamOpenedEvent { - /// Handle to the underlying text stream reader. + /// Always 0. + /// + /// @deprecated The reader handle is owned and consumed by the + /// TextStreamReader the SDK passes to the handler registered with + /// Room::registerTextStreamHandler(); use that reader instead. std::uint64_t reader_handle = 0; /// Identity of the participant that opened the stream. diff --git a/src/data_stream.cpp b/src/data_stream.cpp index eb5ed11e..0d88da8e 100644 --- a/src/data_stream.cpp +++ b/src/data_stream.cpp @@ -18,6 +18,9 @@ #include #include +#include +#include +#include #include #include @@ -96,46 +99,125 @@ void fillBaseInfo(BaseStreamInfo& dst, const std::string& stream_id, const std:: } // namespace +// ===================================================================== +// Errors +// ===================================================================== + +DataStreamError::DataStreamError(const std::string& message) : std::runtime_error(message) {} + // ===================================================================== // Reader implementation // ===================================================================== -TextStreamReader::TextStreamReader(TextStreamInfo info) : info_(std::move(info)) {} +namespace { -void TextStreamReader::onChunkUpdate(const std::string& text) { - { - const std::scoped_lock lock(mutex_); - if (closed_) { - return; +/// Shared state for TextStreamReader / ByteStreamReader. +/// +/// The FFI callback thread pushes chunks and the end-of-stream marker; a user +/// thread pops them. Final attributes are merged into the reader's info on the +/// reading thread so info() is never mutated behind a single-threaded reader. +template +class ReaderState { +public: + void push(Chunk chunk) { + { + const std::scoped_lock lock(mutex_); + if (ended_ || closed_) { + return; + } + queue_.push_back(std::move(chunk)); } - queue_.push_back(text); + cv_.notify_one(); } - cv_.notify_one(); -} -void TextStreamReader::onStreamClose(const std::map& trailer_attrs) { - { - const std::scoped_lock lock(mutex_); - for (const auto& kv : trailer_attrs) { - info_.attributes[kv.first] = kv.second; + void end(const std::map& attributes, std::optional error) { + { + const std::scoped_lock lock(mutex_); + if (ended_) { + return; + } + ended_ = true; + end_attributes_ = attributes; + error_ = std::move(error); } - closed_ = true; + cv_.notify_all(); } - cv_.notify_all(); -} -bool TextStreamReader::readNext(std::string& out) { - std::unique_lock lock(mutex_); - cv_.wait(lock, [this] { return !queue_.empty() || closed_; }); + void close() { + { + const std::scoped_lock lock(mutex_); + closed_ = true; + queue_.clear(); + } + cv_.notify_all(); + } - if (!queue_.empty()) { - out = std::move(queue_.front()); - queue_.pop_front(); - return true; + /// Pops the next chunk into @p out. Returns false at the end of the stream. + /// Throws DataStreamError once the queue is drained if the stream failed. + template + bool next(Chunk& out, Info& info, const char* reader_name) { + std::unique_lock lock(mutex_); + if (!closed_ && !ended_ && queue_.empty() && !warned_ffi_thread_ && isOnFfiCallbackThread()) { + warned_ffi_thread_ = true; + LK_LOG_WARN( + "{}::readNext called on the SDK event thread; this blocks event delivery and can deadlock. " + "Read from a separate thread instead.", + reader_name); + } + cv_.wait(lock, [this] { return closed_ || ended_ || !queue_.empty(); }); + + if (closed_) { + return false; + } + if (!queue_.empty()) { + out = std::move(queue_.front()); + queue_.pop_front(); + return true; + } + + // Ended and drained. + if (!attributes_merged_) { + attributes_merged_ = true; + for (const auto& kv : end_attributes_) { + info.attributes[kv.first] = kv.second; + } + } + if (error_) { + throw DataStreamError(*error_); + } + return false; } - return false; // closed_ and empty + +private: + std::mutex mutex_; + std::condition_variable cv_; + std::deque queue_; + std::map end_attributes_; + std::optional error_; + bool ended_ = false; + bool closed_ = false; + bool attributes_merged_ = false; + bool warned_ffi_thread_ = false; +}; + +} // namespace + +struct TextStreamReader::Impl : ReaderState {}; +struct ByteStreamReader::Impl : ReaderState> {}; + +TextStreamReader::TextStreamReader(TextStreamInfo info) : info_(std::move(info)), impl_(std::make_unique()) {} + +TextStreamReader::~TextStreamReader() = default; + +void TextStreamReader::onChunkReceived(std::string text) { impl_->push(std::move(text)); } + +void TextStreamReader::onStreamEnded(const std::map& attributes, + std::optional error) { + impl_->end(attributes, std::move(error)); } +bool TextStreamReader::readNext(std::string& out) { return impl_->next(out, info_, "TextStreamReader"); } + std::string TextStreamReader::readAll() { std::string result; std::string chunk; @@ -145,42 +227,32 @@ std::string TextStreamReader::readAll() { return result; } -ByteStreamReader::ByteStreamReader(ByteStreamInfo info) : info_(std::move(info)) {} +void TextStreamReader::close() { impl_->close(); } -void ByteStreamReader::onChunkUpdate(const std::vector& bytes) { - { - const std::scoped_lock lock(mutex_); - if (closed_) { - return; - } - queue_.push_back(bytes); - } - cv_.notify_one(); -} +ByteStreamReader::ByteStreamReader(ByteStreamInfo info) : info_(std::move(info)), impl_(std::make_unique()) {} -void ByteStreamReader::onStreamClose(const std::map& trailer_attrs) { - { - const std::scoped_lock lock(mutex_); - for (const auto& kv : trailer_attrs) { - info_.attributes[kv.first] = kv.second; - } - closed_ = true; - } - cv_.notify_all(); +ByteStreamReader::~ByteStreamReader() = default; + +void ByteStreamReader::onChunkReceived(std::vector bytes) { impl_->push(std::move(bytes)); } + +void ByteStreamReader::onStreamEnded(const std::map& attributes, + std::optional error) { + impl_->end(attributes, std::move(error)); } -bool ByteStreamReader::readNext(std::vector& out) { - std::unique_lock lock(mutex_); - cv_.wait(lock, [this] { return !queue_.empty() || closed_; }); +bool ByteStreamReader::readNext(std::vector& out) { return impl_->next(out, info_, "ByteStreamReader"); } - if (!queue_.empty()) { - out = std::move(queue_.front()); - queue_.pop_front(); - return true; +std::vector ByteStreamReader::readAll() { + std::vector result; + std::vector chunk; + while (readNext(chunk)) { + result.insert(result.end(), chunk.begin(), chunk.end()); } - return false; + return result; } +void ByteStreamReader::close() { impl_->close(); } + // ===================================================================== // Writer implementation (uses your future-based FfiClient) // ===================================================================== diff --git a/src/data_stream_proto_converter.cpp b/src/data_stream_proto_converter.cpp new file mode 100644 index 00000000..0cb087d3 --- /dev/null +++ b/src/data_stream_proto_converter.cpp @@ -0,0 +1,111 @@ +/* + * 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. + */ + +#include "data_stream_proto_converter.h" + +namespace livekit { + +proto::StreamTextOptions toProto(const StreamTextOptions& in) { + proto::StreamTextOptions out; + out.set_topic(in.topic); + for (const auto& kv : in.attributes) { + (*out.mutable_attributes())[kv.first] = kv.second; + } + for (const auto& identity : in.destination_identities) { + out.add_destination_identities(identity); + } + if (in.stream_id) { + out.set_id(*in.stream_id); + } + if (in.reply_to_stream_id) { + out.set_reply_to_stream_id(*in.reply_to_stream_id); + } + for (const auto& id : in.attached_stream_ids) { + out.add_attached_stream_ids(id); + } + out.set_compress(in.compress); + if (in.sender_identity) { + out.set_sender_identity(*in.sender_identity); + } + return out; +} + +proto::StreamByteOptions toProto(const StreamByteOptions& in) { + proto::StreamByteOptions out; + out.set_topic(in.topic); + for (const auto& kv : in.attributes) { + (*out.mutable_attributes())[kv.first] = kv.second; + } + for (const auto& identity : in.destination_identities) { + out.add_destination_identities(identity); + } + if (in.stream_id) { + out.set_id(*in.stream_id); + } + if (in.name) { + out.set_name(*in.name); + } + if (in.mime_type) { + out.set_mime_type(*in.mime_type); + } + if (in.total_length) { + out.set_total_length(*in.total_length); + } + out.set_compress(in.compress); + if (in.sender_identity) { + out.set_sender_identity(*in.sender_identity); + } + return out; +} + +TextStreamInfo fromProto(const proto::TextStreamInfo& in) { + TextStreamInfo out; + out.stream_id = in.stream_id(); + out.mime_type = in.mime_type(); + out.topic = in.topic(); + out.timestamp = in.timestamp(); + if (in.has_total_length()) { + out.size = static_cast(in.total_length()); + } + for (const auto& kv : in.attributes()) { + out.attributes.emplace(kv.first, kv.second); + } + for (const auto& id : in.attached_stream_ids()) { + out.attachments.push_back(id); + } + if (in.has_reply_to_stream_id()) { + out.reply_to_stream_id = in.reply_to_stream_id(); + } + return out; +} + +ByteStreamInfo fromProto(const proto::ByteStreamInfo& in) { + ByteStreamInfo out; + out.stream_id = in.stream_id(); + out.mime_type = in.mime_type(); + out.topic = in.topic(); + out.timestamp = in.timestamp(); + if (in.has_total_length()) { + out.size = static_cast(in.total_length()); + } + for (const auto& kv : in.attributes()) { + out.attributes.emplace(kv.first, kv.second); + } + out.name = in.name(); + return out; +} + +} // namespace livekit diff --git a/src/data_stream_proto_converter.h b/src/data_stream_proto_converter.h new file mode 100644 index 00000000..acf3c0ee --- /dev/null +++ b/src/data_stream_proto_converter.h @@ -0,0 +1,45 @@ +/* + * 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. + */ + +#pragma once + +#include "data_stream.pb.h" +#include "livekit/data_stream.h" +#include "livekit/visibility.h" + +namespace livekit { + +/// @brief Convert one-shot text send options to the FFI proto. +/// @param in C++ options. +/// @return The FFI options; `compress` is always set explicitly. +LIVEKIT_INTERNAL_API proto::StreamTextOptions toProto(const StreamTextOptions& in); + +/// @brief Convert one-shot byte send options to the FFI proto. +/// @param in C++ options. +/// @return The FFI options; `compress` is always set explicitly. +LIVEKIT_INTERNAL_API proto::StreamByteOptions toProto(const StreamByteOptions& in); + +/// @brief Convert FFI text stream metadata to the public info struct. +/// @param in FFI info. +/// @return Public info. +LIVEKIT_INTERNAL_API TextStreamInfo fromProto(const proto::TextStreamInfo& in); + +/// @brief Convert FFI byte stream metadata to the public info struct. +/// @param in FFI info. +/// @return Public info. +LIVEKIT_INTERNAL_API ByteStreamInfo fromProto(const proto::ByteStreamInfo& in); + +} // namespace livekit diff --git a/src/ffi_client.cpp b/src/ffi_client.cpp index 0854def8..ccb70300 100644 --- a/src/ffi_client.cpp +++ b/src/ffi_client.cpp @@ -27,6 +27,7 @@ #include "data_track_proto_converter.h" #include "ffi.pb.h" #include "livekit/build.h" +#include "livekit/data_stream.h" #include "livekit/data_track_error.h" #include "livekit/ffi_handle.h" #include "livekit/room.h" @@ -79,6 +80,8 @@ Result subscribeDataTrackF return Result::failure(SubscribeDataTrackError{code, message}); } +thread_local bool t_in_ffi_callback = false; + std::optional ExtractAsyncId(const proto::FfiEvent& event) { using E = proto::FfiEvent; switch (event.message_case()) { @@ -445,9 +448,13 @@ extern "C" LIVEKIT_INTERNAL_API void ffiEventCallback(const uint8_t* buf, size_t return; } + t_in_ffi_callback = true; FfiClient::instance().pushEvent(event); + t_in_ffi_callback = false; } +bool isOnFfiCallbackThread() noexcept { return t_in_ffi_callback; } + FfiClient::AsyncId FfiClient::generateAsyncId() { return next_async_id_.fetch_add(1, std::memory_order_relaxed); } bool FfiClient::cancelPendingByAsyncId(AsyncId async_id) { @@ -1117,6 +1124,147 @@ std::future FfiClient::performRpcAsync(std::uint64_t local_particip return fut; } +std::future FfiClient::sendTextAsync(std::uint64_t local_participant_handle, + const std::string& text, + const proto::StreamTextOptions& options) { + const AsyncId async_id = generateAsyncId(); + + auto fut = registerAsync( + async_id, + [async_id](const proto::FfiEvent& e) { return e.has_send_text() && e.send_text().async_id() == async_id; }, + [](const proto::FfiEvent& e, std::promise& pr) { + const auto& cb = e.send_text(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); + return; + } + if (!cb.has_info()) { + pr.set_exception(std::make_exception_ptr(DataStreamError("send_text callback missing info"))); + return; + } + pr.set_value(cb.info()); + }); + + proto::FfiRequest req; + auto* msg = req.mutable_send_text(); + msg->set_local_participant_handle(local_participant_handle); + *msg->mutable_options() = options; + msg->set_text(text); + msg->set_request_async_id(async_id); + + try { + const proto::FfiResponse resp = sendRequest(req); + if (!resp.has_send_text()) { + logAndThrow("FfiResponse missing send_text"); + } + } catch (...) { + cancelPendingByAsyncId(async_id); + throw; + } + + return fut; +} + +std::future FfiClient::sendBytesAsync(std::uint64_t local_participant_handle, + const std::vector& bytes, + const proto::StreamByteOptions& options) { + const AsyncId async_id = generateAsyncId(); + + auto fut = registerAsync( + async_id, + [async_id](const proto::FfiEvent& e) { return e.has_send_bytes() && e.send_bytes().async_id() == async_id; }, + [](const proto::FfiEvent& e, std::promise& pr) { + const auto& cb = e.send_bytes(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); + return; + } + if (!cb.has_info()) { + pr.set_exception(std::make_exception_ptr(DataStreamError("send_bytes callback missing info"))); + return; + } + pr.set_value(cb.info()); + }); + + proto::FfiRequest req; + auto* msg = req.mutable_send_bytes(); + msg->set_local_participant_handle(local_participant_handle); + *msg->mutable_options() = options; + msg->set_bytes(bytes.data(), bytes.size()); + msg->set_request_async_id(async_id); + + try { + const proto::FfiResponse resp = sendRequest(req); + if (!resp.has_send_bytes()) { + logAndThrow("FfiResponse missing send_bytes"); + } + } catch (...) { + cancelPendingByAsyncId(async_id); + throw; + } + + return fut; +} + +std::future FfiClient::sendFileAsync(std::uint64_t local_participant_handle, + const std::string& file_path, + const proto::StreamByteOptions& options) { + const AsyncId async_id = generateAsyncId(); + + auto fut = registerAsync( + async_id, + [async_id](const proto::FfiEvent& e) { return e.has_send_file() && e.send_file().async_id() == async_id; }, + [](const proto::FfiEvent& e, std::promise& pr) { + const auto& cb = e.send_file(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); + return; + } + if (!cb.has_info()) { + pr.set_exception(std::make_exception_ptr(DataStreamError("send_file callback missing info"))); + return; + } + pr.set_value(cb.info()); + }); + + proto::FfiRequest req; + auto* msg = req.mutable_send_file(); + msg->set_local_participant_handle(local_participant_handle); + *msg->mutable_options() = options; + msg->set_file_path(file_path); + msg->set_request_async_id(async_id); + + try { + const proto::FfiResponse resp = sendRequest(req); + if (!resp.has_send_file()) { + logAndThrow("FfiResponse missing send_file"); + } + } catch (...) { + cancelPendingByAsyncId(async_id); + throw; + } + + return fut; +} + +void FfiClient::textStreamReadIncremental(std::uint64_t reader_handle) { + proto::FfiRequest req; + req.mutable_text_read_incremental()->set_reader_handle(reader_handle); + const proto::FfiResponse resp = sendRequest(req); + if (!resp.has_text_read_incremental()) { + logAndThrow("FfiResponse missing text_read_incremental"); + } +} + +void FfiClient::byteStreamReadIncremental(std::uint64_t reader_handle) { + proto::FfiRequest req; + req.mutable_byte_read_incremental()->set_reader_handle(reader_handle); + const proto::FfiResponse resp = sendRequest(req); + if (!resp.has_byte_read_incremental()) { + logAndThrow("FfiResponse missing byte_read_incremental"); + } +} + 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 3183786a..1359f891 100644 --- a/src/ffi_client.h +++ b/src/ffi_client.h @@ -77,6 +77,11 @@ extern "C" LIVEKIT_INTERNAL_API void ffiEventCallback(const uint8_t* buf, size_t /// @return True if the handle was released; false if it did not exist. [[nodiscard]] LIVEKIT_INTERNAL_API bool dropFfiHandle(std::uint64_t handle) noexcept; +/// @brief Whether the calling thread is currently delivering an FFI event. +/// Used to warn about blocking calls made from SDK callbacks. +/// @return True if called from inside ffiEventCallback. +[[nodiscard]] LIVEKIT_INTERNAL_API bool isOnFfiCallbackThread() noexcept; + // The FfiClient is used to communicate with the FFI interface of the Rust SDK // We use the generated protocol messages to facilitate the communication. class LIVEKIT_INTERNAL_API FfiClient { @@ -155,7 +160,23 @@ class LIVEKIT_INTERNAL_API FfiClient { Result subscribeDataTrack( std::uint64_t track_handle, std::optional buffer_size = std::nullopt); - // Data stream functionalities + // Data stream APIs (high-level; Rust handles framing, chunking and + // compression). A callback error is surfaced as DataStreamError. + std::future sendTextAsync(std::uint64_t local_participant_handle, const std::string& text, + const proto::StreamTextOptions& options); + std::future sendBytesAsync(std::uint64_t local_participant_handle, + const std::vector& bytes, + const proto::StreamByteOptions& options); + std::future sendFileAsync(std::uint64_t local_participant_handle, const std::string& file_path, + const proto::StreamByteOptions& options); + + // Start incremental reads of an owned reader handle. Consumes the handle: + // never drop it afterwards. Chunks and EOS arrive as + // Text/ByteStreamReaderEvent keyed by reader handle. + void textStreamReadIncremental(std::uint64_t reader_handle); + void byteStreamReadIncremental(std::uint64_t reader_handle); + + // Low-level data stream functionalities (legacy v1 framing) std::future sendStreamHeaderAsync(std::uint64_t local_participant_handle, const proto::DataStream::Header& header, const std::vector& destination_identities, diff --git a/src/local_participant.cpp b/src/local_participant.cpp index 2607963d..e93e3fcc 100644 --- a/src/local_participant.cpp +++ b/src/local_participant.cpp @@ -21,6 +21,7 @@ #include #include +#include "data_stream_proto_converter.h" #include "data_track.pb.h" #include "ffi.pb.h" #include "ffi_client.h" @@ -86,6 +87,51 @@ void LocalParticipant::publishData(const std::vector& payload, boo fut.get(); } +std::uint64_t LocalParticipant::dataStreamHandle(const char* operation) const { + if (!FfiClient::instance().isInitialized()) { + throw DataStreamError(std::string("LocalParticipant::") + operation + ": LiveKit is not initialized"); + } + // The FFI panics (and the SDK raises SIGTERM) if a stream is sent after the + // room session is gone, so refuse here instead. + if (disconnected_.load(std::memory_order_acquire)) { + throw DataStreamError(std::string("LocalParticipant::") + operation + ": not connected"); + } + const auto handle_id = ffiHandleId(); + if (handle_id == 0) { + throw DataStreamError(std::string("LocalParticipant::") + operation + ": invalid FFI handle"); + } + return static_cast(handle_id); +} + +TextStreamInfo LocalParticipant::sendText(const std::string& text, const StreamTextOptions& options) { + const auto handle_id = dataStreamHandle("sendText"); + auto fut = FfiClient::instance().sendTextAsync(handle_id, text, toProto(options)); + return fromProto(fut.get()); +} + +ByteStreamInfo LocalParticipant::sendBytes(const std::vector& data, const StreamByteOptions& options) { + const auto handle_id = dataStreamHandle("sendBytes"); + auto fut = FfiClient::instance().sendBytesAsync(handle_id, data, toProto(options)); + return fromProto(fut.get()); +} + +ByteStreamInfo LocalParticipant::sendFile(const std::string& path, const StreamByteOptions& options) { + const auto handle_id = dataStreamHandle("sendFile"); + proto::StreamByteOptions proto_options = toProto(options); + if (!options.name) { + // Basename of a UTF-8 path. Done on the string rather than via + // std::filesystem so non-ASCII names survive on Windows. +#ifdef _WIN32 + const auto slash = path.find_last_of("/\\"); +#else + const auto slash = path.find_last_of('/'); +#endif + proto_options.set_name(slash == std::string::npos ? path : path.substr(slash + 1)); + } + auto fut = FfiClient::instance().sendFileAsync(handle_id, path, proto_options); + return fromProto(fut.get()); +} + void LocalParticipant::publishDtmf(int code, const std::string& digit) { auto handle_id = ffiHandleId(); if (handle_id == 0) { @@ -394,6 +440,7 @@ void LocalParticipant::unregisterRpcMethod(const std::string& method_name) { } void LocalParticipant::shutdown() { + markDisconnected(); // Mark as shutting down and wait for all active invocations to complete { std::unique_lock lock(rpc_state_->mutex); diff --git a/src/room.cpp b/src/room.cpp index 99b39b97..437d0e94 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -16,6 +16,7 @@ #include "livekit/room.h" +#include "data_stream_proto_converter.h" #include "ffi.pb.h" #include "ffi_client.h" #include "livekit/audio_stream.h" @@ -87,6 +88,16 @@ void readyForRoomEvent(std::uint64_t room_handle) { } } +constexpr char kDisconnectedWhileReceiving[] = "Disconnected while receiving"; + +std::map toStdMap(const google::protobuf::Map& in) { + std::map out; + for (const auto& kv : in) { + out.emplace(kv.first, kv.second); + } + return out; +} + } // namespace Room::Room() : subscription_thread_dispatcher_(std::make_unique()) {} @@ -202,6 +213,8 @@ bool Room::connect(const std::string& url, const std::string& token, const RoomO } catch (const std::exception& e) { int listener_to_remove = 0; std::shared_ptr local_participant_to_cleanup; + TextStreamReaderMap text_readers_to_end; + ByteStreamReaderMap byte_readers_to_end; { const std::scoped_lock g(lock_); connection_state_ = ConnectionState::Disconnected; @@ -213,9 +226,12 @@ bool Room::connect(const std::string& url, const std::string& token, const RoomO remote_participants_.clear(); room_handle_.reset(); e2ee_manager_.reset(); + text_readers_to_end = std::move(text_stream_readers_); + byte_readers_to_end = std::move(byte_stream_readers_); text_stream_readers_.clear(); byte_stream_readers_.clear(); } + endStreamReaders(text_readers_to_end, byte_readers_to_end); if (local_participant_to_cleanup) { local_participant_to_cleanup->shutdown(); } @@ -238,8 +254,8 @@ bool Room::shutdown(bool disconnect_ffi, DisconnectReason reason, bool notify_de std::shared_ptr local_participant_to_cleanup; std::unordered_map> remote_participants_to_clear; std::shared_ptr e2ee_manager_to_clear; - std::unordered_map> text_stream_readers_to_clear; - std::unordered_map> byte_stream_readers_to_clear; + TextStreamReaderMap text_stream_readers_to_clear; + ByteStreamReaderMap byte_stream_readers_to_clear; int listener_to_remove = 0; bool claimed_disconnect = false; @@ -317,6 +333,10 @@ bool Room::shutdown(bool disconnect_ffi, DisconnectReason reason, bool notify_de } } + // Wake readers still waiting on data. Their handles were consumed by + // read_incremental, so there is nothing to drop. + endStreamReaders(text_stream_readers_to_clear, byte_stream_readers_to_clear); + local_participant_to_cleanup.reset(); remote_participants_to_clear.clear(); e2ee_manager_to_clear.reset(); @@ -477,6 +497,11 @@ void Room::onEvent(const FfiEvent& event) { delegate_snapshot = delegate_; } + // Incoming data stream chunks / end-of-stream for readers this room owns. + if (dispatchStreamReaderEvent(event)) { + return; + } + // First, handle RPC method invocations (not part of RoomEvent). if (event.message_case() == FfiEvent::kRpcMethodInvocation) { const auto& rpc = event.rpc_method_invocation(); @@ -1251,6 +1276,9 @@ void Room::onEvent(const FfiEvent& event) { bool should_notify = false; { const std::scoped_lock guard(lock_); + if (local_participant_) { + local_participant_->markDisconnected(); + } // Local shutdown marks the state before awaiting the FFI response // and notifies the delegate itself. Suppress that duplicate while // passing server-initiated disconnects through unchanged. @@ -1298,115 +1326,12 @@ void Room::onEvent(const FfiEvent& event) { // Deprecated event, do nothing. break; } - case proto::RoomEvent::kStreamHeaderReceived: { - const auto& sh = re.stream_header_received(); - const auto& header = sh.header(); - const std::string& participant_identity = sh.participant_identity(); - - // Snapshot handler + create reader without holding lock during user - // callback - TextStreamHandler text_cb; - ByteStreamHandler byte_cb; - std::shared_ptr text_reader; - std::shared_ptr byte_reader; - { - const std::scoped_lock guard(lock_); - - // Determine stream type from oneof in protobuf - // Adjust these names if your generated C++ uses different ones - const auto stream_type = header.content_header_case(); - if (stream_type == proto::DataStream::Header::kTextHeader) { - auto it = text_stream_handlers_.find(header.topic()); - if (it == text_stream_handlers_.end()) { - // Ignore if no callback attached - break; - } - text_cb = it->second; - - const TextStreamInfo info = makeTextInfo(header); - text_reader = std::make_shared(info); - text_stream_readers_[header.stream_id()] = text_reader; - - } else if (stream_type == proto::DataStream::Header::kByteHeader) { - auto it = byte_stream_handlers_.find(header.topic()); - if (it == byte_stream_handlers_.end()) { - break; - } - byte_cb = it->second; - const ByteStreamInfo info = makeByteInfo(header); - byte_reader = std::make_shared(info); - byte_stream_readers_[header.stream_id()] = byte_reader; - - } else { - // unknown header type: ignore - break; - } - } - - // Invoke user callback outside lock (very important) - if (text_reader) { - text_cb(text_reader, participant_identity); - } else if (byte_reader) { - byte_cb(byte_reader, participant_identity); - } - break; - } - case proto::RoomEvent::kStreamChunkReceived: { - const auto& sc = re.stream_chunk_received(); - const auto& chunk = sc.chunk(); - std::shared_ptr text_reader; - std::shared_ptr byte_reader; - { - const std::scoped_lock guard(lock_); - auto itT = text_stream_readers_.find(chunk.stream_id()); - if (itT != text_stream_readers_.end()) { - text_reader = itT->second; - } else { - auto itB = byte_stream_readers_.find(chunk.stream_id()); - if (itB != byte_stream_readers_.end()) { - byte_reader = itB->second; - } - } - } - if (text_reader) { - // chunk.content() is bytes; treat as UTF-8 string. - text_reader->onChunkUpdate(chunk.content()); - } else if (byte_reader) { - // Convert string bytes -> vector - const std::string& s = chunk.content(); - const std::vector bytes(s.begin(), s.end()); - byte_reader->onChunkUpdate(bytes); - } - break; - } + case proto::RoomEvent::kStreamHeaderReceived: + case proto::RoomEvent::kStreamChunkReceived: case proto::RoomEvent::kStreamTrailerReceived: { - const auto& st = re.stream_trailer_received(); - const auto& trailer = st.trailer(); - std::shared_ptr text_reader; - std::shared_ptr byte_reader; - std::map trailer_attrs; - for (const auto& kv : trailer.attributes()) { - trailer_attrs.emplace(kv.first, kv.second); - } - { - const std::scoped_lock guard(lock_); - auto itT = text_stream_readers_.find(trailer.stream_id()); - if (itT != text_stream_readers_.end()) { - text_reader = itT->second; - text_stream_readers_.erase(itT); - } else { - auto itB = byte_stream_readers_.find(trailer.stream_id()); - if (itB != byte_stream_readers_.end()) { - byte_reader = itB->second; - byte_stream_readers_.erase(itB); - } - } - } - if (text_reader) { - text_reader->onStreamClose(trailer_attrs); - } else if (byte_reader) { - byte_reader->onStreamClose(trailer_attrs); - } + // Low-level packet events. Every stream is also delivered as a + // text/byte_stream_opened event with an owned reader, which is what + // the SDK consumes; handling these too would duplicate streams. break; } case proto::RoomEvent::kDataChannelLowThresholdChanged: { @@ -1417,17 +1342,11 @@ void Room::onEvent(const FfiEvent& event) { break; } case proto::RoomEvent::kByteStreamOpened: { - auto ev = fromProto(re.byte_stream_opened()); - if (delegate_snapshot) { - delegate_snapshot->onByteStreamOpened(*this, ev); - } + onByteStreamOpened(re.byte_stream_opened(), delegate_snapshot); break; } case proto::RoomEvent::kTextStreamOpened: { - auto ev = fromProto(re.text_stream_opened()); - if (delegate_snapshot) { - delegate_snapshot->onTextStreamOpened(*this, ev); - } + onTextStreamOpened(re.text_stream_opened(), delegate_snapshot); break; } case proto::RoomEvent::kRoomUpdated: { @@ -1500,4 +1419,166 @@ void Room::onEvent(const FfiEvent& event) { } } +// ------------------------------------------------------------------- +// Data streams +// ------------------------------------------------------------------- + +void Room::endStreamReaders(const TextStreamReaderMap& text_readers, const ByteStreamReaderMap& byte_readers) { + for (const auto& kv : text_readers) { + kv.second->onStreamEnded({}, std::string(kDisconnectedWhileReceiving)); + } + for (const auto& kv : byte_readers) { + kv.second->onStreamEnded({}, std::string(kDisconnectedWhileReceiving)); + } +} + +bool Room::dispatchStreamReaderEvent(const FfiEvent& event) { + if (event.message_case() == FfiEvent::kTextStreamReaderEvent) { + const auto& ev = event.text_stream_reader_event(); + std::shared_ptr reader; + { + const std::scoped_lock guard(lock_); + const auto it = text_stream_readers_.find(ev.reader_handle()); + if (it == text_stream_readers_.end()) { + return true; // Not ours (another room) or already ended. + } + reader = it->second; + if (ev.has_eos()) { + text_stream_readers_.erase(it); + } + } + if (ev.has_chunk_received()) { + reader->onChunkReceived(ev.chunk_received().content()); + } else if (ev.has_eos()) { + const auto& eos = ev.eos(); + reader->onStreamEnded(toStdMap(eos.attributes()), + eos.has_error() ? std::optional(eos.error().description()) : std::nullopt); + } + return true; + } + + if (event.message_case() == FfiEvent::kByteStreamReaderEvent) { + const auto& ev = event.byte_stream_reader_event(); + std::shared_ptr reader; + { + const std::scoped_lock guard(lock_); + const auto it = byte_stream_readers_.find(ev.reader_handle()); + if (it == byte_stream_readers_.end()) { + return true; + } + reader = it->second; + if (ev.has_eos()) { + byte_stream_readers_.erase(it); + } + } + if (ev.has_chunk_received()) { + const std::string& content = ev.chunk_received().content(); + reader->onChunkReceived(std::vector(content.begin(), content.end())); + } else if (ev.has_eos()) { + const auto& eos = ev.eos(); + reader->onStreamEnded(toStdMap(eos.attributes()), + eos.has_error() ? std::optional(eos.error().description()) : std::nullopt); + } + return true; + } + + return false; +} + +void Room::onTextStreamOpened(const proto::TextStreamOpened& opened, RoomDelegate* delegate) { + const auto& owned = opened.reader(); + const auto reader_handle = static_cast(owned.handle().id()); + + TextStreamHandler handler; + std::shared_ptr reader; + { + const std::scoped_lock guard(lock_); + const auto it = text_stream_handlers_.find(owned.info().topic()); + // room_handle_ is cleared by shutdown(); a stream opened concurrently + // with shutdown is dropped rather than tracked by a dead room. + if (room_handle_ && it != text_stream_handlers_.end()) { + handler = it->second; + reader = std::make_shared(fromProto(owned.info())); + // Register before read_incremental so no chunk can arrive unrouted. + text_stream_readers_[reader_handle] = reader; + } + } + + if (!reader) { + // Nobody will read it: drop the handle so the FFI frees the stream. + const FfiHandle unread(static_cast(reader_handle)); + LK_LOG_DEBUG("No text stream handler for topic '{}'; ignoring stream {}", owned.info().topic(), + owned.info().stream_id()); + } else { + try { + FfiClient::instance().textStreamReadIncremental(reader_handle); + } catch (const std::exception& e) { + LK_LOG_ERROR("Failed to start reading text stream {}: {}", owned.info().stream_id(), e.what()); + { + const std::scoped_lock guard(lock_); + text_stream_readers_.erase(reader_handle); + } + const FfiHandle unread(static_cast(reader_handle)); + reader->onStreamEnded({}, std::string(e.what())); + } + } + + if (reader) { + handler(reader, opened.participant_identity()); + } + + if (delegate) { + const TextStreamOpenedEvent ev = fromProto(opened); + delegate->onTextStreamOpened(*this, ev); + } +} + +void Room::onByteStreamOpened(const proto::ByteStreamOpened& opened, RoomDelegate* delegate) { + const auto& owned = opened.reader(); + const auto reader_handle = static_cast(owned.handle().id()); + + ByteStreamHandler handler; + std::shared_ptr reader; + { + const std::scoped_lock guard(lock_); + const auto it = byte_stream_handlers_.find(owned.info().topic()); + // room_handle_ is cleared by shutdown(); a stream opened concurrently + // with shutdown is dropped rather than tracked by a dead room. + 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. + byte_stream_readers_[reader_handle] = reader; + } + } + + if (!reader) { + // Nobody will read it: drop the handle so the FFI frees the stream. + 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) { + handler(reader, opened.participant_identity()); + } + + if (delegate) { + const ByteStreamOpenedEvent ev = fromProto(opened); + delegate->onByteStreamOpened(*this, ev); + } +} + } // namespace livekit diff --git a/src/room_proto_converter.cpp b/src/room_proto_converter.cpp index 3d543756..b72710fe 100644 --- a/src/room_proto_converter.cpp +++ b/src/room_proto_converter.cpp @@ -381,16 +381,16 @@ DataChannelBufferedAmountLowThresholdChangedEvent fromProto( ByteStreamOpenedEvent fromProto(const proto::ByteStreamOpened& in) { ByteStreamOpenedEvent ev; - // TODO: map reader handle once OwnedByteStreamReader is known - // ev.reader_handle = in.reader().handle().id(); + // reader_handle is intentionally left 0: the Room's ByteStreamReader owns + // and consumes the handle. ev.participant_identity = in.participant_identity(); return ev; } TextStreamOpenedEvent fromProto(const proto::TextStreamOpened& in) { TextStreamOpenedEvent ev; - // TODO: map reader handle once OwnedTextStreamReader is known - // ev.reader_handle = in.reader().handle().id(); + // reader_handle is intentionally left 0: the Room's TextStreamReader owns + // and consumes the handle. ev.participant_identity = in.participant_identity(); return ev; } @@ -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_streams.cpp b/src/tests/integration/test_data_streams.cpp index 2a919ff8..2d73e7c3 100644 --- a/src/tests/integration/test_data_streams.cpp +++ b/src/tests/integration/test_data_streams.cpp @@ -15,20 +15,27 @@ */ // End-to-end coverage for text/byte data streams (registerTextStreamHandler / -// registerByteStreamHandler + TextStreamWriter / ByteStreamWriter). Requires a -// local SFU; see test_data_track.cpp for setup instructions. Run with: +// registerByteStreamHandler + LocalParticipant::sendText / sendBytes / sendFile +// and TextStreamWriter / ByteStreamWriter). Requires a local SFU; see +// test_data_track.cpp for setup instructions. Run with: // ./build-debug/bin/livekit_integration_tests --gtest_filter=*DataStream* #include +#include #include #include +#include +#include #include +#include #include #include #include #include "../common/test_common.h" +#include "ffi.pb.h" +#include "ffi_client.h" namespace livekit::test { @@ -47,6 +54,14 @@ std::string makeTopic(const std::string& suffix) { class TextStreamCollector { public: ~TextStreamCollector() { + // If the test failed before the stream ended, wake the reader so joining + // doesn't hang the test binary. + std::unique_lock lock(mutex_); + auto reader = reader_.lock(); + lock.unlock(); + if (reader) { + reader->close(); + } if (recv_thread_.joinable()) { recv_thread_.join(); } @@ -58,12 +73,23 @@ class TextStreamCollector { // until close, so it has to happen on a separate thread. room.registerTextStreamHandler( topic, [this](std::shared_ptr reader, const std::string& participant_identity) { + { + std::lock_guard lock(mutex_); + reader_ = reader; + } recv_thread_ = std::thread([this, reader, participant_identity] { - auto info = reader->info(); - auto text = reader->readAll(); + std::string text; + std::optional error; + try { + text = reader->readAll(); + } catch (const DataStreamError& e) { + error = e.what(); + } std::lock_guard lock(mutex_); - info_ = std::move(info); + // Read info after the stream ends so trailer attributes are merged. + info_ = reader->info(); text_ = std::move(text); + error_ = std::move(error); sender_identity_ = participant_identity; done_ = true; cv_.notify_all(); @@ -78,15 +104,18 @@ class TextStreamCollector { const TextStreamInfo& info() const { return info_; } const std::string& text() const { return text_; } + const std::optional& error() const { return error_; } const std::string& senderIdentity() const { return sender_identity_; } private: + std::weak_ptr reader_; std::thread recv_thread_; std::mutex mutex_; std::condition_variable cv_; bool done_ = false; TextStreamInfo info_; std::string text_; + std::optional error_; std::string sender_identity_; }; @@ -94,6 +123,14 @@ class TextStreamCollector { class ByteStreamCollector { public: ~ByteStreamCollector() { + // If the test failed before the stream ended, wake the reader so joining + // doesn't hang the test binary. + std::unique_lock lock(mutex_); + auto reader = reader_.lock(); + lock.unlock(); + if (reader) { + reader->close(); + } if (recv_thread_.joinable()) { recv_thread_.join(); } @@ -103,16 +140,25 @@ class ByteStreamCollector { // not run on the Room event thread. room.registerByteStreamHandler( topic, [this](std::shared_ptr reader, const std::string& participant_identity) { + { + std::lock_guard lock(mutex_); + reader_ = reader; + } recv_thread_ = std::thread([this, reader, participant_identity] { - auto info = reader->info(); std::vector content; std::vector chunk; - while (reader->readNext(chunk)) { - content.insert(content.end(), chunk.begin(), chunk.end()); + std::optional error; + try { + while (reader->readNext(chunk)) { + content.insert(content.end(), chunk.begin(), chunk.end()); + } + } catch (const DataStreamError& e) { + error = e.what(); } std::lock_guard lock(mutex_); - info_ = std::move(info); + info_ = reader->info(); content_ = std::move(content); + error_ = std::move(error); sender_identity_ = participant_identity; done_ = true; cv_.notify_all(); @@ -127,18 +173,85 @@ class ByteStreamCollector { const ByteStreamInfo& info() const { return info_; } const std::vector& content() const { return content_; } + const std::optional& error() const { return error_; } const std::string& senderIdentity() const { return sender_identity_; } private: + std::weak_ptr reader_; std::thread recv_thread_; std::mutex mutex_; std::condition_variable cv_; bool done_ = false; ByteStreamInfo info_; std::vector content_; + std::optional error_; std::string sender_identity_; }; +/// Text that compresses well, cycling through ASCII letters. +std::string compressibleText(std::size_t size) { + std::string out; + out.reserve(size); + for (std::size_t i = 0; i < size; ++i) { + out.push_back(static_cast('a' + (i % 26))); + } + return out; +} + +/// Multi-byte UTF-8 text (2-, 3- and 4-byte code points) of at least @p size bytes. +std::string unicodeText(std::size_t size) { + const std::string unit = "h\xC3\xA9llo \xE4\xB8\x96\xE7\x95\x8C \xF0\x9F\x91\x8B "; + std::string out; + while (out.size() < size) { + out += unit; + } + return out; +} + +/// Records the reader handle of every opened data stream, to probe whether the +/// SDK released them. +class OpenedStreamHandleRecorder { +public: + OpenedStreamHandleRecorder() { + listener_id_ = FfiClient::instance().addListener([this](const proto::FfiEvent& event) { + if (event.message_case() != proto::FfiEvent::kRoomEvent) { + return; + } + const auto& re = event.room_event(); + std::uint64_t handle = 0; + if (re.has_text_stream_opened()) { + handle = re.text_stream_opened().reader().handle().id(); + } else if (re.has_byte_stream_opened()) { + handle = re.byte_stream_opened().reader().handle().id(); + } else { + return; + } + std::lock_guard lock(mutex_); + handles_.push_back(handle); + cv_.notify_all(); + }); + } + ~OpenedStreamHandleRecorder() { FfiClient::instance().removeListener(listener_id_); } + OpenedStreamHandleRecorder(const OpenedStreamHandleRecorder&) = delete; + OpenedStreamHandleRecorder& operator=(const OpenedStreamHandleRecorder&) = delete; + + bool waitForCount(std::size_t count, std::chrono::milliseconds timeout) { + std::unique_lock lock(mutex_); + return cv_.wait_for(lock, timeout, [this, count] { return handles_.size() >= count; }); + } + + std::vector handles() { + std::lock_guard lock(mutex_); + return handles_; + } + +private: + FfiClient::ListenerId listener_id_ = 0; + std::mutex mutex_; + std::condition_variable cv_; + std::vector handles_; +}; + } // namespace class DataStreamE2ETest : public LiveKitTestBase {}; @@ -218,4 +331,308 @@ TEST_F(DataStreamE2ETest, ByteStreamRoundTripEndToEnd) { EXPECT_EQ(collector.info().name, "payload.bin"); } +// --------------------------------------------------------------------------- +// One-shot sends (sendText / sendBytes / sendFile). These produce data streams +// v2 traffic (single-packet and compressed), like every other LiveKit SDK. +// --------------------------------------------------------------------------- + +TEST_F(DataStreamE2ETest, SendTextSmallRoundTrip) { + const auto topic = makeTopic("send_text_small"); + auto rooms = testRooms(2); + auto sender = lockLocalParticipant(*rooms[0]); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamTextOptions options; + options.topic = topic; + options.attributes = {{"kind", "greeting"}}; + const auto sent = sender->sendText("hi there", options); + EXPECT_FALSE(sent.stream_id.empty()); + EXPECT_EQ(sent.topic, topic); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.text(), "hi there"); + EXPECT_EQ(collector.info().stream_id, sent.stream_id); + EXPECT_EQ(collector.info().mime_type, "text/plain"); + EXPECT_EQ(collector.info().attributes.at("kind"), "greeting"); + EXPECT_EQ(collector.senderIdentity(), sender->identity()); +} + +TEST_F(DataStreamE2ETest, SendTextLargeCompressedRoundTrip) { + const auto topic = makeTopic("send_text_large"); + const auto payload = compressibleText(50 * 1024); + auto rooms = testRooms(2); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamTextOptions options; + options.topic = topic; + (void)lockLocalParticipant(*rooms[0])->sendText(payload, options); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.text(), payload); +} + +TEST_F(DataStreamE2ETest, SendTextUncompressedRoundTrip) { + const auto topic = makeTopic("send_text_uncompressed"); + const auto payload = compressibleText(50 * 1024); + auto rooms = testRooms(2); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamTextOptions options; + options.topic = topic; + options.compress = false; + (void)lockLocalParticipant(*rooms[0])->sendText(payload, options); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.text(), payload); +} + +TEST_F(DataStreamE2ETest, SendTextUnicodeRoundTrip) { + const auto topic = makeTopic("send_text_unicode"); + // Larger than one 15 KB chunk, uncompressed, so multi-byte code points + // straddle chunk boundaries. + const auto payload = unicodeText(40 * 1024); + auto rooms = testRooms(2); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamTextOptions options; + options.topic = topic; + options.compress = false; + (void)lockLocalParticipant(*rooms[0])->sendText(payload, options); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.text(), payload); +} + +TEST_F(DataStreamE2ETest, SendBytesSmallRoundTrip) { + const auto topic = makeTopic("send_bytes"); + const std::vector payload{0x00, 0x01, 0xFE, 0xFF, 'o', 'k'}; + auto rooms = testRooms(2); + + ByteStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamByteOptions options; + options.topic = topic; + options.name = "blob.bin"; + options.mime_type = "application/x-test"; + const auto sent = lockLocalParticipant(*rooms[0])->sendBytes(payload, options); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for byte stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.content(), payload); + EXPECT_EQ(collector.info().stream_id, sent.stream_id); + EXPECT_EQ(collector.info().name, "blob.bin"); + EXPECT_EQ(collector.info().mime_type, "application/x-test"); +} + +TEST_F(DataStreamE2ETest, SendFileRoundTrip) { + const auto topic = makeTopic("send_file"); + const std::string file_name = "lk_send_file_" + std::to_string(getTimestampUs()) + ".txt"; + const std::string path = ::testing::TempDir() + file_name; + const auto payload = compressibleText(20 * 1024); + { + std::ofstream out(path, std::ios::binary); + out << payload; + } + auto rooms = testRooms(2); + + ByteStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamByteOptions options; + options.topic = topic; + const auto sent = lockLocalParticipant(*rooms[0])->sendFile(path, options); + EXPECT_EQ(sent.name, file_name) << "name defaults to the file's basename"; + EXPECT_FALSE(sent.mime_type.empty()); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for file stream"; + std::remove(path.c_str()); + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(std::string(collector.content().begin(), collector.content().end()), payload); + EXPECT_EQ(collector.info().name, file_name); + EXPECT_EQ(collector.info().mime_type, sent.mime_type); +} + +TEST_F(DataStreamE2ETest, SendFileMissingFileThrows) { + auto rooms = testRooms(1); + StreamByteOptions options; + options.topic = makeTopic("send_file_missing"); + EXPECT_THROW((void)lockLocalParticipant(*rooms[0])->sendFile(::testing::TempDir() + "no-such-file.bin", options), + DataStreamError); +} + +TEST_F(DataStreamE2ETest, SendAfterDisconnectThrows) { + auto rooms = testRooms(1); + auto sender = lockLocalParticipant(*rooms[0]); + ASSERT_TRUE(rooms[0]->disconnect()); + + StreamTextOptions text_options; + text_options.topic = makeTopic("after_disconnect"); + StreamByteOptions byte_options; + byte_options.topic = text_options.topic; + EXPECT_THROW((void)sender->sendText("late", text_options), DataStreamError); + EXPECT_THROW((void)sender->sendBytes({1}, byte_options), DataStreamError); +} + +// --------------------------------------------------------------------------- +// 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); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + TextStreamWriter writer(*lockLocalParticipant(*rooms[0]), topic, {{"header_key", "h"}}); + writer.write("body"); + writer.close("", {{"trailer_key", "t"}}); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.text(), "body"); + EXPECT_EQ(collector.info().attributes.at("header_key"), "h"); + EXPECT_EQ(collector.info().attributes.at("trailer_key"), "t"); +} + +TEST_F(DataStreamE2ETest, AbnormalCloseSurfacesError) { + const auto topic = makeTopic("abnormal_close"); + auto rooms = testRooms(2); + + ByteStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + ByteStreamWriter writer(*lockLocalParticipant(*rooms[0]), "partial.bin", topic); + writer.write({1, 2, 3}); + writer.close("boom"); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for byte stream"; + ASSERT_TRUE(collector.error().has_value()) << "a close with a reason must surface an error"; + EXPECT_NE(collector.error()->find("boom"), std::string::npos) << *collector.error(); + EXPECT_EQ(collector.content(), (std::vector{1, 2, 3})); +} + +TEST_F(DataStreamE2ETest, ReceiverDisconnectMidStreamWakesReader) { + const auto topic = makeTopic("receiver_disconnect"); + auto rooms = testRooms(2); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + TextStreamWriter writer(*lockLocalParticipant(*rooms[0]), topic); + writer.write("first part"); + // Give the receiver time to open the reader and block on the next chunk. + std::this_thread::sleep_for(1s); + ASSERT_TRUE(rooms[1]->disconnect()); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "A blocked reader must wake when its room disconnects"; + EXPECT_TRUE(collector.error().has_value()) << "an interrupted stream must surface an error"; + writer.close(); +} + +TEST_F(DataStreamE2ETest, ReaderCloseWakesPendingRead) { + const auto topic = makeTopic("reader_close"); + auto rooms = testRooms(2); + + std::mutex mutex; + std::condition_variable cv; + std::shared_ptr reader; + rooms[1]->registerTextStreamHandler(topic, [&](std::shared_ptr r, const std::string&) { + std::lock_guard lock(mutex); + reader = std::move(r); + cv.notify_all(); + }); + + TextStreamWriter writer(*lockLocalParticipant(*rooms[0]), topic); + writer.write("first"); + { + std::unique_lock lock(mutex); + ASSERT_TRUE(cv.wait_for(lock, kStreamWaitTimeout, [&] { return reader != nullptr; })); + } + + std::atomic chunks{0}; + std::atomic finished{false}; + std::thread read_thread([&] { + std::string chunk; + while (reader->readNext(chunk)) { + ++chunks; + } + finished = true; + }); + + std::this_thread::sleep_for(500ms); + EXPECT_FALSE(finished) << "reader should still be waiting for more data"; + reader->close(); + read_thread.join(); + EXPECT_TRUE(finished); + EXPECT_EQ(chunks.load(), 1); + writer.close(); +} + +TEST_F(DataStreamE2ETest, StreamHandlesAreReleased) { + const auto handled_topic = makeTopic("handled"); + const auto unhandled_topic = makeTopic("unhandled"); + constexpr std::size_t kUnhandledStreams = 20; + + auto rooms = testRooms(2); + auto sender = lockLocalParticipant(*rooms[0]); + // Only count streams that reach the receiver room. + OpenedStreamHandleRecorder recorder; + + TextStreamCollector collector; + collector.registerOn(*rooms[1], handled_topic); + + StreamTextOptions unhandled; + unhandled.topic = unhandled_topic; + for (std::size_t i = 0; i < kUnhandledStreams; ++i) { + (void)sender->sendText("nobody listens " + std::to_string(i), unhandled); + } + StreamTextOptions handled; + handled.topic = handled_topic; + (void)sender->sendText("somebody listens", handled); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)); + ASSERT_TRUE(recorder.waitForCount(kUnhandledStreams + 1, kStreamWaitTimeout)); + // The Room handles each opened event in the same callback that the recorder + // sees; allow a moment for the last one to finish. + std::this_thread::sleep_for(200ms); + + // Dropping a handle that the SDK already released (unhandled topic) or + // consumed (read) reports that it no longer exists. + for (const auto handle : recorder.handles()) { + EXPECT_FALSE(dropFfiHandle(handle)) << "reader handle " << handle << " was leaked"; + } +} + } // namespace livekit::test diff --git a/src/tests/unit/test_data_stream.cpp b/src/tests/unit/test_data_stream.cpp index 840f5e02..c399e422 100644 --- a/src/tests/unit/test_data_stream.cpp +++ b/src/tests/unit/test_data_stream.cpp @@ -16,11 +16,54 @@ #include #include +#include +#include +#include +#include +#include #include +#include "data_stream_proto_converter.h" +#include "ffi_client.h" +#include "room_proto_converter.h" + +namespace livekit { + +/// Feeds synthetic FFI reader events into detached readers. +struct DataStreamReaderTestAccess { + static void chunk(TextStreamReader& reader, std::string text) { reader.onChunkReceived(std::move(text)); } + static void chunk(ByteStreamReader& reader, std::vector bytes) { + reader.onChunkReceived(std::move(bytes)); + } + template + static void end(Reader& reader, const std::map& attributes = {}, + std::optional error = std::nullopt) { + reader.onStreamEnded(attributes, std::move(error)); + } +}; + +} // namespace livekit + namespace livekit::test { +using namespace std::chrono_literals; +using Access = DataStreamReaderTestAccess; + +namespace { + +// The proto is built inside liblivekit, which carries its own protobuf copy +// with a different hash seed; iterate instead of using Map::at() / find(). +std::map attrs(const google::protobuf::Map& in) { + std::map out; + for (const auto& kv : in) { + out.emplace(kv.first, kv.second); + } + return out; +} + +} // namespace + TEST(DataStreamTest, TextStreamReaderConstructAndInfo) { TextStreamInfo info; info.stream_id = "stream-1"; @@ -56,4 +99,268 @@ TEST(DataStreamTest, WriterTypesAreDerivedFromBase) { EXPECT_GT(kStreamChunkSize, 0u); } +// --------------------------------------------------------------------------- +// Reader state machine (detached readers fed synthetic events) +// --------------------------------------------------------------------------- + +TEST(DataStreamReaderTest, TextReaderDeliversChunksThenEnds) { + TextStreamReader reader(TextStreamInfo{}); + Access::chunk(reader, "hello, "); + Access::chunk(reader, "world"); + Access::end(reader); + EXPECT_EQ(reader.readAll(), "hello, world"); + + std::string out; + EXPECT_FALSE(reader.readNext(out)) << "readNext after the end keeps returning false"; +} + +TEST(DataStreamReaderTest, ByteReaderReadAllConcatenates) { + ByteStreamReader reader(ByteStreamInfo{}); + Access::chunk(reader, std::vector{1, 2}); + Access::chunk(reader, std::vector{3}); + Access::end(reader); + EXPECT_EQ(reader.readAll(), (std::vector{1, 2, 3})); +} + +TEST(DataStreamReaderTest, EndAttributesAreMergedAfterEnd) { + TextStreamInfo info; + info.attributes = {{"header", "h"}, {"shared", "old"}}; + TextStreamReader reader(info); + Access::chunk(reader, "x"); + Access::end(reader, {{"trailer", "t"}, {"shared", "new"}}); + + std::string out; + ASSERT_TRUE(reader.readNext(out)); + EXPECT_EQ(reader.info().attributes.count("trailer"), 0u) << "attributes are merged only once the end is reached"; + EXPECT_FALSE(reader.readNext(out)); + EXPECT_EQ(reader.info().attributes.at("header"), "h"); + EXPECT_EQ(reader.info().attributes.at("trailer"), "t"); + EXPECT_EQ(reader.info().attributes.at("shared"), "new"); +} + +TEST(DataStreamReaderTest, ErrorIsThrownAfterBufferedChunks) { + ByteStreamReader reader(ByteStreamInfo{}); + Access::chunk(reader, std::vector{42}); + Access::end(reader, {}, std::string("stream closed abnormally: boom")); + + std::vector out; + ASSERT_TRUE(reader.readNext(out)); + EXPECT_EQ(out, std::vector{42}); + try { + (void)reader.readNext(out); + FAIL() << "expected DataStreamError"; + } catch (const DataStreamError& e) { + EXPECT_NE(std::string(e.what()).find("boom"), std::string::npos); + } + EXPECT_THROW((void)reader.readNext(out), DataStreamError) << "the error is sticky"; +} + +TEST(DataStreamReaderTest, ReadAllThrowsOnError) { + TextStreamReader reader(TextStreamInfo{}); + Access::chunk(reader, "partial"); + Access::end(reader, {}, std::string("Disconnected while receiving")); + EXPECT_THROW((void)reader.readAll(), DataStreamError); +} + +TEST(DataStreamReaderTest, DataStreamErrorIsARuntimeError) { + TextStreamReader reader(TextStreamInfo{}); + Access::end(reader, {}, std::string("boom")); + EXPECT_THROW((void)reader.readAll(), std::runtime_error); +} + +TEST(DataStreamReaderTest, CloseWakesBlockedRead) { + auto reader = std::make_shared(TextStreamInfo{}); + auto result = std::async(std::launch::async, [reader] { + std::string out; + return reader->readNext(out); + }); + EXPECT_EQ(result.wait_for(100ms), std::future_status::timeout) << "readNext should block with no data"; + + reader->close(); + ASSERT_EQ(result.wait_for(5s), std::future_status::ready); + EXPECT_FALSE(result.get()); +} + +TEST(DataStreamReaderTest, CloseDiscardsBufferedDataAndIsIdempotent) { + ByteStreamReader reader(ByteStreamInfo{}); + Access::chunk(reader, std::vector{1}); + reader.close(); + reader.close(); + Access::chunk(reader, std::vector{2}); + Access::end(reader, {}, std::string("ignored after close")); + + std::vector out; + EXPECT_FALSE(reader.readNext(out)); + EXPECT_TRUE(reader.readAll().empty()); +} + +TEST(DataStreamReaderTest, TerminalErrorWakesBlockedRead) { + auto reader = std::make_shared(ByteStreamInfo{}); + auto result = std::async(std::launch::async, [reader] { return reader->readAll(); }); + EXPECT_EQ(result.wait_for(100ms), std::future_status::timeout); + + Access::end(*reader, {}, std::string("Disconnected while receiving")); + ASSERT_EQ(result.wait_for(5s), std::future_status::ready); + EXPECT_THROW((void)result.get(), DataStreamError); +} + +// --------------------------------------------------------------------------- +// Option / info conversion +// --------------------------------------------------------------------------- + +TEST(DataStreamConversionTest, TextOptionsDefaultsToProto) { + StreamTextOptions options; + options.topic = "chat"; + const auto proto = toProto(options); + EXPECT_EQ(proto.topic(), "chat"); + ASSERT_TRUE(proto.has_compress()) << "compress is always sent explicitly"; + EXPECT_TRUE(proto.compress()); + EXPECT_FALSE(proto.has_id()); + EXPECT_FALSE(proto.has_reply_to_stream_id()); + EXPECT_FALSE(proto.has_sender_identity()); + EXPECT_FALSE(proto.has_operation_type()); + EXPECT_EQ(proto.destination_identities_size(), 0); +} + +TEST(DataStreamConversionTest, TextOptionsAllFieldsToProto) { + StreamTextOptions options; + options.topic = "chat"; + options.attributes = {{"k", "v"}}; + options.destination_identities = {"alice", "bob"}; + options.stream_id = "stream-1"; + options.reply_to_stream_id = "stream-0"; + options.attached_stream_ids = {"file-1"}; + options.compress = false; + options.sender_identity = "agent"; + + const auto proto = toProto(options); + EXPECT_EQ(attrs(proto.attributes()), (std::map{{"k", "v"}})); + ASSERT_EQ(proto.destination_identities_size(), 2); + EXPECT_EQ(proto.destination_identities(1), "bob"); + EXPECT_EQ(proto.id(), "stream-1"); + EXPECT_EQ(proto.reply_to_stream_id(), "stream-0"); + ASSERT_EQ(proto.attached_stream_ids_size(), 1); + EXPECT_EQ(proto.attached_stream_ids(0), "file-1"); + ASSERT_TRUE(proto.has_compress()); + EXPECT_FALSE(proto.compress()); + EXPECT_EQ(proto.sender_identity(), "agent"); +} + +TEST(DataStreamConversionTest, ByteOptionsToProto) { + StreamByteOptions defaults; + defaults.topic = "files"; + const auto unset = toProto(defaults); + EXPECT_TRUE(unset.has_compress()); + EXPECT_TRUE(unset.compress()); + EXPECT_FALSE(unset.has_name()); + EXPECT_FALSE(unset.has_mime_type()); + EXPECT_FALSE(unset.has_total_length()); + EXPECT_FALSE(unset.has_id()); + EXPECT_FALSE(unset.has_sender_identity()); + + StreamByteOptions options; + options.topic = "files"; + options.attributes = {{"k", "v"}}; + options.destination_identities = {"alice"}; + options.stream_id = "stream-2"; + options.name = "photo.jpg"; + options.mime_type = "image/jpeg"; + options.total_length = 1234; + options.compress = false; + options.sender_identity = "agent"; + const auto proto = toProto(options); + EXPECT_EQ(proto.topic(), "files"); + EXPECT_EQ(attrs(proto.attributes()), (std::map{{"k", "v"}})); + EXPECT_EQ(proto.destination_identities(0), "alice"); + EXPECT_EQ(proto.id(), "stream-2"); + EXPECT_EQ(proto.name(), "photo.jpg"); + EXPECT_EQ(proto.mime_type(), "image/jpeg"); + EXPECT_EQ(proto.total_length(), 1234u); + EXPECT_FALSE(proto.compress()); + EXPECT_EQ(proto.sender_identity(), "agent"); +} + +TEST(DataStreamConversionTest, TextInfoFromProto) { + proto::TextStreamInfo in; + in.set_stream_id("s1"); + in.set_timestamp(99); + in.set_mime_type("text/plain"); + in.set_topic("chat"); + (*in.mutable_attributes())["k"] = "v"; + in.add_attached_stream_ids("a1"); + in.set_reply_to_stream_id("s0"); + + auto out = fromProto(in); + EXPECT_EQ(out.stream_id, "s1"); + EXPECT_EQ(out.timestamp, 99); + EXPECT_EQ(out.mime_type, "text/plain"); + EXPECT_EQ(out.topic, "chat"); + EXPECT_EQ(out.attributes.at("k"), "v"); + EXPECT_EQ(out.attachments, std::vector{"a1"}); + ASSERT_TRUE(out.reply_to_stream_id.has_value()); + EXPECT_EQ(*out.reply_to_stream_id, "s0"); + EXPECT_FALSE(out.size.has_value()) << "an absent total_length stays unset"; + + in.set_total_length(10); + in.clear_reply_to_stream_id(); + out = fromProto(in); + ASSERT_TRUE(out.size.has_value()); + EXPECT_EQ(*out.size, 10u); + EXPECT_FALSE(out.reply_to_stream_id.has_value()); +} + +TEST(DataStreamConversionTest, ByteInfoFromProto) { + proto::ByteStreamInfo in; + in.set_stream_id("s2"); + in.set_timestamp(5); + in.set_mime_type("image/png"); + in.set_topic("files"); + in.set_name("a.png"); + in.set_total_length(2048); + + const auto out = fromProto(in); + EXPECT_EQ(out.stream_id, "s2"); + EXPECT_EQ(out.mime_type, "image/png"); + EXPECT_EQ(out.topic, "files"); + EXPECT_EQ(out.name, "a.png"); + ASSERT_TRUE(out.size.has_value()); + 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 +// --------------------------------------------------------------------------- + +TEST(DataStreamSendTest, SendsThrowWhenNotInitialized) { + ASSERT_FALSE(FfiClient::instance().isInitialized()); + LocalParticipant participant(FfiHandle(0), "sid", "name", "identity", "", {}, ParticipantKind::Standard, + DisconnectReason::Unknown); + StreamTextOptions text_options; + text_options.topic = "t"; + StreamByteOptions byte_options; + byte_options.topic = "t"; + EXPECT_THROW((void)participant.sendText("hi", text_options), DataStreamError); + EXPECT_THROW((void)participant.sendBytes({1, 2}, byte_options), DataStreamError); + EXPECT_THROW((void)participant.sendFile("/tmp/does-not-matter", byte_options), DataStreamError); +} + +TEST(DataStreamSendTest, FfiHelpersThrowWhenNotInitialized) { + ASSERT_FALSE(FfiClient::instance().isInitialized()); + EXPECT_THROW(FfiClient::instance().sendTextAsync(1, "hi", proto::StreamTextOptions{}), std::runtime_error); + EXPECT_THROW(FfiClient::instance().sendBytesAsync(1, {1}, proto::StreamByteOptions{}), std::runtime_error); + EXPECT_THROW(FfiClient::instance().sendFileAsync(1, "/tmp/x", proto::StreamByteOptions{}), std::runtime_error); + EXPECT_THROW(FfiClient::instance().textStreamReadIncremental(1), std::runtime_error); + EXPECT_THROW(FfiClient::instance().byteStreamReadIncremental(1), std::runtime_error); +} + } // namespace livekit::test From a1d3053d789d99de280bcb44d47b2385fd8e8e23 Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 23 Nov 2026 08:24:18 +1300 Subject: [PATCH 05/11] Merge identical no-op switch cases to satisfy clang-tidy kChatMessage and the low-level stream packet events both just break, which bugprone-branch-clone flags as consecutive identical branches. Co-Authored-By: Claude Opus 5.5 --- src/room.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/room.cpp b/src/room.cpp index 437d0e94..28e69ef7 100644 --- a/src/room.cpp +++ b/src/room.cpp @@ -1322,10 +1322,8 @@ void Room::onEvent(const FfiEvent& event) { } break; } - case proto::RoomEvent::kChatMessage: { - // Deprecated event, do nothing. - break; - } + case proto::RoomEvent::kChatMessage: + // Deprecated event, do nothing. case proto::RoomEvent::kStreamHeaderReceived: case proto::RoomEvent::kStreamChunkReceived: case proto::RoomEvent::kStreamTrailerReceived: { From 8dd2cc312b5a5d97e339aba2b14ef56462577427 Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Fri, 20 Nov 2026 13:46:14 +1300 Subject: [PATCH 06/11] Port data stream writers to FFI writer handles; add streamText/streamBytes TextStreamWriter / ByteStreamWriter now open an FFI writer (text/byte_stream_open) and send through text/byte_stream_write and *_stream_close instead of hand-built header/chunk/trailer packets. Rust does the chunking and UTF-8 splitting. - LocalParticipant::streamText / streamBytes return an already-open writer (blocking until the open callback, throwing DataStreamError on failure). The public writer constructors keep working but are deprecated; they open lazily on the first write or close, as the header did before. - write() and close() share one mutex and each waits for its FFI callback, so a close never overtakes an in-flight write (python-sdks#879); this also fixes close() not taking the write lock. - A LocalParticipant tracks its writers in a registry shared with them. On disconnect (or participant destruction) every writer is closed and its handle dropped, so later write/close throw DataStreamError instead of reaching an FFI session that would panic. - A writer destroyed without close() sends a non-waiting FFI close. Rust's writer only sends its drop-time trailer from a Tokio thread, so a plain handle drop from C++ left receivers waiting forever. - kStreamChunkSize and the protected ensureHeaderSent / sendChunk / sendTrailer helpers are deprecated and reimplemented on the new path. - Removed FfiClient::sendStream*Async, splitUtf8 and the now-unused header/chunk/trailer converters. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- CMakeLists.txt | 1 + include/livekit/data_stream.h | 198 ++++++++-- include/livekit/local_participant.h | 50 ++- src/data_stream.cpp | 390 ++++++++++++++------ src/data_stream_writer_registry.h | 62 ++++ src/ffi_client.cpp | 215 ++++++++--- src/ffi_client.h | 25 +- src/local_participant.cpp | 25 +- src/room_proto_converter.cpp | 145 -------- src/room_proto_converter.h | 15 - src/tests/integration/test_data_streams.cpp | 278 ++++++++++++-- src/tests/unit/test_data_stream.cpp | 92 +++++ src/tests/unit/test_ffi_client.cpp | 25 +- 14 files changed, 1107 insertions(+), 416 deletions(-) create mode 100644 src/data_stream_writer_registry.h diff --git a/AGENTS.md b/AGENTS.md index 9901a51a..a747984a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -78,7 +78,7 @@ All `RoomDelegate` callbacks and stream handler callbacks (e.g., `registerTextSt | `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()`. | | `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_`. | +| `TextStreamWriter` / `ByteStreamWriter` | Serialized | `write()` and `close()` are serialized by an internal mutex and each waits for its FFI callback, so `close()` never overtakes a write. `LocalParticipant` closes its writers on disconnect (via a shared registry, so writers may outlive the participant); later calls throw `DataStreamError`. Create writers with `LocalParticipant::streamText` / `streamBytes`; the constructors are deprecated. | ### Directory Layout Be sure to update the directory layout in this file if the directory layout changes. diff --git a/CMakeLists.txt b/CMakeLists.txt index 17a1fcef..44c487bc 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -424,6 +424,7 @@ add_library(livekit SHARED src/data_stream.cpp src/data_stream_proto_converter.cpp src/data_stream_proto_converter.h + src/data_stream_writer_registry.h src/data_track_error.cpp src/data_track_schema.cpp src/data_track_stream.cpp diff --git a/include/livekit/data_stream.h b/include/livekit/data_stream.h index 8d02b41c..0e1635e7 100644 --- a/include/livekit/data_stream.h +++ b/include/livekit/data_stream.h @@ -16,6 +16,7 @@ #pragma once +#include #include #include #include @@ -34,9 +35,15 @@ namespace livekit { class LocalParticipant; +namespace detail { +class StreamWriterRegistry; +} // namespace detail + /// Chunk size for data streams (matches Python STREAM_CHUNK_SIZE). -/// Chosen to balance throughput and latency, and to work well with WebRTC data -/// channels. +/// +/// @deprecated The SDK core now chunks data streams itself (at 15 KB); this +/// constant no longer controls anything. +[[deprecated("kStreamChunkSize no longer controls chunking; the SDK core chunks data streams itself")]] constexpr std::size_t kStreamChunkSize = 15'000; // 15 KB /// @brief Error raised by data stream operations. @@ -324,29 +331,58 @@ class LIVEKIT_API ByteStreamReader { std::unique_ptr impl_; }; -/// Base class for sending data streams. -/// Concrete subclasses are TextStreamWriter and ByteStreamWriter. +/// @brief Base class for sending data streams incrementally. +/// +/// Concrete subclasses are TextStreamWriter and ByteStreamWriter; create them +/// with LocalParticipant::streamText() / LocalParticipant::streamBytes(). +/// +/// Thread safety: write() and close() are serialized internally, and each one +/// returns only after the SDK has processed it, so a close() always follows +/// every write() that returned before it. When the room disconnects, the +/// writer is closed and later write() / close() calls throw DataStreamError. +/// +/// Destroying a writer that was opened but not closed closes the stream +/// normally (without waiting), so receivers don't wait forever. class LIVEKIT_API BaseStreamWriter { public: - virtual ~BaseStreamWriter() = default; + virtual ~BaseStreamWriter(); + + BaseStreamWriter(const BaseStreamWriter&) = delete; + BaseStreamWriter& operator=(const BaseStreamWriter&) = delete; - /// Stream id assigned to this writer. + /// @brief Stream id assigned to this writer. + /// @return The stream id. const std::string& streamId() const noexcept { return stream_id_; } - /// Topic of this stream. + /// @brief Topic of this stream. + /// @return The topic. const std::string& topic() const noexcept { return topic_; } - /// MIME type for this stream. + /// @brief MIME type for this stream. + /// @return The MIME type. const std::string& mimeType() const noexcept { return mime_type_; } - /// Timestamp (ms) when the stream was created. + /// @brief Timestamp (ms) when the stream was created. + /// + /// Updated to the SDK core's timestamp once the stream is opened. + /// @return Creation timestamp in milliseconds since the Unix epoch. std::int64_t timestampMs() const noexcept { return timestamp_ms_; } - /// Whether the stream has been closed. + /// @brief Whether the stream has been closed (explicitly or because the room + /// disconnected). + /// @return True if closed. bool isClosed() const noexcept { return closed_; } - /// Close the stream with optional reason and attributes. - /// Throws on FFI error or if already closed. + /// @brief Close the stream. + /// + /// Waits for any in-progress write() to finish first. A non-empty @p reason + /// closes the stream abnormally: receivers' reads throw DataStreamError + /// carrying the reason. + /// + /// @param reason Empty for a normal close; otherwise the error reason. + /// @param attributes Attributes merged into the receiver's stream info. + /// @throws DataStreamError if the stream is already closed, the room has + /// disconnected, or the SDK reports an error. void close(const std::string& reason = "", const std::map& attributes = {}); protected: @@ -369,51 +405,141 @@ class LIVEKIT_API BaseStreamWriter { std::vector destination_identities_; std::string sender_identity_; - bool closed_ = false; + std::atomic closed_{false}; + /// True once the stream has been opened with the SDK core. bool header_sent_ = false; + /// Unused; chunking is done by the SDK core. std::uint64_t next_chunk_index_ = 0; StreamKind kind_ = StreamKind::kUnknown; std::string reply_to_id_; std::string byte_name_; // Used by ByteStreamWriter - /// Ensure the header has been sent once. - /// Throws on error. + /// @brief Open the stream if it isn't open yet. + /// @deprecated The SDK opens the stream on the first write() or close(). + /// @throws DataStreamError on error. + [[deprecated("BaseStreamWriter::ensureHeaderSent is deprecated; the stream opens on the first write or close")]] void ensureHeaderSent(); - /// Send a raw chunk of bytes. - /// Throws on error or if stream is closed. + /// @brief Write raw bytes to the stream (UTF-8 text for a text stream). + /// @deprecated Use TextStreamWriter::write() or ByteStreamWriter::write() instead. + /// @param content Payload to write. + /// @throws std::runtime_error if the stream is closed; DataStreamError on error. + [[deprecated( + "BaseStreamWriter::sendChunk is deprecated; use TextStreamWriter::write or ByteStreamWriter::write " + "instead")]] void sendChunk(const std::vector& content); - /// Send the trailer with given reason and attributes. - /// Throws on error. + /// @brief Close the stream with the given reason and attributes. + /// @deprecated Use close() instead. + /// @param reason Empty for a normal close; otherwise the error reason. + /// @param attributes Attributes merged into the receiver's stream info. + /// @throws DataStreamError on error. + [[deprecated("BaseStreamWriter::sendTrailer is deprecated; use BaseStreamWriter::close instead")]] void sendTrailer(const std::string& reason, const std::map& attributes); + + /// @brief Open the stream now (requires @c kind_ to be set). Serialized with + /// write() and close(). + /// @throws DataStreamError on error. + void open(); + + /// @brief Write a payload (text for kText, bytes for kByte), opening first if + /// needed. Serialized with other operations. + /// @param data Payload bytes. + /// @param size Payload size. + /// @param closed_message Message thrown if the writer is already closed. + /// @throws DataStreamError on error. + void writePayload(const char* data, std::size_t size, const char* closed_message); + +private: + friend class detail::StreamWriterRegistry; + + void openLocked(); + void closeLocked(const std::string& reason, const std::map& attributes); + void applyOpenedInfo(std::int64_t timestamp_ms, const std::string& mime_type); + std::uint64_t takeHandle() noexcept; + void onParticipantDisconnected() noexcept; + [[noreturn]] void throwNotConnected() const; + + /// Serializes open/write/close. Held across FFI waits. + std::mutex op_mutex_; + /// Guards writer_handle_ and participant_gone_. Never held across FFI calls. + mutable std::mutex state_mutex_; + /// Owned FFI writer handle; 0 before open and after close consumes it. + std::uint64_t writer_handle_ = 0; + bool participant_gone_ = false; + std::shared_ptr registry_; }; -/// Writer for outgoing text streams. +/// @brief Writer for outgoing text streams. +/// +/// Create one with LocalParticipant::streamText(). Text is sent as UTF-8; the +/// SDK splits it into chunks on code point boundaries. class LIVEKIT_API TextStreamWriter : public BaseStreamWriter { public: + /// @brief Construct a text stream writer. + /// + /// The stream is opened lazily on the first write() or close(). + /// + /// @deprecated Use LocalParticipant::streamText() instead. + /// @param local_participant Participant that sends the stream; must outlive the writer. + /// @param topic Topic receivers register handlers on. + /// @param attributes Attributes sent with the stream header. + /// @param stream_id Stream id; generated when empty. + /// @param total_size Recorded locally in info() only; text streams can't transmit a size. + /// @param reply_to_id Id of the stream this one replies to, or empty. + /// @param destination_identities Recipients; empty for everyone. + /// @param sender_identity Identity to send as; defaults to the local participant. + [[deprecated("Constructing TextStreamWriter directly is deprecated; use LocalParticipant::streamText instead")]] TextStreamWriter(LocalParticipant& local_participant, const std::string& topic = "", const std::map& attributes = {}, const std::string& stream_id = "", std::optional total_size = std::nullopt, const std::string& reply_to_id = "", const std::vector& destination_identities = {}, const std::string& sender_identity = ""); - /// Write a UTF-8 string to the stream. - /// Data will be split into chunks of at most kStreamChunkSize bytes. - /// Throws on error or if the stream is closed. + /// @brief Write a UTF-8 string to the stream. + /// + /// Blocks until the SDK has sent it. + /// + /// @param text UTF-8 text to append. + /// @throws DataStreamError if the stream is closed, the room has + /// disconnected, or the SDK reports an error. void write(const std::string& text); - /// Metadata associated with this stream. + /// @brief Metadata associated with this stream. + /// @return Stream metadata; updated with the SDK core's info once opened. const TextStreamInfo& info() const noexcept { return info_; } private: + friend class BaseStreamWriter; + friend class LocalParticipant; + struct FactoryTag {}; + + TextStreamWriter(FactoryTag, LocalParticipant& local_participant, const StreamTextOptions& options); + TextStreamInfo info_; - std::mutex write_mutex_; + std::vector attached_stream_ids_; }; -/// Writer for outgoing byte streams. +/// @brief Writer for outgoing byte streams. +/// +/// Create one with LocalParticipant::streamBytes(). class LIVEKIT_API ByteStreamWriter : public BaseStreamWriter { public: + /// @brief Construct a byte stream writer. + /// + /// The stream is opened lazily on the first write() or close(). + /// + /// @deprecated Use LocalParticipant::streamBytes() instead. + /// @param local_participant Participant that sends the stream; must outlive the writer. + /// @param name Name of the payload (for example a file name). + /// @param topic Topic receivers register handlers on. + /// @param attributes Attributes sent with the stream header. + /// @param stream_id Stream id; generated when empty. + /// @param total_size Total payload size, if known. + /// @param mime_type MIME type of the payload. + /// @param destination_identities Recipients; empty for everyone. + /// @param sender_identity Identity to send as; defaults to the local participant. + [[deprecated("Constructing ByteStreamWriter directly is deprecated; use LocalParticipant::streamBytes instead")]] ByteStreamWriter(LocalParticipant& local_participant, const std::string& name, const std::string& topic = "", const std::map& attributes = {}, const std::string& stream_id = "", std::optional total_size = std::nullopt, @@ -421,17 +547,27 @@ class LIVEKIT_API ByteStreamWriter : public BaseStreamWriter { const std::vector& destination_identities = {}, const std::string& sender_identity = ""); - /// Write binary data to the stream. - /// Data will be chunked into kStreamChunkSize-sized chunks. - /// Throws on error or if the stream is closed. + /// @brief Write binary data to the stream. + /// + /// Blocks until the SDK has sent it. + /// + /// @param data Bytes to append. + /// @throws DataStreamError if the stream is closed, the room has + /// disconnected, or the SDK reports an error. void write(const std::vector& data); - /// Metadata associated with this stream. + /// @brief Metadata associated with this stream. + /// @return Stream metadata; updated with the SDK core's info once opened. const ByteStreamInfo& info() const noexcept { return info_; } private: + friend class BaseStreamWriter; + friend class LocalParticipant; + struct FactoryTag {}; + + ByteStreamWriter(FactoryTag, LocalParticipant& local_participant, const StreamByteOptions& options); + ByteStreamInfo info_; - std::mutex write_mutex_; }; /// Callback invoked when a new incoming text stream is opened. diff --git a/include/livekit/local_participant.h b/include/livekit/local_participant.h index c9ff7c10..4d764ae7 100644 --- a/include/livekit/local_participant.h +++ b/include/livekit/local_participant.h @@ -47,6 +47,9 @@ struct ParticipantTrackPermission; class FfiClient; class Track; +namespace detail { +class StreamWriterRegistry; +} // namespace detail class LocalTrackPublication; /// @brief Data passed to a registered RPC method handler. @@ -76,6 +79,12 @@ class LIVEKIT_API LocalParticipant : public Participant { LocalParticipant(FfiHandle handle, std::string sid, std::string name, std::string identity, std::string metadata, std::unordered_map attributes, ParticipantKind kind, DisconnectReason reason); + ~LocalParticipant() override; + + LocalParticipant(const LocalParticipant&) = delete; + LocalParticipant& operator=(const LocalParticipant&) = delete; + LocalParticipant(LocalParticipant&&) = delete; + LocalParticipant& operator=(LocalParticipant&&) = delete; /// Track publications for this participant, keyed by publication SID. /// @@ -137,6 +146,36 @@ class LIVEKIT_API LocalParticipant : public Participant { /// if the room is no longer connected or the SDK isn't initialized. ByteStreamInfo sendFile(const std::string& path, const StreamByteOptions& options); + /// @brief Open a text stream for incremental writes. + /// + /// Blocks until the stream is open. Write with TextStreamWriter::write() and + /// finish with TextStreamWriter::close(). Incremental streams are never + /// compressed; @c options.compress is ignored. Use sendText() when the whole + /// text is available up front. + /// + /// @param options Topic (required), destinations, attributes, and so on. + /// @return An open writer. It must not outlive this participant's room + /// connection in a meaningful way: once the room disconnects, its + /// write() and close() throw DataStreamError. + /// @throws DataStreamError if the open fails, or if the room is no longer + /// connected or the SDK isn't initialized. + std::unique_ptr streamText(const StreamTextOptions& options); + + /// @brief Open a byte stream for incremental writes. + /// + /// Blocks until the stream is open. Write with ByteStreamWriter::write() and + /// finish with ByteStreamWriter::close(). Incremental streams are never + /// compressed; @c options.compress is ignored. Use sendBytes() or sendFile() + /// when the whole payload is available up front. + /// + /// @param options Topic (required), name, MIME type, total length, + /// destinations, and so on. + /// @return An open writer. Once the room disconnects, its write() and + /// close() throw DataStreamError. + /// @throws DataStreamError if the open fails, or if the room is no longer + /// connected or the SDK isn't initialized. + std::unique_ptr streamBytes(const StreamByteOptions& options); + /// Publish a SIP DTMF (phone keypad) tone into the room. /// /// Only meaningful when a SIP trunk is bridging a phone call into the @@ -346,9 +385,12 @@ class LIVEKIT_API LocalParticipant : public Participant { /// prune expired @c weak_ptr entries. mutable TrackMap published_tracks_by_sid_; + friend class BaseStreamWriter; + /// Marks the participant as disconnected so data stream sends fail fast in - /// C++ instead of reaching an FFI participant whose session is gone. - void markDisconnected() noexcept { disconnected_.store(true, std::memory_order_release); } + /// C++ instead of reaching an FFI participant whose session is gone, and + /// closes every open stream writer. + void markDisconnected() noexcept; /// Returns the FFI handle id for a data stream operation, or throws /// DataStreamError if the participant can no longer send. @@ -360,6 +402,10 @@ class LIVEKIT_API LocalParticipant : public Participant { /// Room::lock_ so send paths never need the room lock. std::atomic disconnected_{false}; + /// Stream writers created for this participant; shared with the writers so + /// they never touch a destroyed participant. + std::shared_ptr stream_writers_; + // Shared state for RPC invocation tracking. Using shared_ptr so the state // can outlive the LocalParticipant if there are in-flight invocations when // the participant is destroyed. diff --git a/src/data_stream.cpp b/src/data_stream.cpp index 0d88da8e..efb12ecd 100644 --- a/src/data_stream.cpp +++ b/src/data_stream.cpp @@ -24,6 +24,8 @@ #include #include +#include "data_stream_proto_converter.h" +#include "data_stream_writer_registry.h" #include "ffi_client.h" #include "livekit/local_participant.h" #include "lk_log.h" @@ -48,44 +50,6 @@ std::string generateRandomId(std::size_t bytes = 16) { return out; } -// Split UTF-8 string into chunks of at most max_bytes, not breaking codepoints. -std::vector splitUtf8(const std::string& s, std::size_t max_bytes) { - std::vector result; - if (s.empty()) { - return result; - } - - std::size_t i = 0; - const std::size_t n = s.size(); - - while (i < n) { - std::size_t end = std::min(i + max_bytes, n); - - // If end points into a UTF-8 continuation byte, walk back to a lead byte. - // NOTE: end is an index into the string; ensure end < n before indexing. - while (end > i && end < n && (static_cast(s[end]) & 0xC0) == 0x80) { - --end; - } - // If end==n, we may still have landed on a continuation byte due to min(). - while (end > i && end == n && (static_cast(s[end - 1]) & 0xC0) == 0x80) { - // Walk back until we hit a lead byte boundary. - // This isn't perfect but is consistent with your earlier intent. - --end; - // If we backed up too far, fall through to fallback. - } - - if (end == i) { - // Fallback: avoid infinite loop if bytes are pathological. - end = std::min(i + max_bytes, n); - } - - result.emplace_back(s.substr(i, end - i)); - i = end; - } - - return result; -} - void fillBaseInfo(BaseStreamInfo& dst, const std::string& stream_id, const std::string& mime_type, const std::string& topic, std::int64_t timestamp_ms, const std::optional& total_size, const std::map& attrs) { @@ -254,9 +218,56 @@ std::vector ByteStreamReader::readAll() { void ByteStreamReader::close() { impl_->close(); } // ===================================================================== -// Writer implementation (uses your future-based FfiClient) +// Writer registry // ===================================================================== +namespace detail { + +bool StreamWriterRegistry::add(BaseStreamWriter* writer) { + const std::scoped_lock lock(mutex_); + if (closed_) { + return false; + } + writers_.insert(writer); + return true; +} + +void StreamWriterRegistry::remove(BaseStreamWriter* writer) { + const std::scoped_lock lock(mutex_); + writers_.erase(writer); +} + +std::uint64_t StreamWriterRegistry::participantHandle() const { + const std::scoped_lock lock(mutex_); + if (closed_) { + throw DataStreamError("stream writer: not connected"); + } + return participant_handle_; +} + +void StreamWriterRegistry::closeAll() noexcept { + // Held while notifying writers so a writer being destroyed (which calls + // remove()) stays alive until it has been notified. + const std::scoped_lock lock(mutex_); + closed_ = true; + for (auto* writer : writers_) { + writer->onParticipantDisconnected(); + } + writers_.clear(); +} + +} // namespace detail + +// ===================================================================== +// Writer implementation +// ===================================================================== + +namespace { + +constexpr char kWriterNotConnected[] = "stream writer: not connected"; + +} // namespace + BaseStreamWriter::BaseStreamWriter(LocalParticipant& local_participant, std::string topic, std::map attributes, std::string stream_id, std::optional total_size, std::string mime_type, @@ -271,81 +282,234 @@ BaseStreamWriter::BaseStreamWriter(LocalParticipant& local_participant, std::str total_size_(total_size), attributes_(std::move(attributes)), destination_identities_(std::move(destination_identities)), - sender_identity_(std::move(sender_identity)) { + sender_identity_(std::move(sender_identity)), + registry_(local_participant.stream_writers_) { if (sender_identity_.empty()) { sender_identity_ = local_participant_.identity(); } + if (!registry_->add(this)) { + // Created after the room disconnected: usable only to fail cleanly. + participant_gone_ = true; + closed_ = true; + } } -void BaseStreamWriter::ensureHeaderSent() { - if (header_sent_) { +BaseStreamWriter::~BaseStreamWriter() { + // After remove() returns, closeAll() can no longer reach this writer. + registry_->remove(this); + + const std::uint64_t handle = takeHandle(); + if (handle == 0) { return; } - proto::DataStream::Header header; - header.set_stream_id(stream_id_); - header.set_timestamp(timestamp_ms_); - header.set_mime_type(mime_type_); - header.set_topic(topic_); - - if (total_size_.has_value()) { - header.set_total_length(static_cast(*total_size_)); + // Opened but never closed. Rust's writer sends a trailer when dropped, but + // only from a Tokio thread; dropping the handle here (a C++ thread) would + // skip it and leave receivers waiting. Close explicitly, without waiting. + try { + if (kind_ == StreamKind::kText) { + (void)FfiClient::instance().textStreamCloseAsync(handle, std::nullopt, {}); + } else { + (void)FfiClient::instance().byteStreamCloseAsync(handle, std::nullopt, {}); + } + } catch (const std::exception& e) { + LK_LOG_DEBUG("Stream writer {} could not be closed on destruction: {}", stream_id_, e.what()); + (void)dropFfiHandle(handle); + } catch (...) { + (void)dropFfiHandle(handle); } - for (const auto& kv : attributes_) { - (*header.mutable_attributes())[kv.first] = kv.second; +} + +std::uint64_t BaseStreamWriter::takeHandle() noexcept { + const std::scoped_lock lock(state_mutex_); + const std::uint64_t handle = writer_handle_; + writer_handle_ = 0; + return handle; +} + +void BaseStreamWriter::onParticipantDisconnected() noexcept { + std::uint64_t handle = 0; + { + const std::scoped_lock lock(state_mutex_); + participant_gone_ = true; + closed_ = true; + handle = writer_handle_; + writer_handle_ = 0; } - if (kind_ == StreamKind::kText) { - auto* th = header.mutable_text_header(); - th->set_operation_type(proto::DataStream::OperationType::DataStream_OperationType_CREATE); - if (!reply_to_id_.empty()) { - th->set_reply_to_stream_id(reply_to_id_); - } - } else if (kind_ == StreamKind::kByte) { - header.mutable_byte_header()->set_name(byte_name_); + // The room is gone; there's nobody to send a trailer to. + if (handle != 0) { + (void)dropFfiHandle(handle); } +} + +void BaseStreamWriter::throwNotConnected() const { throw DataStreamError(kWriterNotConnected); } - FfiClient::instance() - .sendStreamHeaderAsync(local_participant_.ffiHandleId(), header, destination_identities_, sender_identity_) - .get(); +void BaseStreamWriter::applyOpenedInfo(std::int64_t timestamp_ms, const std::string& mime_type) { + timestamp_ms_ = timestamp_ms; + mime_type_ = mime_type; header_sent_ = true; } -void BaseStreamWriter::sendChunk(const std::vector& content) { - if (closed_) { - throw std::runtime_error("Cannot send chunk after stream is closed"); +void BaseStreamWriter::openLocked() { + { + const std::scoped_lock lock(state_mutex_); + if (participant_gone_) { + throwNotConnected(); + } + if (writer_handle_ != 0) { + return; + } } - ensureHeaderSent(); - - proto::DataStream::Chunk chunk; - chunk.set_stream_id(stream_id_); - chunk.set_chunk_index(next_chunk_index_++); // ✅ uses the new member - chunk.set_content(content.data(), content.size()); + const std::uint64_t participant_handle = registry_->participantHandle(); + std::uint64_t handle = 0; + if (kind_ == StreamKind::kText) { + auto* self = static_cast(this); + proto::StreamTextOptions options; + options.set_topic(topic_); + for (const auto& kv : attributes_) { + (*options.mutable_attributes())[kv.first] = kv.second; + } + for (const auto& identity : destination_identities_) { + options.add_destination_identities(identity); + } + options.set_id(stream_id_); + if (!reply_to_id_.empty()) { + options.set_reply_to_stream_id(reply_to_id_); + } + for (const auto& id : self->attached_stream_ids_) { + options.add_attached_stream_ids(id); + } + options.set_sender_identity(sender_identity_); + + const auto owned = FfiClient::instance().textStreamOpenAsync(participant_handle, options).get(); + handle = owned.handle().id(); + TextStreamInfo info = fromProto(owned.info()); + info.size = total_size_; // Text streams can't transmit a size; keep the local one. + self->info_ = std::move(info); + applyOpenedInfo(self->info_.timestamp, self->info_.mime_type); + } else if (kind_ == StreamKind::kByte) { + auto* self = static_cast(this); + proto::StreamByteOptions options; + options.set_topic(topic_); + for (const auto& kv : attributes_) { + (*options.mutable_attributes())[kv.first] = kv.second; + } + for (const auto& identity : destination_identities_) { + options.add_destination_identities(identity); + } + options.set_id(stream_id_); + if (!byte_name_.empty()) { + options.set_name(byte_name_); + } + if (!mime_type_.empty()) { + options.set_mime_type(mime_type_); + } + if (total_size_) { + options.set_total_length(static_cast(*total_size_)); + } + options.set_sender_identity(sender_identity_); + + const auto owned = FfiClient::instance().byteStreamOpenAsync(participant_handle, options).get(); + handle = owned.handle().id(); + self->info_ = fromProto(owned.info()); + applyOpenedInfo(self->info_.timestamp, self->info_.mime_type); + } else { + throw DataStreamError("stream writer: unknown stream kind"); + } - FfiClient::instance() - .sendStreamChunkAsync(local_participant_.ffiHandleId(), chunk, destination_identities_, sender_identity_) - .get(); + bool gone = false; + { + const std::scoped_lock lock(state_mutex_); + gone = participant_gone_; + if (!gone) { + writer_handle_ = handle; + } + } + if (gone) { + // The room disconnected while the open was in flight. + (void)dropFfiHandle(handle); + throwNotConnected(); + } } -void BaseStreamWriter::sendTrailer(const std::string& reason, const std::map& attributes) { - ensureHeaderSent(); +void BaseStreamWriter::open() { + const std::scoped_lock op(op_mutex_); + openLocked(); +} - proto::DataStream::Trailer trailer; - trailer.set_stream_id(stream_id_); - trailer.set_reason(reason); +void BaseStreamWriter::writePayload(const char* data, std::size_t size, const char* closed_message) { + const std::scoped_lock op(op_mutex_); + if (closed_) { + const std::scoped_lock lock(state_mutex_); + if (participant_gone_) { + throwNotConnected(); + } + throw DataStreamError(closed_message); + } + if (size == 0) { + return; + } + openLocked(); - for (const auto& kv : attributes) { - (*trailer.mutable_attributes())[kv.first] = kv.second; + std::uint64_t handle = 0; + { + const std::scoped_lock lock(state_mutex_); + if (participant_gone_) { + throwNotConnected(); + } + handle = writer_handle_; } + // Wait for each write before the next one: the SDK core runs every write + // request as its own task, so unawaited writes could reorder or land after + // the trailer. + if (kind_ == StreamKind::kText) { + FfiClient::instance().textStreamWriteAsync(handle, std::string(data, size)).get(); + } else { + FfiClient::instance().byteStreamWriteAsync(handle, reinterpret_cast(data), size).get(); + } +} - FfiClient::instance().sendStreamTrailerAsync(local_participant_.ffiHandleId(), trailer, sender_identity_).get(); +void BaseStreamWriter::closeLocked(const std::string& reason, const std::map& attributes) { + openLocked(); + // close consumes the handle; it must not be dropped afterwards. + const std::uint64_t handle = takeHandle(); + if (handle == 0) { + throwNotConnected(); + } + const std::optional close_reason = reason.empty() ? std::nullopt : std::optional(reason); + if (kind_ == StreamKind::kText) { + FfiClient::instance().textStreamCloseAsync(handle, close_reason, attributes).get(); + } else { + FfiClient::instance().byteStreamCloseAsync(handle, close_reason, attributes).get(); + } } void BaseStreamWriter::close(const std::string& reason, const std::map& attributes) { - if (closed_) { - throw std::runtime_error("Stream already closed"); + // Taking op_mutex_ orders the close after any in-flight write. + const std::scoped_lock op(op_mutex_); + { + const std::scoped_lock lock(state_mutex_); + if (participant_gone_) { + throwNotConnected(); + } } + if (closed_.exchange(true)) { + throw DataStreamError("Stream already closed"); + } + closeLocked(reason, attributes); +} + +void BaseStreamWriter::ensureHeaderSent() { open(); } + +void BaseStreamWriter::sendChunk(const std::vector& content) { + writePayload(reinterpret_cast(content.data()), content.size(), + "Cannot send chunk after stream is closed"); +} + +void BaseStreamWriter::sendTrailer(const std::string& reason, const std::map& attributes) { + const std::scoped_lock op(op_mutex_); closed_ = true; - sendTrailer(reason, attributes); + closeLocked(reason, attributes); } TextStreamWriter::TextStreamWriter(LocalParticipant& local_participant, const std::string& topic, @@ -357,25 +521,27 @@ TextStreamWriter::TextStreamWriter(LocalParticipant& local_participant, const st /*mime_type=*/"text/plain", destination_identities, sender_identity) { kind_ = StreamKind::kText; reply_to_id_ = reply_to_id; - // ✅ Canonical user-facing metadata comes from BaseStreamWriter fields. fillBaseInfo(info_, stream_id_, mime_type_, topic_, timestamp_ms_, total_size_, attributes_); if (!reply_to_id.empty()) { info_.reply_to_stream_id = reply_to_id; } } -void TextStreamWriter::write(const std::string& text) { - const std::scoped_lock lock(write_mutex_); - if (closed_) { - throw std::runtime_error("Cannot write to closed TextStreamWriter"); - } +TextStreamWriter::TextStreamWriter(FactoryTag /*tag*/, LocalParticipant& local_participant, + const StreamTextOptions& options) + : BaseStreamWriter(local_participant, options.topic, options.attributes, options.stream_id.value_or(""), + std::nullopt, /*mime_type=*/"text/plain", options.destination_identities, + options.sender_identity.value_or("")), + attached_stream_ids_(options.attached_stream_ids) { + kind_ = StreamKind::kText; + reply_to_id_ = options.reply_to_stream_id.value_or(""); + fillBaseInfo(info_, stream_id_, mime_type_, topic_, timestamp_ms_, total_size_, attributes_); + info_.reply_to_stream_id = options.reply_to_stream_id; + info_.attachments = attached_stream_ids_; +} - for (const auto& chunk_str : splitUtf8(text, kStreamChunkSize)) { - const auto* p = reinterpret_cast(chunk_str.data()); - const std::vector bytes(p, p + chunk_str.size()); - LK_LOG_DEBUG("sending chunk"); - sendChunk(bytes); - } +void TextStreamWriter::write(const std::string& text) { + writePayload(text.data(), text.size(), "Cannot write to closed TextStreamWriter"); } ByteStreamWriter::ByteStreamWriter(LocalParticipant& local_participant, const std::string& name, @@ -391,20 +557,22 @@ ByteStreamWriter::ByteStreamWriter(LocalParticipant& local_participant, const st info_.name = name; } -void ByteStreamWriter::write(const std::vector& data) { - const std::scoped_lock lock(write_mutex_); - if (closed_) { - throw std::runtime_error("Cannot write to closed ByteStreamWriter"); - } +ByteStreamWriter::ByteStreamWriter(FactoryTag /*tag*/, LocalParticipant& local_participant, + const StreamByteOptions& options) + : BaseStreamWriter(local_participant, options.topic, options.attributes, options.stream_id.value_or(""), + options.total_length + ? std::optional(static_cast(*options.total_length)) + : std::nullopt, + options.mime_type.value_or("application/octet-stream"), options.destination_identities, + options.sender_identity.value_or("")) { + kind_ = StreamKind::kByte; + byte_name_ = options.name.value_or(""); + fillBaseInfo(info_, stream_id_, mime_type_, topic_, timestamp_ms_, total_size_, attributes_); + info_.name = byte_name_; +} - std::size_t offset = 0; - while (offset < data.size()) { - const std::size_t n = std::min(kStreamChunkSize, data.size() - offset); - auto it = data.begin() + static_cast(offset); - const std::vector chunk(it, it + static_cast(n)); - sendChunk(chunk); - offset += n; - } +void ByteStreamWriter::write(const std::vector& data) { + writePayload(reinterpret_cast(data.data()), data.size(), "Cannot write to closed ByteStreamWriter"); } } // namespace livekit diff --git a/src/data_stream_writer_registry.h b/src/data_stream_writer_registry.h new file mode 100644 index 00000000..584c5d94 --- /dev/null +++ b/src/data_stream_writer_registry.h @@ -0,0 +1,62 @@ +/* + * 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. + */ + +#pragma once + +#include +#include +#include + +namespace livekit { + +class BaseStreamWriter; + +namespace detail { + +/// @brief Tracks a LocalParticipant's stream writers so they can be closed when +/// the participant disconnects or is destroyed. +/// +/// Shared between the participant and its writers, so a writer that outlives +/// its participant never touches the participant itself. +class StreamWriterRegistry { +public: + /// @param participant_handle FFI handle id of the local participant. + explicit StreamWriterRegistry(std::uint64_t participant_handle) : participant_handle_(participant_handle) {} + + /// @brief Register a writer. + /// @return False if the participant is already disconnected. + bool add(BaseStreamWriter* writer); + + /// @brief Unregister a writer. Blocks while closeAll() is running. + void remove(BaseStreamWriter* writer); + + /// @brief Participant handle for a writer FFI request. + /// @throws DataStreamError if the participant is disconnected. + std::uint64_t participantHandle() const; + + /// @brief Mark the participant disconnected and close every registered + /// writer. Idempotent. + void closeAll() noexcept; + +private: + mutable std::mutex mutex_; + std::uint64_t participant_handle_; + bool closed_ = false; + std::unordered_set writers_; +}; + +} // namespace detail +} // namespace livekit diff --git a/src/ffi_client.cpp b/src/ffi_client.cpp index ccb70300..5599ac94 100644 --- a/src/ffi_client.cpp +++ b/src/ffi_client.cpp @@ -1265,43 +1265,115 @@ void FfiClient::byteStreamReadIncremental(std::uint64_t reader_handle) { } } -std::future FfiClient::sendStreamHeaderAsync(std::uint64_t local_participant_handle, - const proto::DataStream::Header& header, - const std::vector& destination_identities, - const std::string& sender_identity) { - // Generate client-side async_id first +std::future FfiClient::textStreamOpenAsync(std::uint64_t local_participant_handle, + const proto::StreamTextOptions& options) { + const AsyncId async_id = generateAsyncId(); + + auto fut = registerAsync( + async_id, + [async_id](const proto::FfiEvent& e) { + return e.has_text_stream_open() && e.text_stream_open().async_id() == async_id; + }, + [](const proto::FfiEvent& e, std::promise& pr) { + const auto& cb = e.text_stream_open(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); + return; + } + if (!cb.has_writer()) { + pr.set_exception(std::make_exception_ptr(DataStreamError("text_stream_open callback missing writer"))); + return; + } + pr.set_value(cb.writer()); + }); + + proto::FfiRequest req; + auto* msg = req.mutable_text_stream_open(); + msg->set_local_participant_handle(local_participant_handle); + *msg->mutable_options() = options; + msg->set_request_async_id(async_id); + + try { + const proto::FfiResponse resp = sendRequest(req); + if (!resp.has_text_stream_open()) { + logAndThrow("FfiResponse missing text_stream_open"); + } + } catch (...) { + cancelPendingByAsyncId(async_id); + throw; + } + + return fut; +} + +std::future FfiClient::byteStreamOpenAsync(std::uint64_t local_participant_handle, + const proto::StreamByteOptions& options) { + const AsyncId async_id = generateAsyncId(); + + auto fut = registerAsync( + async_id, + [async_id](const proto::FfiEvent& e) { + return e.has_byte_stream_open() && e.byte_stream_open().async_id() == async_id; + }, + [](const proto::FfiEvent& e, std::promise& pr) { + const auto& cb = e.byte_stream_open(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); + return; + } + if (!cb.has_writer()) { + pr.set_exception(std::make_exception_ptr(DataStreamError("byte_stream_open callback missing writer"))); + return; + } + pr.set_value(cb.writer()); + }); + + proto::FfiRequest req; + auto* msg = req.mutable_byte_stream_open(); + msg->set_local_participant_handle(local_participant_handle); + *msg->mutable_options() = options; + msg->set_request_async_id(async_id); + + try { + const proto::FfiResponse resp = sendRequest(req); + if (!resp.has_byte_stream_open()) { + logAndThrow("FfiResponse missing byte_stream_open"); + } + } catch (...) { + cancelPendingByAsyncId(async_id); + throw; + } + + return fut; +} + +std::future FfiClient::textStreamWriteAsync(std::uint64_t writer_handle, const std::string& text) { const AsyncId async_id = generateAsyncId(); - // Register the async handler BEFORE sending the request auto fut = registerAsync( async_id, [async_id](const proto::FfiEvent& e) { - return e.has_send_stream_header() && e.send_stream_header().async_id() == async_id; + return e.has_text_stream_writer_write() && e.text_stream_writer_write().async_id() == async_id; }, [](const proto::FfiEvent& e, std::promise& pr) { - const auto& cb = e.send_stream_header(); - if (!cb.error().empty()) { - pr.set_exception(std::make_exception_ptr(std::runtime_error(cb.error()))); + const auto& cb = e.text_stream_writer_write(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); return; } pr.set_value(); }); - // Build and send the request proto::FfiRequest req; - auto* msg = req.mutable_send_stream_header(); - msg->set_local_participant_handle(local_participant_handle); - *msg->mutable_header() = header; - msg->set_sender_identity(sender_identity); + auto* msg = req.mutable_text_stream_write(); + msg->set_writer_handle(writer_handle); + msg->set_text(text); msg->set_request_async_id(async_id); - for (const auto& id : destination_identities) { - msg->add_destination_identities(id); - } try { const proto::FfiResponse resp = sendRequest(req); - if (!resp.has_send_stream_header()) { - logAndThrow("FfiResponse missing send_stream_header"); + if (!resp.has_text_stream_write()) { + logAndThrow("FfiResponse missing text_stream_write"); } } catch (...) { cancelPendingByAsyncId(async_id); @@ -1311,43 +1383,76 @@ std::future FfiClient::sendStreamHeaderAsync(std::uint64_t local_participa return fut; } -std::future FfiClient::sendStreamChunkAsync(std::uint64_t local_participant_handle, - const proto::DataStream::Chunk& chunk, - const std::vector& destination_identities, - const std::string& sender_identity) { - // Generate client-side async_id first +std::future FfiClient::byteStreamWriteAsync(std::uint64_t writer_handle, const std::uint8_t* data, + std::size_t size) { const AsyncId async_id = generateAsyncId(); - // Register the async handler BEFORE sending the request auto fut = registerAsync( async_id, [async_id](const proto::FfiEvent& e) { - return e.has_send_stream_chunk() && e.send_stream_chunk().async_id() == async_id; + return e.has_byte_stream_writer_write() && e.byte_stream_writer_write().async_id() == async_id; }, [](const proto::FfiEvent& e, std::promise& pr) { - const auto& cb = e.send_stream_chunk(); - if (!cb.error().empty()) { - pr.set_exception(std::make_exception_ptr(std::runtime_error(cb.error()))); + const auto& cb = e.byte_stream_writer_write(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); return; } pr.set_value(); }); - // Build and send the request proto::FfiRequest req; - auto* msg = req.mutable_send_stream_chunk(); - msg->set_local_participant_handle(local_participant_handle); - *msg->mutable_chunk() = chunk; - msg->set_sender_identity(sender_identity); + auto* msg = req.mutable_byte_stream_write(); + msg->set_writer_handle(writer_handle); + msg->set_bytes(data, size); msg->set_request_async_id(async_id); - for (const auto& id : destination_identities) { - msg->add_destination_identities(id); + + try { + const proto::FfiResponse resp = sendRequest(req); + if (!resp.has_byte_stream_write()) { + logAndThrow("FfiResponse missing byte_stream_write"); + } + } catch (...) { + cancelPendingByAsyncId(async_id); + throw; + } + + return fut; +} + +std::future FfiClient::textStreamCloseAsync(std::uint64_t writer_handle, const std::optional& reason, + const std::map& attributes) { + const AsyncId async_id = generateAsyncId(); + + auto fut = registerAsync( + async_id, + [async_id](const proto::FfiEvent& e) { + return e.has_text_stream_writer_close() && e.text_stream_writer_close().async_id() == async_id; + }, + [](const proto::FfiEvent& e, std::promise& pr) { + const auto& cb = e.text_stream_writer_close(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); + return; + } + pr.set_value(); + }); + + proto::FfiRequest req; + auto* msg = req.mutable_text_stream_close(); + msg->set_writer_handle(writer_handle); + if (reason) { + msg->set_reason(*reason); + } + for (const auto& kv : attributes) { + (*msg->mutable_attributes())[kv.first] = kv.second; } + msg->set_request_async_id(async_id); try { const proto::FfiResponse resp = sendRequest(req); - if (!resp.has_send_stream_chunk()) { - logAndThrow("FfiResponse missing send_stream_chunk"); + if (!resp.has_text_stream_close()) { + logAndThrow("FfiResponse missing text_stream_close"); } } catch (...) { cancelPendingByAsyncId(async_id); @@ -1357,39 +1462,39 @@ std::future FfiClient::sendStreamChunkAsync(std::uint64_t local_participan return fut; } -std::future FfiClient::sendStreamTrailerAsync(std::uint64_t local_participant_handle, - const proto::DataStream::Trailer& trailer, - const std::string& sender_identity) { - // Generate client-side async_id first +std::future FfiClient::byteStreamCloseAsync(std::uint64_t writer_handle, const std::optional& reason, + const std::map& attributes) { const AsyncId async_id = generateAsyncId(); - // Register the async handler BEFORE sending the request auto fut = registerAsync( async_id, [async_id](const proto::FfiEvent& e) { - return e.has_send_stream_trailer() && e.send_stream_trailer().async_id() == async_id; + return e.has_byte_stream_writer_close() && e.byte_stream_writer_close().async_id() == async_id; }, [](const proto::FfiEvent& e, std::promise& pr) { - const auto& cb = e.send_stream_trailer(); - if (!cb.error().empty()) { - pr.set_exception(std::make_exception_ptr(std::runtime_error(cb.error()))); + const auto& cb = e.byte_stream_writer_close(); + if (cb.has_error()) { + pr.set_exception(std::make_exception_ptr(DataStreamError(cb.error().description()))); return; } pr.set_value(); }); - // Build and send the request proto::FfiRequest req; - auto* msg = req.mutable_send_stream_trailer(); - msg->set_local_participant_handle(local_participant_handle); - *msg->mutable_trailer() = trailer; - msg->set_sender_identity(sender_identity); + auto* msg = req.mutable_byte_stream_close(); + msg->set_writer_handle(writer_handle); + if (reason) { + msg->set_reason(*reason); + } + for (const auto& kv : attributes) { + (*msg->mutable_attributes())[kv.first] = kv.second; + } msg->set_request_async_id(async_id); try { const proto::FfiResponse resp = sendRequest(req); - if (!resp.has_send_stream_trailer()) { - logAndThrow("FfiResponse missing send_stream_trailer"); + if (!resp.has_byte_stream_close()) { + logAndThrow("FfiResponse missing byte_stream_close"); } } catch (...) { cancelPendingByAsyncId(async_id); diff --git a/src/ffi_client.h b/src/ffi_client.h index 1359f891..0be0eb58 100644 --- a/src/ffi_client.h +++ b/src/ffi_client.h @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -57,7 +58,6 @@ class FfiRequest; class OwnedTrackPublication; class OwnedLocalDataTrack; class OwnedDataTrackStream; -class DataStream; } // namespace proto @@ -176,17 +176,18 @@ class LIVEKIT_INTERNAL_API FfiClient { void textStreamReadIncremental(std::uint64_t reader_handle); void byteStreamReadIncremental(std::uint64_t reader_handle); - // Low-level data stream functionalities (legacy v1 framing) - std::future sendStreamHeaderAsync(std::uint64_t local_participant_handle, - const proto::DataStream::Header& header, - const std::vector& destination_identities, - const std::string& sender_identity); - std::future sendStreamChunkAsync(std::uint64_t local_participant_handle, const proto::DataStream::Chunk& chunk, - const std::vector& destination_identities, - const std::string& sender_identity); - std::future sendStreamTrailerAsync(std::uint64_t local_participant_handle, - const proto::DataStream::Trailer& trailer, - const std::string& sender_identity); + // Incremental writers. Open creates an owned writer handle; write borrows + // it; close consumes it (never drop the handle after calling close). + std::future textStreamOpenAsync(std::uint64_t local_participant_handle, + const proto::StreamTextOptions& options); + std::future byteStreamOpenAsync(std::uint64_t local_participant_handle, + const proto::StreamByteOptions& options); + std::future textStreamWriteAsync(std::uint64_t writer_handle, const std::string& text); + std::future byteStreamWriteAsync(std::uint64_t writer_handle, const std::uint8_t* data, std::size_t size); + std::future textStreamCloseAsync(std::uint64_t writer_handle, const std::optional& reason, + const std::map& attributes); + std::future byteStreamCloseAsync(std::uint64_t writer_handle, const std::optional& reason, + const std::map& attributes); // Generic function for sending a request to the Rust FFI. // Note: For asynchronous requests, use the dedicated async functions instead diff --git a/src/local_participant.cpp b/src/local_participant.cpp index e93e3fcc..f6816223 100644 --- a/src/local_participant.cpp +++ b/src/local_participant.cpp @@ -22,6 +22,7 @@ #include #include "data_stream_proto_converter.h" +#include "data_stream_writer_registry.h" #include "data_track.pb.h" #include "ffi.pb.h" #include "ffi_client.h" @@ -66,7 +67,15 @@ LocalParticipant::LocalParticipant(FfiHandle handle, std::string sid, std::strin std::string metadata, std::unordered_map attributes, ParticipantKind kind, DisconnectReason reason) : Participant(std::move(handle), std::move(sid), std::move(name), std::move(identity), std::move(metadata), - std::move(attributes), kind, reason) {} + std::move(attributes), kind, reason), + stream_writers_(std::make_shared(static_cast(ffiHandleId()))) {} + +LocalParticipant::~LocalParticipant() { stream_writers_->closeAll(); } + +void LocalParticipant::markDisconnected() noexcept { + disconnected_.store(true, std::memory_order_release); + stream_writers_->closeAll(); +} void LocalParticipant::publishData(const std::vector& payload, bool reliable, const std::vector& destination_identities, const std::string& topic) { @@ -132,6 +141,20 @@ ByteStreamInfo LocalParticipant::sendFile(const std::string& path, const StreamB return fromProto(fut.get()); } +std::unique_ptr LocalParticipant::streamText(const StreamTextOptions& options) { + (void)dataStreamHandle("streamText"); + std::unique_ptr writer(new TextStreamWriter(TextStreamWriter::FactoryTag{}, *this, options)); + writer->open(); + return writer; +} + +std::unique_ptr LocalParticipant::streamBytes(const StreamByteOptions& options) { + (void)dataStreamHandle("streamBytes"); + std::unique_ptr writer(new ByteStreamWriter(ByteStreamWriter::FactoryTag{}, *this, options)); + writer->open(); + return writer; +} + void LocalParticipant::publishDtmf(int code, const std::string& digit) { auto handle_id = ffiHandleId(); if (handle_id == 0) { diff --git a/src/room_proto_converter.cpp b/src/room_proto_converter.cpp index b72710fe..c6e753a8 100644 --- a/src/room_proto_converter.cpp +++ b/src/room_proto_converter.cpp @@ -246,78 +246,6 @@ AttributeEntry fromProto(const proto::AttributesEntry& in) { return a; } -DataStreamHeaderData fromProto(const proto::DataStream_Header& in) { - DataStreamHeaderData out; - out.stream_id = in.stream_id(); - out.timestamp = in.timestamp(); - out.mime_type = in.mime_type(); - out.topic = in.topic(); - if (in.has_total_length()) { - out.total_length = in.total_length(); - } - for (const auto& kv : in.attributes()) { - out.attributes.emplace(kv.first, kv.second); - } - - // content_header oneof - switch (in.content_header_case()) { - case proto::DataStream_Header::kTextHeader: { - out.content_type = DataStreamHeaderData::ContentType::Text; - const auto& t = in.text_header(); - out.operation_type = static_cast(t.operation_type()); - if (t.has_version()) { - out.version = t.version(); - } - if (t.has_reply_to_stream_id()) { - out.reply_to_stream_id = t.reply_to_stream_id(); - } - for (const auto& id : t.attached_stream_ids()) { - out.attached_stream_ids.push_back(id); - } - if (t.has_generated()) { - out.generated = t.generated(); - } - break; - } - case proto::DataStream_Header::kByteHeader: { - out.content_type = DataStreamHeaderData::ContentType::Byte; - const auto& b = in.byte_header(); - out.name = b.name(); - break; - } - case proto::DataStream_Header::CONTENT_HEADER_NOT_SET: - default: - out.content_type = DataStreamHeaderData::ContentType::None; - break; - } - - return out; -} - -DataStreamChunkData fromProto(const proto::DataStream_Chunk& in) { - DataStreamChunkData out; - out.stream_id = in.stream_id(); - out.chunk_index = in.chunk_index(); - out.content.assign(in.content().begin(), in.content().end()); - if (in.has_version()) { - out.version = in.version(); - } - if (in.has_iv()) { - out.iv.assign(in.iv().begin(), in.iv().end()); - } - return out; -} - -DataStreamTrailerData fromProto(const proto::DataStream_Trailer& in) { - DataStreamTrailerData out; - out.stream_id = in.stream_id(); - out.reason = in.reason(); - for (const auto& kv : in.attributes()) { - out.attributes.emplace(kv.first, kv.second); - } - return out; -} - // --------- event conversions --------- RoomSidChangedEvent fromProto(const proto::RoomSidChanged& in) { @@ -350,27 +278,6 @@ TokenRefreshedEvent fromProto(const proto::TokenRefreshed& in) { RoomEosEvent fromProto(const proto::RoomEOS& /*in*/) { return RoomEosEvent{}; } -DataStreamHeaderReceivedEvent fromProto(const proto::DataStreamHeaderReceived& in) { - DataStreamHeaderReceivedEvent ev; - ev.participant_identity = in.participant_identity(); - ev.header = fromProto(in.header()); - return ev; -} - -DataStreamChunkReceivedEvent fromProto(const proto::DataStreamChunkReceived& in) { - DataStreamChunkReceivedEvent ev; - ev.participant_identity = in.participant_identity(); - ev.chunk = fromProto(in.chunk()); - return ev; -} - -DataStreamTrailerReceivedEvent fromProto(const proto::DataStreamTrailerReceived& in) { - DataStreamTrailerReceivedEvent ev; - ev.participant_identity = in.participant_identity(); - ev.trailer = fromProto(in.trailer()); - return ev; -} - DataChannelBufferedAmountLowThresholdChangedEvent fromProto( const proto::DataChannelBufferedAmountLowThresholdChanged& in) { DataChannelBufferedAmountLowThresholdChangedEvent ev; @@ -617,56 +524,4 @@ SipDtmfReceivedEvent sipDtmfFromProto(const proto::DataPacketReceived& in, Remot return ev; } -std::map toAttrMap(const proto::DataStream::Trailer& trailer) { - std::map out; - for (const auto& kv : trailer.attributes()) { - out.emplace(kv.first, kv.second); - } - return out; -} - -TextStreamInfo makeTextInfo(const proto::DataStream::Header& header) { - TextStreamInfo info; - info.stream_id = header.stream_id(); - info.mime_type = header.mime_type(); - info.topic = header.topic(); - info.timestamp = header.timestamp(); - if (header.text_header().has_reply_to_stream_id()) { - info.reply_to_stream_id = header.text_header().reply_to_stream_id(); - } - - if (header.has_total_length()) { - info.size = static_cast(header.total_length()); - } - - for (const auto& kv : header.attributes()) { - info.attributes.emplace(kv.first, kv.second); - } - - for (const auto& id : header.text_header().attached_stream_ids()) { - info.attachments.push_back(id); - } - - return info; -} - -ByteStreamInfo makeByteInfo(const proto::DataStream::Header& header) { - ByteStreamInfo info; - info.stream_id = header.stream_id(); - info.mime_type = header.mime_type(); - info.topic = header.topic(); - info.timestamp = header.timestamp(); - - if (header.has_total_length()) { - info.size = static_cast(header.total_length()); - } - - for (const auto& kv : header.attributes()) { - info.attributes.emplace(kv.first, kv.second); - } - - info.name = header.byte_header().name(); - return info; -} - } // namespace livekit diff --git a/src/room_proto_converter.h b/src/room_proto_converter.h index b834d262..8d2c2666 100644 --- a/src/room_proto_converter.h +++ b/src/room_proto_converter.h @@ -28,9 +28,7 @@ namespace livekit { enum class RpcErrorCode; class RemoteParticipant; -struct ByteStreamInfo; struct RoomOptions; -struct TextStreamInfo; // --------- basic helper conversions --------- @@ -44,10 +42,6 @@ LIVEKIT_INTERNAL_API UserPacketData fromProto(const proto::UserPacket& in); LIVEKIT_INTERNAL_API SipDtmfData fromProto(const proto::SipDTMF& in); LIVEKIT_INTERNAL_API RoomInfoData fromProto(const proto::RoomInfo& in); -LIVEKIT_INTERNAL_API DataStreamHeaderData fromProto(const proto::DataStream_Header& in); -LIVEKIT_INTERNAL_API DataStreamChunkData fromProto(const proto::DataStream_Chunk& in); -LIVEKIT_INTERNAL_API DataStreamTrailerData fromProto(const proto::DataStream_Trailer& in); - // --------- event conversions (RoomEvent.oneof message) --------- LIVEKIT_INTERNAL_API RoomSidChangedEvent fromProto(const proto::RoomSidChanged& in); @@ -59,10 +53,6 @@ LIVEKIT_INTERNAL_API ReconnectedEvent fromProto(const proto::Reconnected& in); LIVEKIT_INTERNAL_API TokenRefreshedEvent fromProto(const proto::TokenRefreshed& in); LIVEKIT_INTERNAL_API RoomEosEvent fromProto(const proto::RoomEOS& in); -LIVEKIT_INTERNAL_API DataStreamHeaderReceivedEvent fromProto(const proto::DataStreamHeaderReceived& in); -LIVEKIT_INTERNAL_API DataStreamChunkReceivedEvent fromProto(const proto::DataStreamChunkReceived& in); -LIVEKIT_INTERNAL_API DataStreamTrailerReceivedEvent fromProto(const proto::DataStreamTrailerReceived& in); - LIVEKIT_INTERNAL_API DataChannelBufferedAmountLowThresholdChangedEvent fromProto(const proto::DataChannelBufferedAmountLowThresholdChanged& in); @@ -94,9 +84,4 @@ LIVEKIT_INTERNAL_API UserDataPacketEvent userDataPacketFromProto(const proto::Da LIVEKIT_INTERNAL_API SipDtmfReceivedEvent sipDtmfFromProto(const proto::DataPacketReceived& in, RemoteParticipant* participant); -// --------- room Data Stream conversions --------- -LIVEKIT_INTERNAL_API std::map toAttrMap(const proto::DataStream::Trailer& trailer); -LIVEKIT_INTERNAL_API ByteStreamInfo makeByteInfo(const proto::DataStream::Header& header); -LIVEKIT_INTERNAL_API TextStreamInfo makeTextInfo(const proto::DataStream::Header& header); - } // namespace livekit diff --git a/src/tests/integration/test_data_streams.cpp b/src/tests/integration/test_data_streams.cpp index 2d73e7c3..d6645a28 100644 --- a/src/tests/integration/test_data_streams.cpp +++ b/src/tests/integration/test_data_streams.cpp @@ -16,7 +16,7 @@ // End-to-end coverage for text/byte data streams (registerTextStreamHandler / // registerByteStreamHandler + LocalParticipant::sendText / sendBytes / sendFile -// and TextStreamWriter / ByteStreamWriter). Requires a local SFU; see +// and streamText / streamBytes). Requires a local SFU; see // test_data_track.cpp for setup instructions. Run with: // ./build-debug/bin/livekit_integration_tests --gtest_filter=*DataStream* @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -208,6 +209,17 @@ std::string unicodeText(std::size_t size) { return out; } +/// Incompressible bytes. +std::vector randomBytes(std::size_t size) { + std::mt19937 rng(1234); + std::uniform_int_distribution dist(0, 255); + std::vector out(size); + for (auto& b : out) { + b = static_cast(dist(rng)); + } + return out; +} + /// Records the reader handle of every opened data stream, to probe whether the /// SDK released them. class OpenedStreamHandleRecorder { @@ -268,10 +280,12 @@ TEST_F(DataStreamE2ETest, TextStreamRoundTripEndToEnd) { TextStreamCollector collector; collector.registerOn(*receiver_room, topic); - TextStreamWriter writer(*sender, topic); - writer.write("hello, "); - writer.write("world!"); - writer.close(); + StreamTextOptions options; + options.topic = topic; + auto writer = sender->streamText(options); + writer->write("hello, "); + writer->write("world!"); + writer->close(); ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; EXPECT_EQ(collector.text(), "hello, world!"); @@ -283,8 +297,8 @@ TEST_F(DataStreamE2ETest, TextStreamRoundTripEndToEnd) { // Regression coverage for the `text_header.reply_to_stream_id` field: writing // a text stream with a reply-to id set should surface that id on the // receiving side's TextStreamInfo. If this fails while the C++-side -// conversion (room_proto_converter.cpp: makeTextInfo) looks correct, the gap -// is upstream in the Rust FFI layer not forwarding the field. +// conversion (data_stream_proto_converter.cpp) looks correct, the gap is +// upstream in the Rust FFI layer not forwarding the field. TEST_F(DataStreamE2ETest, TextStreamReplyToStreamIdIsRoutedEndToEnd) { const auto topic = makeTopic("text_reply"); const std::string reply_to_id = "original-stream-" + std::to_string(getTimestampUs()); @@ -296,10 +310,12 @@ TEST_F(DataStreamE2ETest, TextStreamReplyToStreamIdIsRoutedEndToEnd) { TextStreamCollector collector; collector.registerOn(*receiver_room, topic); - TextStreamWriter writer(*lockLocalParticipant(*sender_room), topic, /*attributes=*/{}, /*stream_id=*/"", - /*total_size=*/std::nullopt, reply_to_id); - writer.write("reply payload"); - writer.close(); + StreamTextOptions options; + options.topic = topic; + options.reply_to_stream_id = reply_to_id; + auto writer = lockLocalParticipant(*sender_room)->streamText(options); + writer->write("reply payload"); + writer->close(); ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; EXPECT_EQ(collector.text(), "reply payload"); @@ -320,9 +336,12 @@ TEST_F(DataStreamE2ETest, ByteStreamRoundTripEndToEnd) { ByteStreamCollector collector; collector.registerOn(*receiver_room, topic); - ByteStreamWriter writer(*lockLocalParticipant(*sender_room), /*name=*/"payload.bin", topic); - writer.write(payload); - writer.close(); + StreamByteOptions options; + options.topic = topic; + options.name = "payload.bin"; + auto writer = lockLocalParticipant(*sender_room)->streamBytes(options); + writer->write(payload); + writer->close(); ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for byte stream"; EXPECT_EQ(collector.content(), payload); @@ -515,9 +534,12 @@ TEST_F(DataStreamE2ETest, TrailerAttributesAreMergedIntoInfo) { TextStreamCollector collector; collector.registerOn(*rooms[1], topic); - TextStreamWriter writer(*lockLocalParticipant(*rooms[0]), topic, {{"header_key", "h"}}); - writer.write("body"); - writer.close("", {{"trailer_key", "t"}}); + StreamTextOptions options; + options.topic = topic; + options.attributes = {{"header_key", "h"}}; + auto writer = lockLocalParticipant(*rooms[0])->streamText(options); + writer->write("body"); + writer->close("", {{"trailer_key", "t"}}); ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; EXPECT_FALSE(collector.error().has_value()) << *collector.error(); @@ -533,9 +555,12 @@ TEST_F(DataStreamE2ETest, AbnormalCloseSurfacesError) { ByteStreamCollector collector; collector.registerOn(*rooms[1], topic); - ByteStreamWriter writer(*lockLocalParticipant(*rooms[0]), "partial.bin", topic); - writer.write({1, 2, 3}); - writer.close("boom"); + StreamByteOptions options; + options.topic = topic; + options.name = "partial.bin"; + auto writer = lockLocalParticipant(*rooms[0])->streamBytes(options); + writer->write({1, 2, 3}); + writer->close("boom"); ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for byte stream"; ASSERT_TRUE(collector.error().has_value()) << "a close with a reason must surface an error"; @@ -550,15 +575,17 @@ TEST_F(DataStreamE2ETest, ReceiverDisconnectMidStreamWakesReader) { TextStreamCollector collector; collector.registerOn(*rooms[1], topic); - TextStreamWriter writer(*lockLocalParticipant(*rooms[0]), topic); - writer.write("first part"); + StreamTextOptions options; + options.topic = topic; + auto writer = lockLocalParticipant(*rooms[0])->streamText(options); + writer->write("first part"); // Give the receiver time to open the reader and block on the next chunk. std::this_thread::sleep_for(1s); ASSERT_TRUE(rooms[1]->disconnect()); ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "A blocked reader must wake when its room disconnects"; EXPECT_TRUE(collector.error().has_value()) << "an interrupted stream must surface an error"; - writer.close(); + writer->close(); } TEST_F(DataStreamE2ETest, ReaderCloseWakesPendingRead) { @@ -574,8 +601,10 @@ TEST_F(DataStreamE2ETest, ReaderCloseWakesPendingRead) { cv.notify_all(); }); - TextStreamWriter writer(*lockLocalParticipant(*rooms[0]), topic); - writer.write("first"); + StreamTextOptions options; + options.topic = topic; + auto writer = lockLocalParticipant(*rooms[0])->streamText(options); + writer->write("first"); { std::unique_lock lock(mutex); ASSERT_TRUE(cv.wait_for(lock, kStreamWaitTimeout, [&] { return reader != nullptr; })); @@ -597,7 +626,7 @@ TEST_F(DataStreamE2ETest, ReaderCloseWakesPendingRead) { read_thread.join(); EXPECT_TRUE(finished); EXPECT_EQ(chunks.load(), 1); - writer.close(); + writer->close(); } TEST_F(DataStreamE2ETest, StreamHandlesAreReleased) { @@ -635,4 +664,201 @@ TEST_F(DataStreamE2ETest, StreamHandlesAreReleased) { } } +// --------------------------------------------------------------------------- +// Incremental writers (LocalParticipant::streamText / streamBytes) +// --------------------------------------------------------------------------- + +TEST_F(DataStreamE2ETest, StreamTextIncrementalUnicode) { + const auto topic = makeTopic("stream_text_unicode"); + auto rooms = testRooms(2); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamTextOptions options; + options.topic = topic; + auto writer = lockLocalParticipant(*rooms[0])->streamText(options); + EXPECT_EQ(writer->info().mime_type, "text/plain"); + std::string expected; + for (int i = 0; i < 4; ++i) { + // Each write is bigger than one 15 KB chunk. + const auto part = unicodeText(20 * 1024); + writer->write(part); + expected += part; + } + writer->close(); + EXPECT_TRUE(writer->isClosed()); + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "Timed out waiting for text stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.text(), expected); + EXPECT_EQ(collector.info().stream_id, writer->streamId()); +} + +TEST_F(DataStreamE2ETest, StreamBytesLargePayloads) { + auto rooms = testRooms(2); + auto sender = lockLocalParticipant(*rooms[0]); + + for (const bool incompressible : {false, true}) { + const auto topic = makeTopic(incompressible ? "stream_bytes_random" : "stream_bytes_pattern"); + std::vector payload; + if (incompressible) { + payload = randomBytes(1024 * 1024); + } else { + payload.resize(1024 * 1024); + for (std::size_t i = 0; i < payload.size(); ++i) { + payload[i] = static_cast(i % 251); + } + } + + ByteStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamByteOptions options; + options.topic = topic; + options.name = "big.bin"; + options.total_length = payload.size(); + auto writer = sender->streamBytes(options); + const std::size_t half = payload.size() / 2; + writer->write(std::vector(payload.begin(), payload.begin() + static_cast(half))); + writer->write(std::vector(payload.begin() + static_cast(half), payload.end())); + writer->close(); + + ASSERT_TRUE(collector.wait(std::chrono::seconds(30))) << "Timed out waiting for byte stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.content().size(), payload.size()); + EXPECT_TRUE(collector.content() == payload) << "payload mismatch (incompressible=" << incompressible << ")"; + ASSERT_TRUE(collector.info().size.has_value()); + EXPECT_EQ(*collector.info().size, payload.size()); + rooms[1]->unregisterByteStreamHandler(topic); + } +} + +TEST_F(DataStreamE2ETest, CloseWaitsForInFlightWrite) { + const auto topic = makeTopic("close_waits"); + const auto payload = randomBytes(2 * 1024 * 1024); + auto rooms = testRooms(2); + + ByteStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamByteOptions options; + options.topic = topic; + auto writer = lockLocalParticipant(*rooms[0])->streamBytes(options); + + std::atomic write_started{false}; + std::thread write_thread([&] { + write_started = true; + writer->write(payload); + }); + while (!write_started) { + std::this_thread::yield(); + } + std::this_thread::sleep_for(5ms); + writer->close(); // Must not overtake the write. + write_thread.join(); + + ASSERT_TRUE(collector.wait(std::chrono::seconds(30))) << "Timed out waiting for byte stream"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_TRUE(collector.content() == payload) + << "received " << collector.content().size() << " of " << payload.size() << " bytes"; +} + +TEST_F(DataStreamE2ETest, WriteAfterCloseThrows) { + auto rooms = testRooms(2); + StreamTextOptions options; + options.topic = makeTopic("write_after_close"); + auto writer = lockLocalParticipant(*rooms[0])->streamText(options); + writer->write("once"); + writer->close(); + EXPECT_THROW(writer->write("twice"), DataStreamError); + EXPECT_THROW(writer->close(), DataStreamError) << "double close throws"; +} + +TEST_F(DataStreamE2ETest, WriteAfterDisconnectThrows) { + const auto topic = makeTopic("write_after_disconnect"); + auto rooms = testRooms(2); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + StreamTextOptions options; + options.topic = topic; + auto writer = lockLocalParticipant(*rooms[0])->streamText(options); + writer->write("before"); + ASSERT_TRUE(rooms[0]->disconnect()); + + EXPECT_TRUE(writer->isClosed()); + EXPECT_THROW(writer->write("after"), DataStreamError); + EXPECT_THROW(writer->close(), DataStreamError); + + // The receiver learns the sender left mid-stream. + ASSERT_TRUE(collector.wait(std::chrono::seconds(30))) << "receiver should not hang after the sender disconnects"; + EXPECT_TRUE(collector.error().has_value()); +} + +TEST_F(DataStreamE2ETest, WriterDestroyedWithoutCloseEndsStream) { + const auto topic = makeTopic("writer_destroyed"); + auto rooms = testRooms(2); + + TextStreamCollector collector; + collector.registerOn(*rooms[1], topic); + + { + StreamTextOptions options; + options.topic = topic; + auto writer = lockLocalParticipant(*rooms[0])->streamText(options); + writer->write("unfinished"); + } // Destroyed without close(). + + ASSERT_TRUE(collector.wait(kStreamWaitTimeout)) << "receiver must not wait forever for a dropped writer"; + EXPECT_FALSE(collector.error().has_value()) << *collector.error(); + EXPECT_EQ(collector.text(), "unfinished"); +} + +// The writer constructors are deprecated in favour of streamText / +// streamBytes, but must keep working. +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif +TEST_F(DataStreamE2ETest, DeprecatedWriterConstructorsStillWork) { + const auto text_topic = makeTopic("deprecated_text"); + const auto byte_topic = makeTopic("deprecated_bytes"); + auto rooms = testRooms(2); + auto sender = lockLocalParticipant(*rooms[0]); + + TextStreamCollector text_collector; + text_collector.registerOn(*rooms[1], text_topic); + ByteStreamCollector byte_collector; + byte_collector.registerOn(*rooms[1], byte_topic); + + TextStreamWriter text_writer(*sender, text_topic, {{"k", "v"}}); + const std::string stream_id = text_writer.streamId(); + EXPECT_FALSE(stream_id.empty()) << "the id is known before the stream opens"; + text_writer.write("legacy "); + text_writer.write("text"); + text_writer.close(); + + ByteStreamWriter byte_writer(*sender, "legacy.bin", byte_topic); + byte_writer.write({9, 8, 7}); + byte_writer.close(); + + ASSERT_TRUE(text_collector.wait(kStreamWaitTimeout)); + EXPECT_EQ(text_collector.text(), "legacy text"); + EXPECT_EQ(text_collector.info().stream_id, stream_id); + EXPECT_EQ(text_collector.info().attributes.at("k"), "v"); + ASSERT_TRUE(byte_collector.wait(kStreamWaitTimeout)); + EXPECT_EQ(byte_collector.content(), (std::vector{9, 8, 7})); + EXPECT_EQ(byte_collector.info().name, "legacy.bin"); +} +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif + } // namespace livekit::test diff --git a/src/tests/unit/test_data_stream.cpp b/src/tests/unit/test_data_stream.cpp index c399e422..73669aac 100644 --- a/src/tests/unit/test_data_stream.cpp +++ b/src/tests/unit/test_data_stream.cpp @@ -96,7 +96,20 @@ TEST(DataStreamTest, ByteStreamReaderConstructAndInfo) { TEST(DataStreamTest, WriterTypesAreDerivedFromBase) { static_assert(std::is_base_of_v); static_assert(std::is_base_of_v); + // Deprecated, but must keep compiling for existing callers. +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif EXPECT_GT(kStreamChunkSize, 0u); +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif } // --------------------------------------------------------------------------- @@ -363,4 +376,83 @@ TEST(DataStreamSendTest, FfiHelpersThrowWhenNotInitialized) { EXPECT_THROW(FfiClient::instance().byteStreamReadIncremental(1), std::runtime_error); } +// --------------------------------------------------------------------------- +// Writers without a live room +// --------------------------------------------------------------------------- + +namespace { + +std::shared_ptr detachedParticipant() { + return std::make_shared(FfiHandle(0), "sid", "name", "identity", "", + std::unordered_map{}, ParticipantKind::Standard, + DisconnectReason::Unknown); +} + +} // namespace + +TEST(DataStreamWriterTest, FactoriesThrowWhenNotInitialized) { + ASSERT_FALSE(FfiClient::instance().isInitialized()); + auto participant = detachedParticipant(); + StreamTextOptions text_options; + text_options.topic = "t"; + StreamByteOptions byte_options; + byte_options.topic = "t"; + EXPECT_THROW((void)participant->streamText(text_options), DataStreamError); + EXPECT_THROW((void)participant->streamBytes(byte_options), DataStreamError); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#elif defined(_MSC_VER) +#pragma warning(push) +#pragma warning(disable : 4996) +#endif + +TEST(DataStreamWriterTest, DeprecatedConstructorsKeepMetadata) { + auto participant = detachedParticipant(); + TextStreamWriter text(*participant, "chat", {{"k", "v"}}, "my-id", 42, "reply-id"); + EXPECT_EQ(text.streamId(), "my-id"); + EXPECT_EQ(text.topic(), "chat"); + EXPECT_EQ(text.mimeType(), "text/plain"); + EXPECT_FALSE(text.isClosed()); + EXPECT_EQ(text.info().attributes.at("k"), "v"); + ASSERT_TRUE(text.info().size.has_value()); + EXPECT_EQ(*text.info().size, 42u); + EXPECT_EQ(text.info().reply_to_stream_id.value_or(""), "reply-id"); + + ByteStreamWriter bytes(*participant, "file.bin", "files"); + EXPECT_EQ(bytes.streamId().size(), 32u) << "a stream id is generated when none is given"; + EXPECT_EQ(bytes.mimeType(), "application/octet-stream"); + EXPECT_EQ(bytes.info().name, "file.bin"); +} + +TEST(DataStreamWriterTest, WritersCloseWhenParticipantGoes) { + auto participant = detachedParticipant(); + auto writer = std::make_unique(*participant, "chat"); + ASSERT_FALSE(writer->isClosed()); + + participant.reset(); // Closes registered writers. + EXPECT_TRUE(writer->isClosed()); + EXPECT_THROW(writer->write("late"), DataStreamError); + EXPECT_THROW(writer->close(), DataStreamError); + writer.reset(); // Must not touch the destroyed participant. +} + +TEST(DataStreamWriterTest, WriteToClosedWriterThrowsWithoutReachingFfi) { + auto participant = detachedParticipant(); + ByteStreamWriter writer(*participant, "file.bin", "files"); + // An empty write is a no-op and must not open the stream. + EXPECT_NO_THROW(writer.write({})); + // Without an initialized FFI the open fails, and the writer stays usable + // only to report errors. + EXPECT_THROW(writer.write({1, 2, 3}), std::runtime_error); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#elif defined(_MSC_VER) +#pragma warning(pop) +#endif + } // namespace livekit::test diff --git a/src/tests/unit/test_ffi_client.cpp b/src/tests/unit/test_ffi_client.cpp index 4edf3243..9b51f712 100644 --- a/src/tests/unit/test_ffi_client.cpp +++ b/src/tests/unit/test_ffi_client.cpp @@ -544,25 +544,16 @@ TEST_F(FfiClientTest, NotInitialized_SubscribeDataTrackFails) { EXPECT_EQ(result.error().code, SubscribeDataTrackErrorCode::INTERNAL); } -TEST_F(FfiClientTest, NotInitialized_SendStreamHeaderAsyncThrows) { +TEST_F(FfiClientTest, NotInitialized_StreamWriterHelpersThrow) { ASSERT_FALSE(FfiClient::instance().isInitialized()); - proto::DataStream::Header header; - EXPECT_THROW(FfiClient::instance().sendStreamHeaderAsync(1, header, {}, "sender"), std::runtime_error); -} - -TEST_F(FfiClientTest, NotInitialized_SendStreamChunkAsyncThrows) { - ASSERT_FALSE(FfiClient::instance().isInitialized()); - - proto::DataStream::Chunk chunk; - EXPECT_THROW(FfiClient::instance().sendStreamChunkAsync(1, chunk, {}, "sender"), std::runtime_error); -} - -TEST_F(FfiClientTest, NotInitialized_SendStreamTrailerAsyncThrows) { - ASSERT_FALSE(FfiClient::instance().isInitialized()); - - proto::DataStream::Trailer trailer; - EXPECT_THROW(FfiClient::instance().sendStreamTrailerAsync(1, trailer, "sender"), std::runtime_error); + const std::uint8_t byte = 0; + EXPECT_THROW(FfiClient::instance().textStreamOpenAsync(1, proto::StreamTextOptions{}), std::runtime_error); + EXPECT_THROW(FfiClient::instance().byteStreamOpenAsync(1, proto::StreamByteOptions{}), std::runtime_error); + EXPECT_THROW(FfiClient::instance().textStreamWriteAsync(1, "x"), std::runtime_error); + EXPECT_THROW(FfiClient::instance().byteStreamWriteAsync(1, &byte, 1), std::runtime_error); + EXPECT_THROW(FfiClient::instance().textStreamCloseAsync(1, std::nullopt, {}), std::runtime_error); + EXPECT_THROW(FfiClient::instance().byteStreamCloseAsync(1, std::string("reason"), {}), std::runtime_error); } } // namespace livekit::test From b7d9d6f13af085b82af2c9a5fb032648da79a5fd Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 23 Nov 2026 08:59:13 +1300 Subject: [PATCH 07/11] Add send-side data stream conformance tests Ports the outgoing-manager tests that are observable end to end: the C++ SDK sends through sendText / sendBytes / sendFile / streamText / streamBytes, and the receiving room's raw packets and reader output are checked. Covers inline vs multi-packet decisions, compression (one-shot and sendFile), compress=false, MTU splitting (including UTF-8 aware text splits), attachments, empty payloads, writer trailers (reason and attributes), header size limits, writer drop, targeting, and sender identity attribution. The raw header event does not carry inline_content or compression, so inline is observed as a header with no chunk/trailer packets and compression as chunk bytes that differ from and are smaller than the payload. The SFU attributes packets to the authenticated participant for standard tokens, so the sender_identity tests check acceptance and delivery rather than the outgoing stamp. Co-Authored-By: Claude Opus 5.5 --- .../test_data_stream_conformance_send.cpp | 825 ++++++++++++++++++ 1 file changed, 825 insertions(+) create mode 100644 src/tests/integration/test_data_stream_conformance_send.cpp diff --git a/src/tests/integration/test_data_stream_conformance_send.cpp b/src/tests/integration/test_data_stream_conformance_send.cpp new file mode 100644 index 00000000..0ae3304d --- /dev/null +++ b/src/tests/integration/test_data_stream_conformance_send.cpp @@ -0,0 +1,825 @@ +/* + * 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. + */ + +// Send-side data stream conformance: the C++ SDK sends through its public API +// (sendText / sendBytes / sendFile / streamText / streamBytes), and the +// receiving room's raw packets are checked against what the Rust +// `livekit-data-stream` crate's outgoing-manager tests require +// (client-sdk-rust/livekit-data-stream/src/outgoing/manager.rs), along with +// the content the receiver's reader delivers. +// +// All test participants are FFI clients and advertise data streams v2 with +// deflate-raw compression, so every recipient here is "v2 capable". The raw +// header event carries neither `inline_content` nor `compression`, so an +// inline stream is observed as a header with no chunk or trailer packets, and +// compression as chunk bytes that differ from (and are smaller than) the +// payload. +// +// See data_stream_conformance.md for the full Rust-test -> C++-test mapping. +// +// Run with: +// ./build-debug/bin/livekit_integration_tests --gtest_filter=DataStreamSend* + +#include + +#include +#include +#include +#include +#include +#include + +#include "../common/data_stream_test_utils.h" + +namespace livekit::test::ds { + +namespace { + +/// "hello hello compressible world": 30 bytes that deflate to 28. +const std::string kShortCompressible = "hello hello compressible world"; + +/// Waits for the header on `topic`, then checks no chunk or trailer follows. +RawHeader expectInline(const RawPacketSniffer& sniffer, const std::string& topic) { + const auto header = sniffer.waitForHeader(topic); + EXPECT_TRUE(header.has_value()) << "no raw header received"; + if (!header) { + return {}; + } + std::this_thread::sleep_for(kQuietPeriod); + EXPECT_TRUE(sniffer.chunks(header->stream_id).empty()) << "inline stream must not send chunk packets"; + EXPECT_TRUE(sniffer.trailers(header->stream_id).empty()) << "inline stream must not send a trailer packet"; + return *header; +} + +/// Waits for a complete multi-packet stream on `topic` and returns its header. +RawHeader expectMultipacket(const RawPacketSniffer& sniffer, const std::string& topic) { + const auto header = sniffer.waitForHeader(topic); + EXPECT_TRUE(header.has_value()) << "no raw header received"; + if (!header) { + return {}; + } + const auto trailer = sniffer.waitForTrailer(header->stream_id); + EXPECT_TRUE(trailer.has_value()) << "multi-packet stream must end with a trailer"; + if (trailer) { + EXPECT_EQ(trailer->reason, ""); + } + return *header; +} + +std::vector chunkSizes(const RawPacketSniffer& sniffer, const std::string& stream_id) { + std::vector sizes; + for (const auto& c : sniffer.chunks(stream_id)) { + sizes.push_back(c.content.size()); + } + return sizes; +} + +std::vector chunkIndices(const RawPacketSniffer& sniffer, const std::string& stream_id) { + std::vector indices; + for (const auto& c : sniffer.chunks(stream_id)) { + indices.push_back(c.chunk_index); + } + return indices; +} + +/// A file in a fresh temporary directory, removed on destruction. +class TempFile { +public: + TempFile(const std::string& name, const std::string& content) { + dir_ = std::filesystem::temp_directory_path() / uniqueStreamId("ds_conf_file"); + std::filesystem::create_directories(dir_); + path_ = dir_ / name; + std::ofstream out(path_, std::ios::binary); + out.write(content.data(), static_cast(content.size())); + } + ~TempFile() { + std::error_code ec; + std::filesystem::remove_all(dir_, ec); + } + TempFile(const TempFile&) = delete; + TempFile& operator=(const TempFile&) = delete; + TempFile(TempFile&&) = delete; + TempFile& operator=(TempFile&&) = delete; + + std::string path() const { return path_.string(); } + +private: + std::filesystem::path dir_; + std::filesystem::path path_; +}; + +} // namespace + +class DataStreamSendConformanceTest : public DataStreamConformanceTest { +protected: + std::shared_ptr sender() { return lockLocalParticipant(senderRoom()); } + + StreamTextOptions textOptions(const std::string& topic) { + StreamTextOptions opts; + opts.topic = topic; + return opts; + } + + StreamByteOptions byteOptions(const std::string& topic) { + StreamByteOptions opts; + opts.topic = topic; + return opts; + } +}; + +// --------------------------------------------------------------------------- +// sendText +// --------------------------------------------------------------------------- + +// Rust: v2_short_incompressible_text_inlines_raw +TEST_F(DataStreamSendConformanceTest, SendTextShortIncompressibleInlines) { + const auto topic = uniqueTopic("send_short"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + const auto info = sender()->sendText("short", textOptions(topic)); + + const auto header = expectInline(sniffer, topic); + EXPECT_EQ(header.stream_id, info.stream_id); + EXPECT_TRUE(header.is_text); + EXPECT_EQ(header.mime_type, "text/plain"); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, 5U); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, "short"); +} + +// Rust: v2_short_compressible_text_inlines_compressed, +// v2_broadcast_all_capable_inlines_compressed +TEST_F(DataStreamSendConformanceTest, SendTextShortCompressibleInlines) { + const auto topic = uniqueTopic("send_short_z"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendText(kShortCompressible, textOptions(topic)); + + const auto header = expectInline(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, kShortCompressible.size()); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, kShortCompressible); +} + +// Rust: v2_large_highly_compressible_text_still_inlines +TEST_F(DataStreamSendConformanceTest, SendTextLargeHighlyCompressibleStillInlines) { + const auto topic = uniqueTopic("send_large_z"); + std::string text; + for (int i = 0; i < 20'000; ++i) { + text += "hello world"; + } + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendText(text, textOptions(topic)); + + const auto header = expectInline(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, text.size()) << "total_length is the uncompressed length"; + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, text); +} + +// Rust: v2_somewhat_compressible_text_is_compressed_multipacket +TEST_F(DataStreamSendConformanceTest, SendTextSomewhatCompressibleIsCompressedMultipacket) { + const auto topic = uniqueTopic("send_somewhat_z"); + const auto text = randomText(50'000); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendText(text, textOptions(topic)); + + const auto header = expectMultipacket(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, text.size()); + const auto sizes = chunkSizes(sniffer, header.stream_id); + ASSERT_GE(sizes.size(), 2U); + EXPECT_LT(sizes.size(), 4U) << "compressed chunks are fewer than uncompressed ones would be"; + EXPECT_EQ(sizes.front(), kMtu); + const auto raw = sniffer.rawContent(header.stream_id); + EXPECT_LT(raw.size(), text.size()); + EXPECT_NE(raw, text.substr(0, raw.size())) << "chunks must carry compressed bytes"; + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, text); +} + +// Rust: v2_compress_false_short_inlines_raw +TEST_F(DataStreamSendConformanceTest, SendTextCompressFalseShortInlines) { + const auto topic = uniqueTopic("send_nocomp_short"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = textOptions(topic); + opts.compress = false; + (void)sender()->sendText(kShortCompressible, opts); + + (void)expectInline(sniffer, topic); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, kShortCompressible); +} + +// Rust: v2_compress_false_large_is_uncompressed_multipacket +TEST_F(DataStreamSendConformanceTest, SendTextCompressFalseLargeIsUncompressedMultipacket) { + const auto topic = uniqueTopic("send_nocomp_large"); + const std::string text(50'000, 'B'); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = textOptions(topic); + opts.compress = false; + (void)sender()->sendText(text, opts); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_EQ(chunkSizes(sniffer, header.stream_id), (std::vector{kMtu, kMtu, kMtu, 5'000})); + EXPECT_EQ(chunkIndices(sniffer, header.stream_id), (std::vector{0, 1, 2, 3})); + EXPECT_EQ(sniffer.rawContent(header.stream_id), text) << "uncompressed chunks carry the text verbatim"; + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, text); +} + +// Rust: v2_send_text_with_attachments_never_inlines +TEST_F(DataStreamSendConformanceTest, SendTextWithAttachmentsNeverInlines) { + const auto topic = uniqueTopic("send_attach"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = textOptions(topic); + opts.attached_stream_ids = {"att1"}; + (void)sender()->sendText(kShortCompressible, opts); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_EQ(header.attached_stream_ids, std::vector{"att1"}); + EXPECT_EQ(sniffer.chunks(header.stream_id).size(), 1U); + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_EQ(s.content, kShortCompressible); + EXPECT_EQ(s.info.attachments, std::vector{"att1"}); +} + +// Rust: v2_empty_text_sends_single_inline_packet +TEST_F(DataStreamSendConformanceTest, SendTextEmptyIsSingleInlinePacket) { + const auto topic = uniqueTopic("send_empty"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendText("", textOptions(topic)); + + const auto header = expectInline(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, 0U); + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, ""); +} + +// Rust: oversized_attributes_on_chunked_path_errors +TEST_F(DataStreamSendConformanceTest, SendTextOversizedAttributesThrows) { + const auto topic = uniqueTopic("send_big_attrs"); + RawPacketSniffer sniffer(receiverRoom()); + + auto opts = textOptions(topic); + opts.attributes = {{"big", std::string(20'000, 'x')}}; + try { + (void)sender()->sendText("hello", opts); + FAIL() << "a header over the packet size limit must be rejected"; + } catch (const DataStreamError& e) { + EXPECT_NE(std::string(e.what()).find("stream header exceeds maximum size"), std::string::npos) << e.what(); + } + EXPECT_FALSE(sniffer.waitForHeader(topic, kQuietPeriod).has_value()) << "nothing may be sent"; +} + +// --------------------------------------------------------------------------- +// sendBytes +// --------------------------------------------------------------------------- + +// Rust: v2_send_bytes_short_incompressible_inlines_raw +TEST_F(DataStreamSendConformanceTest, SendBytesShortIncompressibleInlines) { + const auto topic = uniqueTopic("bytes_short"); + const std::vector payload{0, 1, 2, 3}; + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendBytes(payload, byteOptions(topic)); + + const auto header = expectInline(sniffer, topic); + EXPECT_FALSE(header.is_text); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, fromBytes(payload)); +} + +// Rust: v2_send_bytes_short_compressible_inlines_compressed (incl. returned info) +TEST_F(DataStreamSendConformanceTest, SendBytesShortCompressibleInlinesAndReturnsInfo) { + const auto topic = uniqueTopic("bytes_short_z"); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = byteOptions(topic); + opts.attributes = {{"foo", "bar"}}; + const auto info = sender()->sendBytes(toBytes(kShortCompressible), opts); + + EXPECT_EQ(info.name, "unknown"); + EXPECT_EQ(info.mime_type, "application/octet-stream"); + ASSERT_TRUE(info.size.has_value()); + EXPECT_EQ(*info.size, kShortCompressible.size()); + EXPECT_EQ(info.attributes.at("foo"), "bar"); + const auto header = expectInline(sniffer, topic); + EXPECT_EQ(header.stream_id, info.stream_id); + EXPECT_EQ(header.name, "unknown"); + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_EQ(s.content, kShortCompressible); + EXPECT_EQ(s.info.name, "unknown"); + EXPECT_EQ(s.info.attributes.at("foo"), "bar"); +} + +// Rust: v2_send_bytes_large_highly_compressible_inlines +TEST_F(DataStreamSendConformanceTest, SendBytesLargeHighlyCompressibleInlines) { + const auto topic = uniqueTopic("bytes_large_z"); + const std::string payload(50'000, '\x01'); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendBytes(toBytes(payload), byteOptions(topic)); + + const auto header = expectInline(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, 50'000U) << "total_length is the pre-compression length"; + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, payload); +} + +// Rust: v2_send_bytes_somewhat_compressible_is_compressed_multipacket +TEST_F(DataStreamSendConformanceTest, SendBytesSomewhatCompressibleIsCompressedMultipacket) { + const auto topic = uniqueTopic("bytes_somewhat_z"); + const auto payload = randomText(50'000); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendBytes(toBytes(payload), byteOptions(topic)); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_FALSE(header.is_text); + const auto sizes = chunkSizes(sniffer, header.stream_id); + ASSERT_GE(sizes.size(), 2U); + EXPECT_LT(sizes.size(), 4U); + EXPECT_EQ(sizes.front(), kMtu); + EXPECT_LT(sniffer.rawContent(header.stream_id).size(), payload.size()); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, payload); +} + +// Rust: v2_send_bytes_compress_false_large_is_uncompressed_multipacket +TEST_F(DataStreamSendConformanceTest, SendBytesCompressFalseLargeIsUncompressedMultipacket) { + const auto topic = uniqueTopic("bytes_nocomp_large"); + const std::string payload(40'000, '\x07'); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = byteOptions(topic); + opts.compress = false; + (void)sender()->sendBytes(toBytes(payload), opts); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_EQ(chunkSizes(sniffer, header.stream_id), (std::vector{kMtu, kMtu, 10'000})); + EXPECT_EQ(sniffer.rawContent(header.stream_id), payload); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, payload); +} + +// --------------------------------------------------------------------------- +// sendFile +// --------------------------------------------------------------------------- + +// Rust: send_file_never_inlines_and_compresses_when_eligible +TEST_F(DataStreamSendConformanceTest, SendFileNeverInlinesAndCompresses) { + const auto topic = uniqueTopic("file_z"); + const std::string content(10'000, '\x01'); + TempFile file("ones.bin", content); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + const auto info = sender()->sendFile(file.path(), byteOptions(topic)); + + EXPECT_EQ(info.name, "ones.bin") << "the name defaults to the file's name"; + const auto header = expectMultipacket(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, content.size()); + const auto sizes = chunkSizes(sniffer, header.stream_id); + ASSERT_EQ(sizes.size(), 1U); + EXPECT_LT(sizes.front(), content.size()) << "the chunk must carry compressed bytes"; + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_EQ(s.content, content); + EXPECT_EQ(s.info.name, "ones.bin"); +} + +// Rust: send_file_uncompressed_splits_at_mtu, send_file_streams_one_packet_per_request +TEST_F(DataStreamSendConformanceTest, SendFileUncompressedSplitsAtMtu) { + const auto topic = uniqueTopic("file_nocomp"); + const std::string content(20'000, '\x07'); + TempFile file("sevens.bin", content); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = byteOptions(topic); + opts.compress = false; + (void)sender()->sendFile(file.path(), opts); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_EQ(chunkSizes(sniffer, header.stream_id), (std::vector{kMtu, 5'000})); + EXPECT_EQ(chunkIndices(sniffer, header.stream_id), (std::vector{0, 1})); + EXPECT_EQ(sniffer.rawContent(header.stream_id), content); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, content); +} + +// Rust: send_file_incompressible_compressed_expands +TEST_F(DataStreamSendConformanceTest, SendFileIncompressibleCompressedExpands) { + const auto topic = uniqueTopic("file_random"); + const auto content = randomBytes(50'000); + TempFile file("random.bin", content); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendFile(file.path(), byteOptions(topic)); + + const auto header = expectMultipacket(sniffer, topic); + const auto sizes = chunkSizes(sniffer, header.stream_id); + ASSERT_EQ(sizes.size(), 4U); + EXPECT_EQ(sizes.front(), kMtu); + EXPECT_GT(sniffer.rawContent(header.stream_id).size(), content.size()) + << "sendFile compresses whenever the recipients support it, even if that expands the data"; + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, content); +} + +// Rust: send_file_empty_file, send_file_reports_progress_for_empty_file +TEST_F(DataStreamSendConformanceTest, SendFileEmptyFile) { + const auto topic = uniqueTopic("file_empty"); + TempFile file("empty.bin", ""); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + (void)sender()->sendFile(file.path(), byteOptions(topic)); + + const auto header = expectMultipacket(sniffer, topic); + ASSERT_TRUE(header.total_length.has_value()); + EXPECT_EQ(*header.total_length, 0U); + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.content, ""); +} + +TEST_F(DataStreamSendConformanceTest, SendFileMissingFileThrows) { + const auto topic = uniqueTopic("file_missing"); + const auto missing = (std::filesystem::temp_directory_path() / uniqueStreamId("missing") / "nope.bin").string(); + EXPECT_THROW((void)sender()->sendFile(missing, byteOptions(topic)), DataStreamError); +} + +// --------------------------------------------------------------------------- +// Stream writers +// --------------------------------------------------------------------------- + +// Rust: stream_text_never_compresses_or_inlines, incremental_writer_sends_per_write +TEST_F(DataStreamSendConformanceTest, StreamTextSendsEachPacketAsItIsWritten) { + const auto topic = uniqueTopic("writer_text"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto writer = sender()->streamText(textOptions(topic)); + const auto header = sniffer.waitForHeader(topic); + ASSERT_TRUE(header.has_value()) << "the header is sent when the writer opens"; + EXPECT_EQ(header->stream_id, writer->streamId()); + EXPECT_TRUE(sniffer.chunks(header->stream_id).empty()); + + writer->write("hello world"); + ASSERT_TRUE(sniffer.waitForChunks(header->stream_id, 1)) << "each write is sent immediately"; + EXPECT_EQ(sniffer.chunks(header->stream_id).front().content, "hello world") << "writers never compress"; + writer->write("!"); + ASSERT_TRUE(sniffer.waitForChunks(header->stream_id, 2)); + EXPECT_TRUE(sniffer.trailers(header->stream_id).empty()); + + writer->close(); + ASSERT_TRUE(sniffer.waitForTrailer(header->stream_id).has_value()); + EXPECT_EQ(chunkIndices(sniffer, header->stream_id), (std::vector{0, 1})); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, "hello world!"); +} + +// Rust: stream_bytes_never_compresses_or_inlines +TEST_F(DataStreamSendConformanceTest, StreamBytesNeverCompressesOrInlines) { + const auto topic = uniqueTopic("writer_bytes"); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = byteOptions(topic); + opts.name = "blob.bin"; + opts.total_length = 4; + auto writer = sender()->streamBytes(opts); + writer->write({0, 1, 2, 3}); + writer->close(); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_EQ(header.name, "blob.bin"); + ASSERT_TRUE(header.total_length.has_value()) << "a declared total_length is sent in the header"; + EXPECT_EQ(*header.total_length, 4U); + EXPECT_EQ(sniffer.rawContent(header.stream_id), std::string("\x00\x01\x02\x03", 4)); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, std::string("\x00\x01\x02\x03", 4)); +} + +// Rust: stream_bytes_multi_write_splits_at_mtu +TEST_F(DataStreamSendConformanceTest, StreamBytesMultiWriteSplitsAtMtu) { + const auto topic = uniqueTopic("writer_split"); + const std::vector block(20'000, 0x01); + RawPacketSniffer sniffer(receiverRoom()); + ByteStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto writer = sender()->streamBytes(byteOptions(topic)); + writer->write(block); + writer->write(block); + writer->close(); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_EQ(chunkSizes(sniffer, header.stream_id), (std::vector{kMtu, 5'000, kMtu, 5'000})); + EXPECT_EQ(chunkIndices(sniffer, header.stream_id), (std::vector{0, 1, 2, 3})); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, std::string(40'000, '\x01')); +} + +// Rust: stream_text_splits_on_utf8_boundaries_at_mtu (and the utf8_chunk tests) +TEST_F(DataStreamSendConformanceTest, StreamTextSplitsOnUtf8BoundariesAtMtu) { + const auto topic = uniqueTopic("writer_utf8"); + const std::string text = std::string(14'999, 'a') + "\xF0\x9F\x98\x80" + std::string(10, 'b'); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto writer = sender()->streamText(textOptions(topic)); + writer->write(text); + writer->close(); + + const auto header = expectMultipacket(sniffer, topic); + const auto chunks = sniffer.chunks(header.stream_id); + ASSERT_EQ(chunks.size(), 2U); + EXPECT_EQ(chunks[0].content.size(), 14'999U) << "the split moves back to the character boundary"; + EXPECT_TRUE(isValidUtf8(chunks[0].content)); + EXPECT_TRUE(isValidUtf8(chunks[1].content)); + EXPECT_EQ(chunks[0].content + chunks[1].content, text); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, text); +} + +// Rust: close_with_options_sends_trailer_attributes +TEST_F(DataStreamSendConformanceTest, CloseWithAttributesSendsTrailerAttributes) { + const auto topic = uniqueTopic("writer_close_attrs"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = textOptions(topic); + opts.attributes = {{"stage", "start"}}; + auto writer = sender()->streamText(opts); + writer->write("hello"); + writer->close("", {{"result", "ok"}, {"stage", "end"}}); + + const auto header = expectMultipacket(sniffer, topic); + const auto trailer = sniffer.trailers(header.stream_id); + ASSERT_EQ(trailer.size(), 1U); + EXPECT_EQ(trailer[0].reason, ""); + const std::map trailer_attrs{{"result", "ok"}, {"stage", "end"}}; + EXPECT_EQ(trailer[0].attributes, trailer_attrs); + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.info.attributes, trailer_attrs) << "trailer attributes override the header's"; +} + +// Rust: close_with_options_sends_reason_and_attributes +TEST_F(DataStreamSendConformanceTest, CloseWithReasonSendsReasonAndAttributes) { + const auto topic = uniqueTopic("writer_close_reason"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto writer = sender()->streamText(textOptions(topic)); + writer->close("aborted", {{"cause", "cancelled"}}); + + const auto header = sniffer.waitForHeader(topic); + ASSERT_TRUE(header.has_value()); + const auto trailer = sniffer.waitForTrailer(header->stream_id); + ASSERT_TRUE(trailer.has_value()); + EXPECT_EQ(trailer->reason, "aborted"); + EXPECT_EQ(trailer->attributes, (std::map{{"cause", "cancelled"}})); + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_TRUE(s.errored); + EXPECT_NE(s.error.find("stream closed abnormally: aborted"), std::string::npos) << s.error; +} + +// Rust: stream_text_oversized_attributes_errors +TEST_F(DataStreamSendConformanceTest, StreamTextOversizedAttributesThrows) { + const auto topic = uniqueTopic("writer_big_attrs"); + RawPacketSniffer sniffer(receiverRoom()); + + auto opts = textOptions(topic); + opts.attributes = {{"big", std::string(20'000, 'x')}}; + try { + (void)sender()->streamText(opts); + FAIL() << "a header over the packet size limit must be rejected"; + } catch (const DataStreamError& e) { + EXPECT_NE(std::string(e.what()).find("stream header exceeds maximum size"), std::string::npos) << e.what(); + } + EXPECT_FALSE(sniffer.waitForHeader(topic, kQuietPeriod).has_value()) << "nothing may be sent"; +} + +// Rust: drop_raw_stream_on_non_tokio_thread_does_not_panic. Destroying an +// unclosed writer (on an application thread) must still end the stream. +TEST_F(DataStreamSendConformanceTest, DestroyedWriterSendsTrailer) { + const auto topic = uniqueTopic("writer_dropped"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + std::thread([&] { + auto writer = sender()->streamText(textOptions(topic)); + writer->write("unfinished"); + }).join(); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_FALSE(header.stream_id.empty()); + ASSERT_TRUE(collector.waitFor(1)); + EXPECT_EQ(collector.only().content, "unfinished"); +} + +// --------------------------------------------------------------------------- +// Routing and identity +// --------------------------------------------------------------------------- + +// Rust: packets_carry_no_identity_when_sender_identity_unset. Without an +// explicit sender identity, every packet is attributed to the sender. +TEST_F(DataStreamSendConformanceTest, PacketsAreAttributedToTheSender) { + const auto topic = uniqueTopic("identity_default"); + RawPacketSniffer sniffer(receiverRoom()); + + auto writer = sender()->streamText(textOptions(topic)); + writer->write("hello"); + writer->close(); + + const auto header = expectMultipacket(sniffer, topic); + EXPECT_EQ(header.sender, senderIdentity()); + for (const auto& c : sniffer.chunks(header.stream_id)) { + EXPECT_EQ(c.sender, senderIdentity()); + } + for (const auto& t : sniffer.trailers(header.stream_id)) { + EXPECT_EQ(t.sender, senderIdentity()); + } +} + +// Rust: empty_room_broadcast_is_v2_eligible +TEST_F(DataStreamSendConformanceTest, BroadcastToEmptyRoomSucceeds) { + (void)receiverRoom().disconnect(); + const auto deadline = std::chrono::steady_clock::now() + kStreamTimeout; + while (!senderRoom().remoteParticipants().empty() && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(50ms); + } + ASSERT_TRUE(senderRoom().remoteParticipants().empty()); + const auto topic = uniqueTopic("empty_room"); + EXPECT_NO_THROW((void)sender()->sendText(kShortCompressible, textOptions(topic))); + EXPECT_NO_THROW((void)sender()->sendBytes(toBytes(kShortCompressible), byteOptions(topic))); +} + +// Rust: one_shot_send_text_targets_every_packet, stream_text_targets_every_packet, +// send_file_targets_every_packet, compressed_send_file_progress_targets_every_packet, +// mixed_targeted_v2_subset_inlines_compressed +TEST_F(DataStreamSendConformanceTest, TargetedStreamsReachOnlyTheirDestinations) { + rooms_.clear(); + rooms_ = threeTestRooms(); + if (rooms_.empty()) { + GTEST_SKIP() << "LIVEKIT_TOKEN_C not set"; + } + Room& target = *rooms_[1]; + Room& bystander = *rooms_[2]; + const auto topic = uniqueTopic("targeted"); + RawPacketSniffer target_sniffer(target); + RawPacketSniffer bystander_sniffer(bystander); + TextStreamCollector target_text; + target_text.registerOn(target, topic); + ByteStreamCollector target_bytes; + target_bytes.registerOn(target, topic); + TextStreamCollector bystander_text; + bystander_text.registerOn(bystander, topic); + ByteStreamCollector bystander_bytes; + bystander_bytes.registerOn(bystander, topic); + + auto text_opts = textOptions(topic); + text_opts.destination_identities = {identityOf(target)}; + auto byte_opts = byteOptions(topic); + byte_opts.destination_identities = {identityOf(target)}; + + // Inline, compressed multi-packet, writer, and file streams. + (void)sender()->sendText(kShortCompressible, text_opts); + const auto large = randomText(50'000); + (void)sender()->sendText(large, text_opts); + auto writer = sender()->streamText(text_opts); + writer->write("written"); + writer->close(); + const auto file_content = randomBytes(20'000); + TempFile file("targeted.bin", file_content); + (void)sender()->sendFile(file.path(), byte_opts); + + ASSERT_TRUE(target_text.waitFor(3)); + ASSERT_TRUE(target_bytes.waitFor(1)); + for (const auto& s : target_text.streams()) { + EXPECT_FALSE(s.errored) << s.error; + } + EXPECT_EQ(target_bytes.only().content, file_content); + EXPECT_EQ(target_sniffer.headers(topic).size(), 4U); + + std::this_thread::sleep_for(kQuietPeriod); + EXPECT_EQ(bystander_text.openedCount(), 0U) << "a non-targeted participant must not receive the stream"; + EXPECT_EQ(bystander_bytes.openedCount(), 0U) << "a non-targeted participant must not receive the stream"; + EXPECT_TRUE(bystander_sniffer.headers(topic).empty()) << "no packet may reach a non-targeted participant"; +} + +// Rust: stream_text_with_sender_identity_stamps_every_packet, +// send_text_inline_with_sender_identity_stamps_packet, +// one_shot_send_with_sender_identity_stamps_every_packet +// (partial). The Rust tests check the identity stamped on outgoing packets. +// End to end, the SFU attributes every packet to the authenticated sender +// unless its token allows impersonation, which the test tokens do not, so +// this checks that the option is accepted, every kind of send still +// delivers, and packets arrive attributed to the real sender. +TEST_F(DataStreamSendConformanceTest, SenderIdentityOptionIsAcceptedAndDelivers) { + const auto topic = uniqueTopic("identity_override"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + auto opts = textOptions(topic); + opts.sender_identity = "impostor"; + auto writer = sender()->streamText(opts); + writer->write("written"); + writer->close(); + (void)sender()->sendText("inline", opts); + opts.compress = false; + const std::string chunked(20'000, 'A'); + (void)sender()->sendText(chunked, opts); + + ASSERT_TRUE(collector.waitFor(3)); + std::vector contents; + for (const auto& s : collector.streams()) { + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.sender, senderIdentity()); + contents.push_back(s.content); + } + std::sort(contents.begin(), contents.end()); + EXPECT_EQ(contents, (std::vector{chunked, "inline", "written"})); + for (const auto& h : sniffer.headers(topic)) { + EXPECT_EQ(h.sender, senderIdentity()); + for (const auto& c : sniffer.chunks(h.stream_id)) { + EXPECT_EQ(c.sender, senderIdentity()); + } + } +} + +} // namespace livekit::test::ds From 26679a9d98da0f040d9d46df5a4a0761bbd8cac6 Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 23 Nov 2026 08:59:13 +1300 Subject: [PATCH 08/11] Add conformance tests for the receive payload cap and reader close Ports the incoming-manager max_payload_byte_length tests (unknown total, declared total fast-fail, exactly-at-cap, inline and compressed breaches) through RoomOptions::data_stream, and the closer tests through TextStreamReader::close(). Co-Authored-By: Claude Opus 5.5 --- ...st_data_stream_conformance_receive_api.cpp | 325 ++++++++++++++++++ 1 file changed, 325 insertions(+) create mode 100644 src/tests/integration/test_data_stream_conformance_receive_api.cpp diff --git a/src/tests/integration/test_data_stream_conformance_receive_api.cpp b/src/tests/integration/test_data_stream_conformance_receive_api.cpp new file mode 100644 index 00000000..bbb08a25 --- /dev/null +++ b/src/tests/integration/test_data_stream_conformance_receive_api.cpp @@ -0,0 +1,325 @@ +/* + * 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. + */ + +// Receive-side data stream conformance for behavior controlled through the +// 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. +// See data_stream_conformance.md for the full mapping. +// +// Run with: +// ./build-debug/bin/livekit_integration_tests --gtest_filter=DataStreamReceiveApi* + +#include + +#include +#include +#include +#include +#include + +#include "../common/data_stream_test_utils.h" + +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 +// --------------------------------------------------------------------------- + +/// Captures readers as they open without reading them, so a test controls +/// exactly when (and whether) each reader is read or closed. +class ReaderCapture { +public: + void registerOn(Room& room, const std::string& topic) { + room.registerTextStreamHandler(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) { + std::unique_lock lock(mutex_); + if (!cv_.wait_for(lock, kStreamTimeout, [&] { return readers_.size() > index; })) { + return nullptr; + } + return readers_[index]; + } + + std::size_t count() { + const std::scoped_lock lock(mutex_); + return readers_.size(); + } + + ~ReaderCapture() { + const std::scoped_lock lock(mutex_); + for (auto& r : readers_) { + r->close(); + } + } + + ReaderCapture() = default; + ReaderCapture(const ReaderCapture&) = delete; + ReaderCapture& operator=(const ReaderCapture&) = delete; + ReaderCapture(ReaderCapture&&) = delete; + ReaderCapture& operator=(ReaderCapture&&) = delete; + +private: + std::mutex mutex_; + std::condition_variable cv_; + std::vector> readers_; +}; + +class DataStreamReceiveApiCloseTest : public DataStreamConformanceTest {}; + +// Rust: closer_ends_an_open_stream_once +TEST_F(DataStreamReceiveApiCloseTest, CloseEndsAnOpenStreamOnce) { + const auto topic = uniqueTopic("close_open"); + ReaderCapture capture; + capture.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + PeerTextOptions opts; + opts.topic = topic; + const auto writer = peer.openText(opts); + ASSERT_TRUE(writer.ok) << writer.error; + ASSERT_TRUE(peer.writeText(writer.writer_handle, "hello").ok); + + auto reader = capture.waitForReader(0); + ASSERT_NE(reader, nullptr); + std::string chunk; + ASSERT_TRUE(reader->readNext(chunk)); + EXPECT_EQ(chunk, "hello"); + + reader->close(); + reader->close(); // idempotent + EXPECT_FALSE(reader->readNext(chunk)) << "a closed reader reports the end of the stream"; + + // The sender keeps going; nothing reaches the closed reader and no new + // stream is opened. + ASSERT_TRUE(peer.writeText(writer.writer_handle, "world").ok); + ASSERT_TRUE(peer.closeText(writer.writer_handle).ok); + std::this_thread::sleep_for(kQuietPeriod); + EXPECT_FALSE(reader->readNext(chunk)); + EXPECT_EQ(capture.count(), 1U); +} + +// Rust: closer_discards_packets_still_queued +TEST_F(DataStreamReceiveApiCloseTest, CloseDiscardsQueuedChunks) { + const auto topic = uniqueTopic("close_queued"); + RawPacketSniffer sniffer(receiverRoom()); + ReaderCapture capture; + capture.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + PeerTextOptions opts; + opts.topic = topic; + const auto writer = peer.openText(opts); + ASSERT_TRUE(writer.ok) << writer.error; + ASSERT_TRUE(peer.writeText(writer.writer_handle, "hello").ok); + ASSERT_TRUE(peer.writeText(writer.writer_handle, "world").ok); + + auto reader = capture.waitForReader(0); + ASSERT_NE(reader, nullptr); + ASSERT_TRUE(sniffer.waitForChunks(writer.stream_id, 2)); + // Give the chunks time to reach the reader's queue, unread. + std::this_thread::sleep_for(300ms); + + reader->close(); + std::string chunk; + EXPECT_FALSE(reader->readNext(chunk)) << "closing discards chunks that were never read"; + (void)peer.closeText(writer.writer_handle); +} + +// Rust: closer_spares_a_later_stream_with_the_same_id +TEST_F(DataStreamReceiveApiCloseTest, CloseSparesALaterStreamWithTheSameId) { + const auto topic = uniqueTopic("close_same_id"); + const auto sid = uniqueStreamId("reused"); + ReaderCapture capture; + capture.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + PeerTextOptions opts; + opts.topic = topic; + opts.stream_id = sid; + + // First stream with the id runs to completion. + auto first_writer = peer.openText(opts); + ASSERT_TRUE(first_writer.ok) << first_writer.error; + ASSERT_TRUE(peer.writeText(first_writer.writer_handle, "hello").ok); + ASSERT_TRUE(peer.writeText(first_writer.writer_handle, "world").ok); + ASSERT_TRUE(peer.closeText(first_writer.writer_handle).ok); + auto first = capture.waitForReader(0); + ASSERT_NE(first, nullptr); + EXPECT_EQ(first->readAll(), "helloworld"); + + // A second stream reuses the id; closing the first reader must not touch it. + auto second_writer = peer.openText(opts); + ASSERT_TRUE(second_writer.ok) << second_writer.error; + ASSERT_TRUE(peer.writeText(second_writer.writer_handle, "hello").ok); + auto second = capture.waitForReader(1); + ASSERT_NE(second, nullptr); + first->close(); + ASSERT_TRUE(peer.writeText(second_writer.writer_handle, "world").ok); + ASSERT_TRUE(peer.closeText(second_writer.writer_handle).ok); + + std::string content; + std::thread reader_thread([&] { content = second->readAll(); }); + reader_thread.join(); + EXPECT_EQ(content, "helloworld"); + EXPECT_EQ(second->info().stream_id, sid); +} + +// Rust: closer_after_shutdown_does_nothing +TEST_F(DataStreamReceiveApiCloseTest, CloseAfterDisconnectIsHarmless) { + const auto topic = uniqueTopic("close_after_shutdown"); + ReaderCapture capture; + capture.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + PeerTextOptions opts; + opts.topic = topic; + const auto writer = peer.openText(opts); + ASSERT_TRUE(writer.ok) << writer.error; + ASSERT_TRUE(peer.writeText(writer.writer_handle, "hello").ok); + auto reader = capture.waitForReader(0); + ASSERT_NE(reader, nullptr); + + (void)receiverRoom().disconnect(); + EXPECT_THROW((void)reader->readAll(), DataStreamError) << "a stream cut off by a disconnect ends with an error"; + EXPECT_NO_THROW(reader->close()); + EXPECT_NO_THROW(reader->close()); + (void)peer.closeText(writer.writer_handle); +} + +} // namespace livekit::test::ds From da3367fab46cbcf94ccb1fbb44db1409e0d09cf4 Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 23 Nov 2026 09:01:02 +1300 Subject: [PATCH 09/11] Expose text stream operation type, version and generated Other SDKs set these text header fields (agents mark transcriptions with generated=true), but the C++ API could neither send nor see them. Add TextStreamOperationType plus operation_type / version / generated to StreamTextOptions and TextStreamInfo, and carry them through one-shot sends, stream writers and received streams. Defaults are left off the wire, matching what the SDK core treats as unset. TextStreamInfo gains members, so code built against older headers must be recompiled. Co-Authored-By: Claude Opus 5.5 --- include/livekit/data_stream.h | 31 +++++ src/data_stream.cpp | 17 ++- src/data_stream_proto_converter.cpp | 43 +++++++ src/data_stream_proto_converter.h | 10 ++ ...st_data_stream_conformance_text_header.cpp | 115 ++++++++++++++++++ src/tests/unit/test_data_stream.cpp | 29 ++++- 6 files changed, 243 insertions(+), 2 deletions(-) create mode 100644 src/tests/integration/test_data_stream_conformance_text_header.cpp diff --git a/include/livekit/data_stream.h b/include/livekit/data_stream.h index 0e1635e7..b99b320c 100644 --- a/include/livekit/data_stream.h +++ b/include/livekit/data_stream.h @@ -64,6 +64,17 @@ class LIVEKIT_API DataStreamError : public std::runtime_error { explicit DataStreamError(const std::string& message); }; +/// @brief What a text stream does to the conversation it belongs to. +/// +/// Chat-style applications use it to distinguish new messages from edits, +/// deletions and reactions; the SDK only transports it. +enum class TextStreamOperationType { + Create = 0, + Update = 1, + Delete = 2, + Reaction = 3, +}; + /// @brief Options for a one-shot text send or an incremental text stream. /// /// Used by LocalParticipant::sendText(). @@ -88,6 +99,16 @@ struct StreamTextOptions { /// Ids of other streams (for example files) attached to this text stream. std::vector attached_stream_ids; + /// Operation this stream performs (new message, edit, deletion, reaction). + TextStreamOperationType operation_type = TextStreamOperationType::Create; + + /// Version of the message this stream creates or updates, if any. + std::optional version; + + /// Whether the text was generated, for example by an agent transcribing a + /// participant's speech. + bool generated = false; + /// Compress the payload when every recipient supports compression. /// /// Only one-shot sends compress; incremental writers ignore this flag. @@ -167,6 +188,13 @@ struct TextStreamInfo : BaseStreamInfo { std::vector attachments; /// If this stream is a reply to another stream, this field holds its ID std::optional reply_to_stream_id; + /// Operation this stream performs (new message, edit, deletion, reaction). + TextStreamOperationType operation_type = TextStreamOperationType::Create; + /// Version of the message this stream creates or updates, if the sender set one. + std::optional version; + /// Whether the text was generated, for example by an agent transcribing a + /// participant's speech. + bool generated = false; }; /// Metadata for a byte stream. @@ -518,6 +546,9 @@ class LIVEKIT_API TextStreamWriter : public BaseStreamWriter { TextStreamInfo info_; std::vector attached_stream_ids_; + TextStreamOperationType operation_type_ = TextStreamOperationType::Create; + std::optional version_; + bool generated_ = false; }; /// @brief Writer for outgoing byte streams. diff --git a/src/data_stream.cpp b/src/data_stream.cpp index efb12ecd..6e1d2278 100644 --- a/src/data_stream.cpp +++ b/src/data_stream.cpp @@ -379,6 +379,15 @@ void BaseStreamWriter::openLocked() { for (const auto& id : self->attached_stream_ids_) { options.add_attached_stream_ids(id); } + if (self->operation_type_ != TextStreamOperationType::Create) { + options.set_operation_type(toProto(self->operation_type_)); + } + if (self->version_) { + options.set_version(*self->version_); + } + if (self->generated_) { + options.set_generated(true); + } options.set_sender_identity(sender_identity_); const auto owned = FfiClient::instance().textStreamOpenAsync(participant_handle, options).get(); @@ -532,12 +541,18 @@ TextStreamWriter::TextStreamWriter(FactoryTag /*tag*/, LocalParticipant& local_p : BaseStreamWriter(local_participant, options.topic, options.attributes, options.stream_id.value_or(""), std::nullopt, /*mime_type=*/"text/plain", options.destination_identities, options.sender_identity.value_or("")), - attached_stream_ids_(options.attached_stream_ids) { + attached_stream_ids_(options.attached_stream_ids), + operation_type_(options.operation_type), + version_(options.version), + generated_(options.generated) { kind_ = StreamKind::kText; reply_to_id_ = options.reply_to_stream_id.value_or(""); fillBaseInfo(info_, stream_id_, mime_type_, topic_, timestamp_ms_, total_size_, attributes_); info_.reply_to_stream_id = options.reply_to_stream_id; info_.attachments = attached_stream_ids_; + info_.operation_type = operation_type_; + info_.version = version_; + info_.generated = generated_; } void TextStreamWriter::write(const std::string& text) { diff --git a/src/data_stream_proto_converter.cpp b/src/data_stream_proto_converter.cpp index 0cb087d3..1dbc15a1 100644 --- a/src/data_stream_proto_converter.cpp +++ b/src/data_stream_proto_converter.cpp @@ -18,6 +18,34 @@ namespace livekit { +proto::TextStreamInfo::OperationType toProto(TextStreamOperationType in) { + switch (in) { + case TextStreamOperationType::Update: + return proto::TextStreamInfo::UPDATE; + case TextStreamOperationType::Delete: + return proto::TextStreamInfo::DELETE; + case TextStreamOperationType::Reaction: + return proto::TextStreamInfo::REACTION; + case TextStreamOperationType::Create: + default: + return proto::TextStreamInfo::CREATE; + } +} + +TextStreamOperationType fromProto(proto::TextStreamInfo::OperationType in) { + switch (in) { + case proto::TextStreamInfo::UPDATE: + return TextStreamOperationType::Update; + case proto::TextStreamInfo::DELETE: + return TextStreamOperationType::Delete; + case proto::TextStreamInfo::REACTION: + return TextStreamOperationType::Reaction; + case proto::TextStreamInfo::CREATE: + default: + return TextStreamOperationType::Create; + } +} + proto::StreamTextOptions toProto(const StreamTextOptions& in) { proto::StreamTextOptions out; out.set_topic(in.topic); @@ -36,6 +64,16 @@ proto::StreamTextOptions toProto(const StreamTextOptions& in) { for (const auto& id : in.attached_stream_ids) { out.add_attached_stream_ids(id); } + // Unset means Create / not generated on the wire; only send non-defaults. + if (in.operation_type != TextStreamOperationType::Create) { + out.set_operation_type(toProto(in.operation_type)); + } + if (in.version) { + out.set_version(*in.version); + } + if (in.generated) { + out.set_generated(true); + } out.set_compress(in.compress); if (in.sender_identity) { out.set_sender_identity(*in.sender_identity); @@ -89,6 +127,11 @@ TextStreamInfo fromProto(const proto::TextStreamInfo& in) { if (in.has_reply_to_stream_id()) { out.reply_to_stream_id = in.reply_to_stream_id(); } + out.operation_type = fromProto(in.operation_type()); + if (in.has_version()) { + out.version = in.version(); + } + out.generated = in.generated(); return out; } diff --git a/src/data_stream_proto_converter.h b/src/data_stream_proto_converter.h index acf3c0ee..7b98243e 100644 --- a/src/data_stream_proto_converter.h +++ b/src/data_stream_proto_converter.h @@ -22,6 +22,16 @@ namespace livekit { +/// @brief Convert a text stream operation type to the FFI enum. +/// @param in C++ operation type. +/// @return The FFI enum value. +LIVEKIT_INTERNAL_API proto::TextStreamInfo::OperationType toProto(TextStreamOperationType in); + +/// @brief Convert an FFI text stream operation type to the public enum. +/// @param in FFI enum value. +/// @return The C++ operation type. +LIVEKIT_INTERNAL_API TextStreamOperationType fromProto(proto::TextStreamInfo::OperationType in); + /// @brief Convert one-shot text send options to the FFI proto. /// @param in C++ options. /// @return The FFI options; `compress` is always set explicitly. diff --git a/src/tests/integration/test_data_stream_conformance_text_header.cpp b/src/tests/integration/test_data_stream_conformance_text_header.cpp new file mode 100644 index 00000000..3f73a2c0 --- /dev/null +++ b/src/tests/integration/test_data_stream_conformance_text_header.cpp @@ -0,0 +1,115 @@ +/* + * 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. + */ + +// Text stream header fields (operation type, version, generated, reply-to) +// in both directions: another SDK's text stream must surface them on the C++ +// TextStreamInfo, and C++ text streams must put them on the wire. Agents, for +// example, mark transcriptions with `generated`. +// +// Run with: +// ./build-debug/bin/livekit_integration_tests --gtest_filter=DataStreamTextHeader* + +#include + +#include + +#include "../common/data_stream_test_utils.h" + +namespace livekit::test::ds { + +class DataStreamTextHeaderTest : public DataStreamConformanceTest {}; + +TEST_F(DataStreamTextHeaderTest, RemoteHeaderFieldsSurfaceOnInfo) { + const auto topic = uniqueTopic("hdr_recv"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + FfiPeer peer(senderRoom()); + + PeerTextOptions opts; + opts.topic = topic; + opts.operation_type = static_cast(TextStreamOperationType::Update); + opts.version = 3; + opts.generated = true; + opts.reply_to_stream_id = "original"; + ASSERT_TRUE(peer.sendText("edited", opts).ok); // one-shot (inline) + const auto writer = peer.openText(opts); // writer (multi-packet) + ASSERT_TRUE(writer.ok) << writer.error; + ASSERT_TRUE(peer.writeText(writer.writer_handle, "edited again").ok); + ASSERT_TRUE(peer.closeText(writer.writer_handle).ok); + + ASSERT_TRUE(collector.waitFor(2)); + for (const auto& s : collector.streams()) { + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.info.operation_type, TextStreamOperationType::Update); + ASSERT_TRUE(s.info.version.has_value()); + EXPECT_EQ(*s.info.version, 3); + EXPECT_TRUE(s.info.generated); + ASSERT_TRUE(s.info.reply_to_stream_id.has_value()); + EXPECT_EQ(*s.info.reply_to_stream_id, "original"); + } +} + +TEST_F(DataStreamTextHeaderTest, LocalHeaderFieldsAreSent) { + const auto topic = uniqueTopic("hdr_send"); + RawPacketSniffer sniffer(receiverRoom()); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + auto sender = lockLocalParticipant(senderRoom()); + + StreamTextOptions opts; + opts.topic = topic; + opts.operation_type = TextStreamOperationType::Reaction; + opts.version = 5; + opts.generated = true; + (void)sender->sendText("+1", opts); + auto writer = sender->streamText(opts); + EXPECT_EQ(writer->info().operation_type, TextStreamOperationType::Reaction); + writer->write("+1 again"); + writer->close(); + + ASSERT_TRUE(collector.waitFor(2)); + for (const auto& s : collector.streams()) { + EXPECT_FALSE(s.errored) << s.error; + EXPECT_EQ(s.info.operation_type, TextStreamOperationType::Reaction); + ASSERT_TRUE(s.info.version.has_value()); + EXPECT_EQ(*s.info.version, 5); + EXPECT_TRUE(s.info.generated); + } + const auto headers = sniffer.headers(topic); + ASSERT_EQ(headers.size(), 2U); + for (const auto& h : headers) { + EXPECT_EQ(h.operation_type, static_cast(TextStreamOperationType::Reaction)); + EXPECT_EQ(h.version, 5); + EXPECT_TRUE(h.generated); + } +} + +TEST_F(DataStreamTextHeaderTest, DefaultsAreCreateUnversionedNotGenerated) { + const auto topic = uniqueTopic("hdr_default"); + TextStreamCollector collector; + collector.registerOn(receiverRoom(), topic); + + StreamTextOptions opts; + opts.topic = topic; + (void)lockLocalParticipant(senderRoom())->sendText("plain", opts); + + ASSERT_TRUE(collector.waitFor(1)); + const auto s = collector.only(); + EXPECT_EQ(s.info.operation_type, TextStreamOperationType::Create); + EXPECT_FALSE(s.info.generated); +} + +} // namespace livekit::test::ds diff --git a/src/tests/unit/test_data_stream.cpp b/src/tests/unit/test_data_stream.cpp index 73669aac..e03ebc97 100644 --- a/src/tests/unit/test_data_stream.cpp +++ b/src/tests/unit/test_data_stream.cpp @@ -231,7 +231,9 @@ TEST(DataStreamConversionTest, TextOptionsDefaultsToProto) { EXPECT_FALSE(proto.has_id()); EXPECT_FALSE(proto.has_reply_to_stream_id()); EXPECT_FALSE(proto.has_sender_identity()); - EXPECT_FALSE(proto.has_operation_type()); + EXPECT_FALSE(proto.has_operation_type()) << "Create is the wire default"; + EXPECT_FALSE(proto.has_version()); + EXPECT_FALSE(proto.has_generated()); EXPECT_EQ(proto.destination_identities_size(), 0); } @@ -243,10 +245,16 @@ TEST(DataStreamConversionTest, TextOptionsAllFieldsToProto) { options.stream_id = "stream-1"; options.reply_to_stream_id = "stream-0"; options.attached_stream_ids = {"file-1"}; + options.operation_type = TextStreamOperationType::Update; + options.version = 3; + options.generated = true; options.compress = false; options.sender_identity = "agent"; const auto proto = toProto(options); + EXPECT_EQ(proto.operation_type(), proto::TextStreamInfo::UPDATE); + EXPECT_EQ(proto.version(), 3); + EXPECT_TRUE(proto.generated()); EXPECT_EQ(attrs(proto.attributes()), (std::map{{"k", "v"}})); ASSERT_EQ(proto.destination_identities_size(), 2); EXPECT_EQ(proto.destination_identities(1), "bob"); @@ -320,6 +328,25 @@ TEST(DataStreamConversionTest, TextInfoFromProto) { ASSERT_TRUE(out.size.has_value()); EXPECT_EQ(*out.size, 10u); EXPECT_FALSE(out.reply_to_stream_id.has_value()); + EXPECT_EQ(out.operation_type, TextStreamOperationType::Create); + EXPECT_FALSE(out.version.has_value()); + EXPECT_FALSE(out.generated); + + in.set_operation_type(proto::TextStreamInfo::REACTION); + in.set_version(7); + in.set_generated(true); + out = fromProto(in); + EXPECT_EQ(out.operation_type, TextStreamOperationType::Reaction); + ASSERT_TRUE(out.version.has_value()); + EXPECT_EQ(*out.version, 7); + EXPECT_TRUE(out.generated); +} + +TEST(DataStreamConversionTest, TextOperationTypeRoundTrips) { + for (const auto type : {TextStreamOperationType::Create, TextStreamOperationType::Update, + TextStreamOperationType::Delete, TextStreamOperationType::Reaction}) { + EXPECT_EQ(fromProto(toProto(type)), type); + } } TEST(DataStreamConversionTest, ByteInfoFromProto) { From 8e286e50e50da8886aa819cc633f3285ffd94ea2 Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 23 Nov 2026 09:07:15 +1300 Subject: [PATCH 10/11] Add ByteStreamReader::writeToFile Wrap the FFI's write-to-file so a received byte stream can be written straight to disk by the SDK core, which also rejects sender-chosen file names that are not plain file names (path separators, "..", absolute paths, empty). Write-to-file and incremental reading both consume the FFI reader handle, so byte readers now start reading lazily: the first readNext() / readAll() starts incremental reading, writeToFile() hands the stream to the core instead, and a reader closed or destroyed unconsumed drops its handle. Room tracks byte readers weakly so an ignored reader releases its stream rather than being kept alive by the room. Ports the Rust write_to_file tests end to end, plus the one-consumer rule, the event-thread guard and ignored readers. Co-Authored-By: Claude Opus 5.5 --- include/livekit/data_stream.h | 35 ++ include/livekit/room.h | 5 +- src/data_stream.cpp | 97 +++++- src/ffi_client.cpp | 47 +++ src/ffi_client.h | 7 + src/room.cpp | 30 +- ..._data_stream_conformance_write_to_file.cpp | 323 ++++++++++++++++++ 7 files changed, 524 insertions(+), 20 deletions(-) create mode 100644 src/tests/integration/test_data_stream_conformance_write_to_file.cpp diff --git a/include/livekit/data_stream.h b/include/livekit/data_stream.h index b99b320c..7043f2f0 100644 --- a/include/livekit/data_stream.h +++ b/include/livekit/data_stream.h @@ -289,6 +289,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. @@ -319,6 +324,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. @@ -355,6 +382,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 a3ac4b10..8e7a1a2b 100644 --- a/include/livekit/room.h +++ b/include/livekit/room.h @@ -381,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 6e1d2278..b62dfae7 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 "data_stream_proto_converter.h" #include "data_stream_writer_registry.h" @@ -167,7 +170,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()) {} @@ -195,7 +217,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)); } @@ -204,7 +250,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; @@ -215,7 +264,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 registry diff --git a/src/ffi_client.cpp b/src/ffi_client.cpp index 5599ac94..e0d1a4ff 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::textStreamOpenAsync(std::uint64_t local_participant_handle, const proto::StreamTextOptions& options) { const AsyncId async_id = generateAsyncId(); diff --git a/src/ffi_client.h b/src/ffi_client.h index 0be0eb58..ff248e37 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); + // Incremental writers. Open creates an owned writer handle; write borrows // it; close consumes it (never drop the handle after calling close). std::future textStreamOpenAsync(std::uint64_t local_participant_handle, 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/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 From 07561ec08c0390868c6cc05d97d6a213792699cd Mon Sep 17 00:00:00 2001 From: Ryan Gaus Date: Mon, 23 Nov 2026 09:09:18 +1300 Subject: [PATCH 11/11] Document the data stream conformance tests Map every test of the Rust livekit-data-stream crate to its C++ conformance test, or say why it cannot be expressed from the C++ layer (no progress API, no pre-v2 recipients, malformed v2 packets, per-packet encryption, manager internals, SFU sender attribution). Also document writeToFile and lazy byte reading in README / AGENTS.md, and give the three-participant disconnect test more time for its final stream, which can be slow to drain on a congested local network. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- README.md | 5 +- .../integration/data_stream_conformance.md | 210 ++++++++++++++++++ ...est_data_stream_conformance_receive_v1.cpp | 2 +- 4 files changed, 215 insertions(+), 4 deletions(-) create mode 100644 src/tests/integration/data_stream_conformance.md diff --git a/AGENTS.md b/AGENTS.md index a747984a..62937f3b 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()` and `close()` are serialized by an internal mutex and each waits for its FFI callback, so `close()` never overtakes a write. `LocalParticipant` closes its writers on disconnect (via a shared registry, so writers may outlive the participant); later calls throw `DataStreamError`. Create writers with `LocalParticipant::streamText` / `streamBytes`; the constructors are deprecated. | 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/src/tests/integration/data_stream_conformance.md b/src/tests/integration/data_stream_conformance.md new file mode 100644 index 00000000..5a8ad363 --- /dev/null +++ b/src/tests/integration/data_stream_conformance.md @@ -0,0 +1,210 @@ +# Data stream conformance tests + +The `test_data_stream_conformance_*.cpp` integration tests port the unit tests +of the Rust `livekit-data-stream` crate +(`client-sdk-rust/livekit-data-stream/src`) to end-to-end C++ tests against a +real SFU. They check that the C++ SDK sends and receives data streams the way +every other LiveKit SDK does, including data streams v2 (inline single-packet +streams and deflate-compressed streams). + +| File | What it covers | Needs API added with the FFI port | +|------|----------------|-----------------------------------| +| `test_data_stream_conformance_receive_v1.cpp` | Receiving v1 streams: hand-built packets, remote writers, disconnects | No | +| `test_data_stream_conformance_receive_v2.cpp` | Receiving v2 streams: inline, compressed, attachments | No | +| `test_data_stream_conformance_receive_api.cpp` | Receive payload cap (`RoomOptions::data_stream`), `reader->close()` | Yes | +| `test_data_stream_conformance_send.cpp` | Sending through `sendText` / `sendBytes` / `sendFile` / `streamText` / `streamBytes` | Yes | +| `test_data_stream_conformance_text_header.cpp` | Text operation type / version / generated, both directions | Yes | +| `test_data_stream_conformance_write_to_file.cpp` | `ByteStreamReader::writeToFile` | Yes | + +Shared helpers live in `src/tests/common/data_stream_test_utils.h`: + +- `FfiPeer` drives a room's participant through the raw FFI, so it sends + exactly what another FFI-based SDK sends. Its one-shot sends and writers go + through the Rust outgoing manager, and its raw header / chunk / trailer + requests send hand-built v1 packets. +- `RawPacketSniffer` records the raw stream packets a room receives. The FFI's + raw header event carries neither `inline_content` nor `compression`, so an + inline stream shows up as a header with no chunk or trailer packets, and + compression shows up as chunk bytes that differ from, and are smaller than, + the payload. +- `TextStreamCollector` / `ByteStreamCollector` receive through the public C++ + API. + +The receive-side v1 and v2 files use only API that predates the FFI port, so +they also build against the old C++ data stream implementation. There, 22 of +their 27 tests fail. + +Tests with a third participant (`SenderDisconnectOnlyAffectsItsOwnStreams`, +`TargetedStreamsReachOnlyTheirDestinations`) need `LIVEKIT_TOKEN_C`, which +`scripts/set-test-tokens.sh` mints, and skip without it. + +## What cannot be tested from the C++ layer + +- **Progress reporting.** The FFI exposes no send or receive progress. +- **Recipients without v2 support.** Every FFI client advertises data streams + v2 with deflate-raw compression, so a test can't create a pre-v2 recipient or + one without compression. The Rust pre-v2 / mixed-room routing tests therefore + have no end-to-end equivalent. +- **Malformed v2 packets.** The FFI can send hand-built v1 packets only; v2 + packets come from the Rust outgoing manager, which never produces gaps, + unknown compression types, inline/length mismatches or compressed duplicates. +- **Per-packet encryption mismatches.** A sender can't change encryption + mid-stream. +- **Manager internals.** Open-stream counts, `StreamClosed` events, transport + batching and the internal-topic filtering of raw events aren't exposed to the + C++ SDK. +- **The outgoing `sender_identity` stamp.** The SFU attributes packets to the + authenticated participant unless its token allows impersonation, which the + test tokens don't. + +The C++ SDK delegates all of these to the Rust crate, whose own unit tests +cover them. + +## Rust test → C++ test + +"Partial" means the C++ test checks what is observable end to end, and the +note says what is not. + +### `outgoing/manager.rs` (60) + +| Rust test | C++ test (`DataStreamSendConformanceTest.*` unless noted) | +|-----------|----------------------------------------------------------| +| one_shot_progress_follows_acknowledgement | N/A: no progress API | +| pre_v2_short_text_is_legacy_multipacket | N/A: no pre-v2 recipient | +| pre_v2_long_text_splits_at_mtu | N/A: no pre-v2 recipient (MTU split: SendTextCompressFalseLargeIsUncompressedMultipacket) | +| pre_v2_bytes_is_legacy_multipacket | N/A: no pre-v2 recipient | +| pre_v2_empty_text_sends_header_and_trailer | N/A: no pre-v2 recipient | +| v2_short_compressible_text_inlines_compressed | SendTextShortCompressibleInlines (partial: compression flag not visible) | +| v2_short_incompressible_text_inlines_raw | SendTextShortIncompressibleInlines | +| v2_no_compression_cap_inlines_raw | N/A: no recipient without compression | +| v2_large_highly_compressible_text_still_inlines | SendTextLargeHighlyCompressibleStillInlines | +| v2_somewhat_compressible_text_is_compressed_multipacket | SendTextSomewhatCompressibleIsCompressedMultipacket | +| v2_compress_false_short_inlines_raw | SendTextCompressFalseShortInlines (partial: compression flag not visible) | +| v2_compress_false_large_is_uncompressed_multipacket | SendTextCompressFalseLargeIsUncompressedMultipacket | +| v2_send_text_with_attachments_never_inlines | SendTextWithAttachmentsNeverInlines | +| v2_large_text_to_uncapable_recipient_is_uncompressed_multipacket | N/A: no recipient without compression | +| v2_empty_text_sends_single_inline_packet | SendTextEmptyIsSingleInlinePacket | +| v2_send_bytes_short_incompressible_inlines_raw | SendBytesShortIncompressibleInlines | +| v2_send_bytes_no_compression_cap_inlines_raw | N/A: no recipient without compression | +| v2_send_bytes_large_highly_compressible_inlines | SendBytesLargeHighlyCompressibleInlines | +| v2_send_bytes_somewhat_compressible_is_compressed_multipacket | SendBytesSomewhatCompressibleIsCompressedMultipacket | +| v2_send_bytes_compress_false_large_is_uncompressed_multipacket | SendBytesCompressFalseLargeIsUncompressedMultipacket | +| v2_send_bytes_short_compressible_inlines_compressed | SendBytesShortCompressibleInlinesAndReturnsInfo | +| send_file_never_inlines_and_compresses_when_eligible | SendFileNeverInlinesAndCompresses | +| send_file_uncompressed_splits_at_mtu | SendFileUncompressedSplitsAtMtu | +| send_file_incompressible_compressed_expands | SendFileIncompressibleCompressedExpands | +| send_file_to_no_compression_recipient_is_uncompressed | N/A: no recipient without compression | +| send_file_reports_progress_after_each_chunk | N/A: no progress API | +| compressed_send_file_reports_rising_progress_and_the_total_last | N/A: no progress API | +| compressed_send_file_without_its_last_chunk_never_reports_the_total | N/A: no progress API or transport fault injection | +| send_file_reports_progress_for_empty_file | SendFileEmptyFile (partial: no progress API) | +| send_file_empty_file | SendFileEmptyFile | +| v2_broadcast_all_capable_inlines_compressed | SendTextShortCompressibleInlines (broadcast; partial: compression flag not visible) | +| v2_broadcast_with_uncapable_member_inlines_raw | N/A: no recipient without compression | +| empty_room_broadcast_is_v2_eligible | BroadcastToEmptyRoomSucceeds (partial: with nobody listening, no packet can be inspected) | +| mixed_broadcast_falls_back_to_legacy | N/A: no pre-v2 recipient | +| mixed_targeted_v2_subset_inlines_compressed | TargetedStreamsReachOnlyTheirDestinations (partial) | +| mixed_targeted_subset_missing_cap_inlines_uncompressed | N/A: no recipient without compression | +| stream_text_with_sender_identity_stamps_every_packet | SenderIdentityOptionIsAcceptedAndDelivers (partial: SFU attribution) | +| send_text_inline_with_sender_identity_stamps_packet | SenderIdentityOptionIsAcceptedAndDelivers (partial: SFU attribution) | +| packets_carry_no_identity_when_sender_identity_unset | PacketsAreAttributedToTheSender | +| one_shot_send_text_targets_every_packet | TargetedStreamsReachOnlyTheirDestinations | +| stream_text_targets_every_packet | TargetedStreamsReachOnlyTheirDestinations | +| send_file_targets_every_packet | TargetedStreamsReachOnlyTheirDestinations | +| compressed_send_file_progress_targets_every_packet | TargetedStreamsReachOnlyTheirDestinations (partial: no progress API) | +| stream_text_never_compresses_or_inlines | StreamTextSendsEachPacketAsItIsWritten | +| stream_text_declares_total_length | N/A: text stream options carry no total length over the FFI (byte streams: StreamBytesNeverCompressesOrInlines) | +| stream_bytes_never_compresses_or_inlines | StreamBytesNeverCompressesOrInlines | +| oversized_attributes_on_chunked_path_errors | SendTextOversizedAttributesThrows | +| enforce_header_size_accepts_small_header | Implied by every send test (internal function) | +| enforce_header_size_rejects_large_header | SendTextOversizedAttributesThrows, StreamTextOversizedAttributesThrows | +| drop_raw_stream_on_non_tokio_thread_does_not_panic | DestroyedWriterSendsTrailer | +| one_shot_send_text_is_a_single_transport_request | N/A: transport batching is internal | +| one_shot_send_bytes_is_a_single_transport_request | N/A: transport batching is internal | +| one_shot_send_with_sender_identity_stamps_every_packet | SenderIdentityOptionIsAcceptedAndDelivers (partial: SFU attribution) | +| incremental_writer_sends_per_write | StreamTextSendsEachPacketAsItIsWritten | +| send_file_streams_one_packet_per_request | SendFileUncompressedSplitsAtMtu (partial: batching is internal) | +| stream_bytes_multi_write_splits_at_mtu | StreamBytesMultiWriteSplitsAtMtu | +| close_with_options_sends_trailer_attributes | CloseWithAttributesSendsTrailerAttributes | +| close_with_options_sends_reason_and_attributes | CloseWithReasonSendsReasonAndAttributes | +| stream_text_oversized_attributes_errors | StreamTextOversizedAttributesThrows | +| stream_text_splits_on_utf8_boundaries_at_mtu | StreamTextSplitsOnUtf8BoundariesAtMtu | + +### `incoming/manager.rs` (54) + +| Rust test | C++ test | +|-----------|----------| +| v1_text_stream_round_trips | DataStreamReceiveV1Test.V1TextStreamRoundTrips | +| v1_byte_stream_round_trips | DataStreamReceiveV1Test.V1ByteStreamRoundTrips | +| v1_merges_trailer_attributes | DataStreamReceiveV1Test.V1TrailerAttributesMergedAfterClose, .RemoteTextWriterRoundTripsWithTrailerAttributes | +| v1_errors_when_too_few_bytes | DataStreamReceiveV1Test.V1ErrorsWhenTooFewBytes, .RemoteWriterTooFewBytesErrors | +| v1_errors_when_too_many_bytes | DataStreamReceiveV1Test.V1ErrorsWhenTooManyBytes, .RemoteWriterTooManyBytesErrors | +| v1_max_payload_size_breached_with_unknown_total | DataStreamReceiveApiCapTest.BreachedWithUnknownTotal | +| v1_max_payload_size_fast_fails_on_declared_total | DataStreamReceiveApiCapTest.FastFailsOnDeclaredTotal | +| v1_payload_exactly_at_max_payload_size_succeeds | DataStreamReceiveApiCapTest.PayloadExactlyAtCapSucceeds | +| v1_drops_on_encryption_type_mismatch | N/A: per-packet encryption mismatch | +| v1_drops_on_trailer_encryption_type_mismatch | N/A: per-packet encryption mismatch | +| v1_trailer_attributes_merged_after_close | DataStreamReceiveV1Test.V1TrailerAttributesMergedAfterClose | +| v2_inline_uncompressed_text | DataStreamReceiveV2Test.V2InlineUncompressedText | +| v2_inline_uncompressed_byte | DataStreamReceiveV2Test.V2InlineUncompressedByte | +| v2_inline_compressed_text | DataStreamReceiveV2Test.V2InlineCompressedText | +| v2_inline_compressed_byte | DataStreamReceiveV2Test.V2InlineCompressedByte | +| v2_inline_compressed_max_payload_size_breached | DataStreamReceiveApiCapTest.InlineCompressedBreached | +| v2_inline_uncompressed_max_payload_size_breached | DataStreamReceiveApiCapTest.InlineUncompressedBreached | +| v2_inline_payload_is_held_to_its_declared_length | N/A: malformed v2 packet (consistent lengths are covered by the inline tests) | +| v2_inline_zero_length_text | DataStreamReceiveV2Test.V2InlineZeroLengthText | +| v2_multipacket_compressed_text | DataStreamReceiveV2Test.V2MultipacketCompressedText | +| errors_open_streams_on_sender_disconnect | DataStreamReceiveV1Test.SenderDisconnectErrorsOpenStreams | +| abort_only_affects_matching_sender | DataStreamReceiveV1Test.SenderDisconnectOnlyAffectsItsOwnStreams | +| v2_compressed_gap_errors | N/A: malformed v2 packet (v1 gap: V1MissedChunkErrors) | +| v2_max_payload_size_breached | DataStreamReceiveApiCapTest.CompressedMultipacketBreached | +| v2_multipacket_compressed_byte_stream | DataStreamReceiveV2Test.V2MultipacketCompressedByteStream | +| v2_compressed_errors_when_too_few_bytes | N/A: malformed v2 packet (v1: V1ErrorsWhenTooFewBytes) | +| v2_compressed_errors_when_too_many_bytes | N/A: malformed v2 packet (v1: V1ErrorsWhenTooManyBytes) | +| v1_duplicate_chunk_dropped | DataStreamReceiveV1Test.V1DuplicateChunkDropped | +| v2_compressed_duplicate_chunk_dropped | N/A: malformed v2 packet | +| v2_compressed_text_reframes_multibyte_utf8 | DataStreamReceiveV2Test.V2CompressedTextReframesMultibyteUtf8 (high-entropy multibyte text instead of a hand-split stream) | +| v2_unknown_compression_type_is_ignored | N/A: malformed v2 packet | +| v2_compressed_merges_trailer_attributes | N/A: no sender puts trailer attributes on a compressed stream (v1: V1TrailerAttributesMergedAfterClose) | +| progress_reports_completion_uncompressed_bytes | N/A: no progress API | +| progress_reports_completion_compressed_text | N/A: no progress API (content: V2MultipacketCompressedText) | +| progress_reports_completion_inline | N/A: no progress API | +| progress_stream_outlives_a_consuming_read | N/A: no progress API | +| closer_after_shutdown_does_nothing | DataStreamReceiveApiCloseTest.CloseAfterDisconnectIsHarmless | +| closer_ends_an_open_stream_once | DataStreamReceiveApiCloseTest.CloseEndsAnOpenStreamOnce | +| closer_discards_packets_still_queued | DataStreamReceiveApiCloseTest.CloseDiscardsQueuedChunks | +| closer_spares_a_later_stream_with_the_same_id | DataStreamReceiveApiCloseTest.CloseSparesALaterStreamWithTheSameId | +| counts_streams_across_their_lifecycle | N/A: open-stream count is internal | +| inline_streams_are_never_counted | N/A: open-stream count is internal (inline delivery: V2InlineUncompressedText) | +| shutdown_errors_open_streams | DataStreamReceiveV1Test.ReceiverDisconnectErrorsOpenStreams | +| dropping_all_inputs_errors_open_streams | DataStreamReceiveV1Test.ReceiverDisconnectErrorsOpenStreams (closest C++ equivalent) | +| trailer_close_emits_stream_closed | N/A: StreamClosed is internal (the reader's end is checked everywhere) | +| inline_stream_emits_stream_closed | N/A: StreamClosed is internal (V2InlineUncompressedText) | +| error_close_emits_stream_closed | DataStreamReceiveV1Test.V1MissedChunkErrors | +| abort_emits_stream_closed | DataStreamReceiveV1Test.SenderDisconnectErrorsOpenStreams | +| trailer_for_unopened_stream_emits_no_stream_closed | DataStreamReceiveV1Test.OrphanChunkAndTrailerAreIgnored | +| empty_chunks_are_ignored | DataStreamReceiveV1Test.EmptyChunksAreIgnored | +| trailer_with_reason_errors_abnormal_end | DataStreamReceiveV1Test.V1TrailerWithReasonErrorsAbnormalEnd, .RemoteWriterCloseWithReasonErrorsAbnormalEnd | +| text_stream_with_attachments_round_trips | DataStreamReceiveV2Test.TextStreamWithAttachmentsRoundTrips | +| chunk_and_trailer_report_the_topic_of_their_stream | N/A: internal-topic filtering of raw events is host policy the C++ SDK doesn't consume | +| chunk_for_an_unopened_stream_reports_no_topic | DataStreamReceiveV1Test.OrphanChunkAndTrailerAreIgnored | + +### `incoming/stream_reader.rs` (6) + +| Rust test | C++ test (`DataStreamWriteToFileTest.*`) | +|-----------|------------------------------------------| +| write_to_file_accepts_plain_name | AcceptsPlainName | +| write_to_file_rejects_traversal_in_stream_name | RejectsTraversalInStreamName | +| write_to_file_rejects_traversal_in_name_override | RejectsTraversalInNameOverride | +| write_to_file_rejects_absolute_path_in_stream_name | RejectsAbsolutePathInStreamName | +| write_to_file_rejects_nested_path_in_stream_name | RejectsNestedPathInStreamName | +| write_to_file_rejects_empty_stream_name | RejectsEmptyStreamName | + +### `utf8_chunk.rs` (4) + +`test_string_chunking`, `test_empty_string_chunking`, +`test_single_character_string_chunking` and `test_mixed_string_chunking` unit +test an internal chunking helper. The C++ SDK never chunks text itself; the +behavior they protect is checked end to end by +`DataStreamSendConformanceTest.StreamTextSplitsOnUtf8BoundariesAtMtu` and +`DataStreamReceiveV2Test.V2CompressedTextReframesMultibyteUtf8`. diff --git a/src/tests/integration/test_data_stream_conformance_receive_v1.cpp b/src/tests/integration/test_data_stream_conformance_receive_v1.cpp index 8e9c899a..53b76afe 100644 --- a/src/tests/integration/test_data_stream_conformance_receive_v1.cpp +++ b/src/tests/integration/test_data_stream_conformance_receive_v1.cpp @@ -437,7 +437,7 @@ TEST_F(DataStreamReceiveV1Test, SenderDisconnectOnlyAffectsItsOwnStreams) { rooms[0].reset(); ASSERT_TRUE(collector.waitFor(1)); ASSERT_TRUE(staying.closeText(staying_writer.writer_handle).ok); - ASSERT_TRUE(collector.waitFor(2)); + ASSERT_TRUE(collector.waitFor(2, 2 * kStreamTimeout)) << "the remaining sender's stream must still complete"; for (const auto& s : collector.streams()) { if (s.sender == staying.identity()) {