diff --git a/src/extensions/rppgrpc/rppgrpc/client_reactor.hpp b/src/extensions/rppgrpc/rppgrpc/client_reactor.hpp index 68c4f9924..1eb642e5a 100644 --- a/src/extensions/rppgrpc/rppgrpc/client_reactor.hpp +++ b/src/extensions/rppgrpc/rppgrpc/client_reactor.hpp @@ -28,7 +28,7 @@ namespace rppgrpc * - to access values FROM stream you can subscribe to observable obtained via `reactor->get_observable()` (same observable WOULD emit on_completed in case of successful stream termination and on_error in case of some errors with grpc stream) * - to pass values TO stream you can emit values to observer obtained via `reactor->get_observer()` * - * @warning After `init()` the call may end at any moment (connection refused, deadline, cancel) and the reactor deletes itself in `OnDone`. Obtain the observer and emit the first values before `init()`: they are posted and sent once the call starts. Emitting from outside the reactor's callbacks after `init()` races with the end of the call (gRPC requires a hold for that, see `grpc::ClientBidiReactor::AddHold`). + * @warning After `init()` the call may end at any moment (connection refused, deadline, cancel) and the reactor deletes itself in `OnDone`, so obtain the observer and the observable before `init()` and do not use the reactor afterwards. The observer may be used from any thread, also after `init()`: the reactor holds the call (see `grpc::ClientBidiReactor::AddHold`) until its read side has ended; values still queued then, and values emitted after that, are dropped. * * @snippet client_reactor.cpp bidi_reactor * @@ -46,6 +46,9 @@ namespace rppgrpc void init() { + // The observer may write from outside the reactions after StartCall(), which gRPC allows + // only under a hold. OnReadDone(false) releases it. + Base::AddHold(); // The first read is posted before StartCall(): gRPC keeps it until the call starts and // counts it as an outstanding operation. StartCall() is the last use of the reactor in // init(), because a call that ends at once may run OnDone (and so `delete this`) on a @@ -79,7 +82,15 @@ namespace rppgrpc void OnReadDone(bool ok) override { if (!ok) + { + // One read is always posted, so each call ends its read side exactly once, here. + // A write that took the observer's lock before close_writes() has called StartWrite + // and is counted by gRPC, so OnDone comes after its OnWriteDone; later and still queued + // writes are dropped. This reaction is itself still counted, so RemoveHold() does not run OnDone. + details::base_writer::close_writes(); + Base::RemoveHold(); return; + } details::base_reader::handle_read_done(); } diff --git a/src/extensions/rppgrpc/rppgrpc/details/base.hpp b/src/extensions/rppgrpc/rppgrpc/details/base.hpp index f1f388b39..4adc20a23 100644 --- a/src/extensions/rppgrpc/rppgrpc/details/base.hpp +++ b/src/extensions/rppgrpc/rppgrpc/details/base.hpp @@ -19,6 +19,7 @@ #include "rpp/subjects/publish_subject.hpp" #include +#include #include namespace rppgrpc::details @@ -29,9 +30,14 @@ namespace rppgrpc::details public: base_writer() { - m_subject.get_observable().subscribe(typename details::base_writer::observer_strategy{*this}); + m_state->owner = this; + m_subject.get_observable().subscribe(typename details::base_writer::observer_strategy{m_state}); } + // The observer's shared state points back at this object, so a copy would write through the original. + base_writer(const base_writer&) = delete; + base_writer& operator=(const base_writer&) = delete; + virtual ~base_writer() noexcept = default; auto get_observer() const @@ -45,54 +51,85 @@ namespace rppgrpc::details void handle_on_done() { + close_writes(); m_subject.get_disposable().dispose(); } + // Values and terminals emitted to the observer after this call, and values still queued, reach neither this object nor its stream. + // It waits for an emission that is inside start_write or finish_writes. + void close_writes() + { + std::lock_guard lock{m_state->mutex}; + m_state->owner = nullptr; + } + void handle_write_done() { - std::lock_guard lock{m_write_mutex}; - m_write.pop_front(); + std::lock_guard lock{m_state->mutex}; + m_state->queue.pop_front(); + + if (!m_state->owner) + return; - if (!m_write.empty()) + if (!m_state->queue.empty()) { - start_write(m_write.front()); + start_write(m_state->queue.front()); } - else if (m_finished) + else if (m_state->finished) { finish_writes(grpc::Status::OK); } } + // Shared by this object and the observer subscribed to the subject, so it outlives this object: an emission + // that has passed the subject when this object ends still locks a live mutex and finds no owner. + struct write_state + { + std::mutex mutex{}; + std::deque queue{}; + bool finished{}; + base_writer* owner{}; + }; + struct observer_strategy { static constexpr auto preferred_disposables_mode = rpp::details::observers::disposables_mode::Auto; - std::reference_wrapper owner{}; + std::shared_ptr state{}; template T> void on_next(T&& message) const { - std::lock_guard lock{owner.get().m_write_mutex}; - owner.get().m_write.push_back(std::forward(message)); - if (owner.get().m_write.size() == 1) - owner.get().start_write(owner.get().m_write.front()); + std::lock_guard lock{state->mutex}; + if (!state->owner) + return; + + state->queue.push_back(std::forward(message)); + if (state->queue.size() == 1) + state->owner->start_write(state->queue.front()); } void on_error(const std::exception_ptr&) const { - std::lock_guard lock{owner.get().m_write_mutex}; - owner.get().m_finished = true; + std::lock_guard lock{state->mutex}; + if (!state->owner) + return; - if (owner.get().m_write.size() == 0) - owner.get().finish_writes(grpc::Status{grpc::StatusCode::INTERNAL, "Internal error happens"}); + state->finished = true; + + if (state->queue.size() == 0) + state->owner->finish_writes(grpc::Status{grpc::StatusCode::INTERNAL, "Internal error happens"}); } void on_completed() const { - std::lock_guard lock{owner.get().m_write_mutex}; - owner.get().m_finished = true; + std::lock_guard lock{state->mutex}; + if (!state->owner) + return; + + state->finished = true; - if (owner.get().m_write.size() == 0) - owner.get().finish_writes(grpc::Status::OK); + if (state->queue.size() == 0) + state->owner->finish_writes(grpc::Status::OK); } static constexpr bool is_disposed() { return false; } @@ -102,9 +139,7 @@ namespace rppgrpc::details private: rpp::subjects::serialized_publish_subject m_subject{}; - std::mutex m_write_mutex{}; - std::deque m_write{}; - bool m_finished{}; + std::shared_ptr m_state = std::make_shared(); }; template diff --git a/src/tests/rppgrpc/test_async_client.cpp b/src/tests/rppgrpc/test_async_client.cpp index e4d0f1bdc..7bdd48837 100644 --- a/src/tests/rppgrpc/test_async_client.cpp +++ b/src/tests/rppgrpc/test_async_client.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -13,7 +14,15 @@ #include "rpp_trompeloil.hpp" +#include +#include #include +#include +#include +#include +#include +#include +#include namespace { @@ -23,6 +32,135 @@ namespace IMPLEMENT_MOCK3(ClientSide); IMPLEMENT_MOCK2(Bidirectional); }; + + // The write side of the reactors, with a start_write that signals `entered` and waits for `release`. + struct blocking_writer final : rppgrpc::details::base_writer + { + using base_writer::handle_on_done; + + blocking_writer(std::promise& entered, std::shared_future release) + : m_entered{entered} + , m_release{std::move(release)} + { + } + + private: + void start_write(const int&) override + { + m_entered.set_value(); + m_release.wait(); + } + + // The test emits no terminal, so the write side is never finished. + void finish_writes(const grpc::Status&) override { } + + std::promise& m_entered; + std::shared_future m_release; + }; + + // The write side of the reactors, recording what it passes to the stream. + struct recording_writer final : rppgrpc::details::base_writer + { + using base_writer::close_writes; + using base_writer::handle_write_done; + + std::vector writes{}; + int finishes{}; + + private: + void start_write(const int& v) override { writes.push_back(v); } + void finish_writes(const grpc::Status&) override { ++finishes; } + }; + + // Threads that live as long as this object. start() hands them an observer, and each of them emits up to + // `writes` values into it until stop() is called. stop() returns once every thread has left the observer. + class writer_threads + { + public: + explicit writer_threads(size_t count) + { + for (size_t i = 0; i < count; ++i) + m_threads.emplace_back([this] { run(); }); + } + + writer_threads(const writer_threads&) = delete; + writer_threads& operator=(const writer_threads&) = delete; + + ~writer_threads() + { + { + std::lock_guard lock{m_mutex}; + m_exit = true; + } + m_cv.notify_all(); + for (auto& t : m_threads) + t.join(); + } + + void start(rpp::dynamic_observer observer, uint32_t writes) + { + { + std::lock_guard lock{m_mutex}; + m_observer.emplace(std::move(observer)); + m_writes = writes; + m_stop = false; + m_running = m_threads.size(); + ++m_round; + } + m_cv.notify_all(); + } + + void stop() + { + m_stop = true; + std::unique_lock lock{m_mutex}; + m_cv.wait(lock, [this] { return m_running == 0; }); + m_observer.reset(); + } + + private: + void run() + { + size_t round = 0; + while (true) + { + const rpp::dynamic_observer* observer{}; + uint32_t writes{}; + { + std::unique_lock lock{m_mutex}; + m_cv.wait(lock, [&] { return m_exit || m_round != round; }); + if (m_exit) + return; + round = m_round; + observer = &*m_observer; + writes = m_writes; + } + + Request request{}; + for (uint32_t v = 0; v < writes && !m_stop; ++v) + { + request.set_value(v); + observer->on_next(request); + } + + { + std::lock_guard lock{m_mutex}; + --m_running; + } + m_cv.notify_all(); + } + } + + std::mutex m_mutex{}; + std::condition_variable m_cv{}; + std::optional> m_observer{}; + uint32_t m_writes{}; + size_t m_round{}; + size_t m_running{}; + bool m_exit{}; + std::atomic_bool m_stop{}; + std::vector m_threads{}; + }; } // namespace TEST_CASE("async client reactor") @@ -421,3 +559,213 @@ TEST_CASE("async client reactor: call that ends during init()") server->Shutdown(); server->Wait(); } + +TEST_CASE("async client reactor: write that is under way when the call ends") +{ + // t0 is inside start_write. t1 has entered the observer and waits behind t0. Then the write side ends + // and its owner is destroyed, as in OnDone. Ending the write side waits until t0 has left start_write, + // and neither thread may touch the destroyed owner afterwards: a write that does is a use-after-free; + // AddressSanitizer reports it. + std::promise entered{}; + std::promise release{}; + auto writer = std::make_unique(entered, release.get_future().share()); + const auto observer = writer->get_observer(); + + std::thread t0{[&] { observer.on_next(1); }}; + entered.get_future().wait(); + std::thread t1{[&] { observer.on_next(2); }}; + std::this_thread::sleep_for(std::chrono::milliseconds{50}); // t1 waits behind t0 + + std::atomic_bool closed{}; + auto done = std::async(std::launch::async, [&] { + writer->handle_on_done(); + closed = true; + writer.reset(); + }); + std::this_thread::sleep_for(std::chrono::milliseconds{50}); // handle_on_done() runs while t0 is inside start_write + CHECK_FALSE(closed.load()); // and has not returned + release.set_value(); + + done.get(); + CHECK(closed.load()); + t0.join(); + t1.join(); +} + +TEST_CASE("async client reactor: values still queued when the write side closes are dropped") +{ + // A reactor closes its write side once its stream has ended (client_bidi_reactor in OnReadDone(false)). + // The completion of the write that was in flight then starts neither the next queued value nor the + // half-close. + recording_writer writer{}; + const auto observer = writer.get_observer(); + observer.on_next(1); + observer.on_next(2); + observer.on_completed(); + + writer.close_writes(); + writer.handle_write_done(); // OnWriteDone(true) for the value 1 + + CHECK(writer.writes == std::vector{1}); + CHECK(writer.finishes == 0); +} + +TEST_CASE("async client reactor: writes from other threads while the call ends") +{ + // Threads emit into the reactor's observer after init() while the call ends. A write that reaches the + // reactor after OnDone, or its stream after gRPC has destroyed it, is a use-after-free; AddressSanitizer + // reports it. + constexpr int iterations = 200; + constexpr size_t writers = 2; + constexpr uint32_t writes = 1000; + + grpc::ServerBuilder builder{}; + auto mock_service = std::make_unique(); + int server_reads = 0; // the server returns OK after this many reads, or when the client's side ends + ALLOW_CALL(*mock_service, Bidirectional(trompeloeil::_, trompeloeil::_)) + .RETURN(grpc::Status::OK) + .LR_SIDE_EFFECT({ + Request request{}; + for (int i = 0; i < server_reads && _2->Read(&request); ++i) + { + } + }); + builder.RegisterService(mock_service.get()); + + auto server = builder.BuildAndStart(); + const auto stub = TestService::NewStub(server->InProcessChannel({}), {}); + + // The same `writers` threads serve every call of a subcase. + writer_threads threads{writers}; + + // Starts one call, lets the writer threads emit into its observer, ends the call with `end_call` and waits for + // the reactor's terminal, which it emits from OnDone. The context must outlive the call: after a timeout the + // call is cancelled and OnDone is still awaited (a call that never ends is left to the process timeout). + const auto run_call = [&](const auto& end_call) { + grpc::ClientContext ctx{}; + const auto done = std::make_shared>(); + const auto reactor = new rppgrpc::client_bidi_reactor(); + reactor->get_observable().subscribe([](const Response&) { }, + [done](const std::exception_ptr&) { done->set_value(); }, + [done] { done->set_value(); }); + stub->async()->Bidirectional(&ctx, reactor); + auto observer = reactor->get_observer().as_dynamic(); + reactor->init(); + + threads.start(std::move(observer), writes); + end_call(ctx); + auto on_done = done->get_future(); + const bool ended = on_done.wait_for(std::chrono::seconds{5}) == std::future_status::ready; + threads.stop(); + if (!ended) + { + ctx.TryCancel(); + on_done.wait(); + } + return ended; + }; + + SUBCASE("server finishes the call") + { + server_reads = 10; + for (int i = 0; i < iterations; ++i) + REQUIRE(run_call([](grpc::ClientContext&) { })); + } + SUBCASE("client cancels the call") + { + server_reads = std::numeric_limits::max(); + for (int i = 0; i < iterations; ++i) + REQUIRE(run_call([](grpc::ClientContext& ctx) { ctx.TryCancel(); })); + } + + server->Shutdown(); + server->Wait(); +} + +TEST_CASE("async client reactor: bidirectional call reaches OnDone however it ends") +{ + // Each call gets a write from outside the reactions after init(), and must still reach OnDone, which emits + // the observable's terminal and deletes the reactor (LeakSanitizer reports a reactor that is never deleted). + // A context cancelled before init() is covered by "call that ends during init()". + grpc::ServerBuilder builder{}; + auto mock_service = std::make_unique(); + grpc::Status server_status = grpc::Status::OK; + bool server_reads = false; // the server reads until the client's side ends, then returns + ALLOW_CALL(*mock_service, Bidirectional(trompeloeil::_, trompeloeil::_)) + .LR_RETURN(server_status) + .LR_SIDE_EFFECT({ + Request request{}; + while (server_reads && _2->Read(&request)) + { + } + }); + builder.RegisterService(mock_service.get()); + + auto server = builder.BuildAndStart(); + std::shared_ptr channel = server->InProcessChannel({}); + grpc::ClientContext ctx{}; + + enum class terminal + { + none, + completed, + error + }; + + // Starts one call on `channel`, writes once after init(), ends the call with `end_call` and returns the + // terminal the reactor emitted from OnDone. The context must outlive the call: after a timeout the call is + // cancelled and OnDone is still awaited (a call that never ends is left to the process timeout). + const auto run_call = [&](const auto& end_call) { + const auto stub = TestService::NewStub(channel, {}); + const auto result = std::make_shared>(); + const auto reactor = new rppgrpc::client_bidi_reactor(); + reactor->get_observable().subscribe([](const Response&) { }, + [result](const std::exception_ptr&) { result->set_value(terminal::error); }, + [result] { result->set_value(terminal::completed); }); + stub->async()->Bidirectional(&ctx, reactor); + const auto observer = reactor->get_observer(); + reactor->init(); + observer.on_next(Request{}); + end_call(); + auto f = result->get_future(); + if (f.wait_for(std::chrono::seconds{5}) == std::future_status::ready) + return f.get(); + ctx.TryCancel(); + f.wait(); + return terminal::none; + }; + + SUBCASE("server finishes with OK") + { + CHECK(run_call([] { }) == terminal::completed); + } + SUBCASE("server finishes with an error status") + { + server_status = grpc::Status{grpc::StatusCode::INTERNAL, "server error"}; + CHECK(run_call([] { }) == terminal::error); + } + SUBCASE("client cancels") + { + server_reads = true; + CHECK(run_call([&] { ctx.TryCancel(); }) == terminal::error); + } + SUBCASE("deadline expires") + { + server_reads = true; + ctx.set_deadline(std::chrono::system_clock::now() + std::chrono::milliseconds{100}); + CHECK(run_call([] { }) == terminal::error); + } + SUBCASE("server shuts down during the call") + { + server_reads = true; + CHECK(run_call([&] { server->Shutdown(std::chrono::system_clock::now()); }) == terminal::error); + } + SUBCASE("connection refused, before any read succeeds") + { + channel = grpc::CreateChannel("127.0.0.1:1", grpc::InsecureChannelCredentials()); + CHECK(run_call([] { }) == terminal::error); + } + + server->Shutdown(); + server->Wait(); +}