Skip to content

Commit cc36777

Browse files
committed
proxy: add local connection limit to ListenConnections
Add an optional max_connections parameter to ListenConnections() so a listener can stop accepting new connections after reaching a local connection cap and resume accepting after an existing connection disconnects. Implement the limit with listener-local state tracking the listening socket, maximum number of active connections, and whether an async accept() has already been posted. This keeps the limit scoped to the individual listener instead of introducing global EventLoop state. Extend the dedicated listener test coverage to verify that with max_connections=1 the first client is accepted normally, a second client is not accepted while the first remains connected, and the second client is accepted after the first disconnects.
1 parent c1a22c4 commit cc36777

4 files changed

Lines changed: 154 additions & 20 deletions

File tree

doc/usage.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ _libmultiprocess_ is a library and code generator that allows calling C++ class
1010

1111
The `*.capnp` data definition files are consumed by the _libmultiprocess_ code generator and each `X.capnp` file generates `X.capnp.c++`, `X.capnp.h`, `X.capnp.proxy-client.c++`, `X.capnp.proxy-server.c++`, `X.capnp.proxy-types.c++`, `X.capnp.proxy-types.h`, and `X.capnp.proxy.h` output files. The generated files include `mp::ProxyClient<Interface>` and `mp::ProxyServer<Interface>` class specializations for all the interfaces in the `.capnp` files. These allow methods on C++ objects in one process to be called from other processes over IPC sockets.
1212

13-
The `ProxyServer` objects help translate IPC requests from a socket to method calls on a local object. The `ProxyServer` objects are just used internally by the `mp::ServeStream(loop, socket, wrapped_object)` and `mp::ListenConnections(loop, socket, wrapped_object)` functions, and aren't exposed externally. The `ProxyClient` classes are exposed, and returned from the `mp::ConnectStream(loop, socket)` function and meant to be used directly. The classes implement methods described in `.capnp` definitions, and whenever any method is called, a request with the method arguments is sent over the associated IPC connection, and the corresponding `wrapped_object` method on the other end of the connection is called, with the `ProxyClient` method blocking until it returns and forwarding back any return value to the `ProxyClient` method caller.
13+
The `ProxyServer` objects help translate IPC requests from a socket to method calls on a local object. The `ProxyServer` objects are just used internally by the `mp::ServeStream(loop, socket, wrapped_object)` and `mp::ListenConnections(loop, socket, wrapped_object[, max_connections])` functions, and aren't exposed externally. The `ProxyClient` classes are exposed, and returned from the `mp::ConnectStream(loop, socket)` function and meant to be used directly. The classes implement methods described in `.capnp` definitions, and whenever any method is called, a request with the method arguments is sent over the associated IPC connection, and the corresponding `wrapped_object` method on the other end of the connection is called, with the `ProxyClient` method blocking until it returns and forwarding back any return value to the `ProxyClient` method caller.
1414

1515
## Example
1616

doc/versions.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ include.
99

1010
## v12
1111
- Current unstable version.
12+
- Adds an optional per-listener `max_connections` parameter to `ListenConnections()`
13+
so servers can stop accepting new connections when a local connection cap is reached,
14+
and resume accepting after existing connections disconnect.
1215

1316
## [v11.0](https://github.com/bitcoin-core/libmultiprocess/commits/v11.0)
1417
- Tolerates unexpected exceptions in event loop `post()` callbacks.

include/mp/proxy-io.h

Lines changed: 66 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313
#include <capnp/rpc-twoparty.h>
1414

1515
#include <assert.h>
16+
#include <algorithm>
1617
#include <condition_variable>
18+
#include <cstdlib>
1719
#include <functional>
1820
#include <kj/function.h>
1921
#include <map>
@@ -834,8 +836,8 @@ std::unique_ptr<ProxyClient<InitInterface>> ConnectStream(EventLoop& loop, int f
834836
//! handles requests from the stream by calling the init object. Embed the
835837
//! ProxyServer in a Connection object that is stored and erased if
836838
//! disconnected. This should be called from the event loop thread.
837-
template <typename InitInterface, typename InitImpl>
838-
void _Serve(EventLoop& loop, kj::Own<kj::AsyncIoStream>&& stream, InitImpl& init)
839+
template <typename InitInterface, typename InitImpl, typename OnDisconnect>
840+
void _Serve(EventLoop& loop, kj::Own<kj::AsyncIoStream>&& stream, InitImpl& init, OnDisconnect&& on_disconnect)
839841
{
840842
loop.m_incoming_connections.emplace_front(loop, kj::mv(stream), [&](Connection& connection) {
841843
// Disable deleter so proxy server object doesn't attempt to delete the
@@ -846,23 +848,69 @@ void _Serve(EventLoop& loop, kj::Own<kj::AsyncIoStream>&& stream, InitImpl& init
846848
auto it = loop.m_incoming_connections.begin();
847849
MP_LOG(loop, Log::Info) << "IPC server: socket connected.";
848850
if (loop.testing_hook_connected) loop.testing_hook_connected();
849-
it->onDisconnect([&loop, it] {
851+
it->onDisconnect([&loop, it, on_disconnect = std::forward<OnDisconnect>(on_disconnect)]() mutable {
850852
MP_LOG(loop, Log::Info) << "IPC server: socket disconnected.";
851853
loop.m_incoming_connections.erase(it);
854+
on_disconnect();
852855
});
853856
}
854857

855-
//! Given connection receiver and an init object, handle incoming connections by
856-
//! calling _Serve, to create ProxyServer objects and forward requests to the
857-
//! init object.
858+
struct ListenState
859+
{
860+
explicit ListenState(kj::Own<kj::ConnectionReceiver>&& listener_, std::optional<size_t> max_connections_)
861+
: listener(kj::mv(listener_)), max_connections(max_connections_) {}
862+
863+
kj::Own<kj::ConnectionReceiver> listener;
864+
std::optional<size_t> max_connections;
865+
size_t active_connections{0};
866+
};
867+
858868
template <typename InitInterface, typename InitImpl>
859-
void _Listen(EventLoop& loop, kj::Own<kj::ConnectionReceiver>&& listener, InitImpl& init)
869+
void _Listen(EventLoop& loop, InitImpl& init, const std::shared_ptr<ListenState>& state);
870+
871+
inline bool _ListenAtCapacity(const ListenState& state)
860872
{
861-
auto* ptr = listener.get();
873+
return state.max_connections && state.active_connections >= *state.max_connections;
874+
}
875+
876+
//! Return an EventLoopRef if this is a capped listener, to keep the event loop
877+
//! alive while waiting for connections.
878+
//!
879+
//! For uncapped listeners, we do not hold an EventLoopRef because the event
880+
//! loop should automatically exit when the last active client disconnects (when
881+
//! m_num_clients drops to 0).
882+
//!
883+
//! For capped listeners, we stop calling ptr->accept() when at capacity. Since
884+
//! no accept task remains pending in the task set, we must hold an EventLoopRef
885+
//! while listening to keep the event loop alive until the limit is reached.
886+
inline std::unique_ptr<EventLoopRef> _MakeCappedListenerRef(EventLoop& loop, const ListenState& state)
887+
{
888+
return state.max_connections && *state.max_connections > 0 ? std::make_unique<EventLoopRef>(loop) : nullptr;
889+
}
890+
891+
//! Given init object and a state object containing a connection receiver, handle
892+
//! incoming connections by calling _Serve, to create ProxyServer objects and
893+
//! forward requests to the init object.
894+
template <typename InitInterface, typename InitImpl>
895+
void _Listen(EventLoop& loop, InitImpl& init, const std::shared_ptr<ListenState>& state)
896+
{
897+
if (_ListenAtCapacity(*state)) return;
898+
899+
auto* ptr = state->listener.get();
900+
// Bind the EventLoopRef lifetime to the pending accept task. If the listener
901+
// reaches capacity, _Listen returns early, destroying the accept_ref and
902+
// letting the event loop client count decrement.
903+
auto accept_ref{_MakeCappedListenerRef(loop, *state)};
862904
loop.m_task_set->add(ptr->accept().then(
863-
[&loop, &init, listener = kj::mv(listener)](kj::Own<kj::AsyncIoStream>&& stream) mutable {
864-
_Serve<InitInterface>(loop, kj::mv(stream), init);
865-
_Listen<InitInterface>(loop, kj::mv(listener), init);
905+
[&loop, &init, state, accept_ref = std::move(accept_ref)](kj::Own<kj::AsyncIoStream>&& stream) mutable {
906+
++state->active_connections;
907+
_Serve<InitInterface>(loop, kj::mv(stream), init, [&loop, &init, state] {
908+
const bool resume_accept{_ListenAtCapacity(*state)};
909+
assert(state->active_connections > 0);
910+
--state->active_connections;
911+
if (resume_accept) _Listen<InitInterface>(loop, init, state);
912+
});
913+
_Listen<InitInterface>(loop, init, state);
866914
}));
867915
}
868916

@@ -872,18 +920,21 @@ template <typename InitInterface, typename InitImpl>
872920
void ServeStream(EventLoop& loop, int fd, InitImpl& init)
873921
{
874922
_Serve<InitInterface>(
875-
loop, loop.m_io_context.lowLevelProvider->wrapSocketFd(fd, kj::LowLevelAsyncIoProvider::TAKE_OWNERSHIP), init);
923+
loop,
924+
loop.m_io_context.lowLevelProvider->wrapSocketFd(fd, kj::LowLevelAsyncIoProvider::TAKE_OWNERSHIP),
925+
init,
926+
[] {});
876927
}
877928

878929
//! Given listening socket file descriptor and an init object, handle incoming
879930
//! connections and requests by calling methods on the Init object.
880931
template <typename InitInterface, typename InitImpl>
881-
void ListenConnections(EventLoop& loop, int fd, InitImpl& init)
932+
void ListenConnections(EventLoop& loop, int fd, InitImpl& init, std::optional<size_t> max_connections = std::nullopt)
882933
{
883934
loop.sync([&]() {
884-
_Listen<InitInterface>(loop,
935+
_Listen<InitInterface>(loop, init, std::make_shared<ListenState>(
885936
loop.m_io_context.lowLevelProvider->wrapListenSocketFd(fd, kj::LowLevelAsyncIoProvider::TAKE_OWNERSHIP),
886-
init);
937+
max_connections));
887938
});
888939
}
889940

test/mp/test/listen_tests.cpp

Lines changed: 84 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#include <memory>
2020
#include <mp/proxy-io.h>
2121
#include <mutex>
22+
#include <optional>
2223
#include <ratio> // IWYU pragma: keep
2324
#include <stdexcept>
2425
#include <string>
@@ -119,19 +120,28 @@ class ClientSetup
119120
class ListenSetup
120121
{
121122
public:
122-
ListenSetup()
123-
: thread([this] {
123+
explicit ListenSetup(std::optional<size_t> max_connections = std::nullopt)
124+
: capped_listener(max_connections.has_value()), thread([this, max_connections] {
124125
EventLoop loop("mptest-server", [this](mp::LogMessage log) {
125126
KJ_LOG(INFO, log.level, log.message);
126127
if (log.level == mp::Log::Raise) throw std::runtime_error(log.message);
128+
if (log.message.find("IPC server: socket disconnected.") != std::string::npos) {
129+
std::lock_guard<std::mutex> lock(counter_mutex);
130+
++disconnected_count;
131+
counter_cv.notify_all();
132+
}
127133
});
128134
loop.testing_hook_connected = [&] {
129135
std::lock_guard<std::mutex> lock(counter_mutex);
130136
++connected_count;
131137
counter_cv.notify_all();
132138
};
139+
{
140+
std::lock_guard<std::mutex> lock(counter_mutex);
141+
event_loop = &loop;
142+
}
133143
FooImplementation foo;
134-
ListenConnections<messages::FooInterface>(loop, listener.release(), foo);
144+
ListenConnections<messages::FooInterface>(loop, listener.release(), foo, max_connections);
135145
ready_promise.set_value();
136146
loop.loop();
137147
})
@@ -141,9 +151,23 @@ class ListenSetup
141151

142152
~ListenSetup()
143153
{
154+
if (capped_listener) {
155+
EventLoop* loop;
156+
{
157+
std::lock_guard<std::mutex> lock(counter_mutex);
158+
loop = event_loop;
159+
}
160+
if (loop) loop->sync([&] { loop->m_task_set.reset(); });
161+
}
144162
thread.join();
145163
}
146164

165+
size_t ConnectedCount()
166+
{
167+
std::lock_guard<std::mutex> lock(counter_mutex);
168+
return connected_count;
169+
}
170+
147171
void WaitForConnectedCount(size_t expected_count)
148172
{
149173
std::unique_lock<std::mutex> lock(counter_mutex);
@@ -154,15 +178,27 @@ class ListenSetup
154178
KJ_REQUIRE(matched);
155179
}
156180

181+
void WaitForDisconnectedCount(size_t expected_count)
182+
{
183+
std::unique_lock<std::mutex> lock(counter_mutex);
184+
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
185+
const bool matched = counter_cv.wait_until(lock, deadline, [&] {
186+
return disconnected_count >= expected_count;
187+
});
188+
KJ_REQUIRE(matched);
189+
}
190+
157191
UnixListener listener;
158192
std::promise<void> ready_promise;
193+
bool capped_listener{false};
159194
std::mutex counter_mutex;
160195
std::condition_variable counter_cv;
196+
EventLoop* event_loop{nullptr};
161197
size_t connected_count{0};
198+
size_t disconnected_count{0};
162199
//! Thread variable should be after other struct members so the thread does
163200
//! not start until the other members are initialized.
164201
std::thread thread;
165-
166202
};
167203

168204
KJ_TEST("ListenConnections accepts incoming connections")
@@ -174,6 +210,50 @@ KJ_TEST("ListenConnections accepts incoming connections")
174210
KJ_EXPECT(client->client->add(1, 2) == 3);
175211
}
176212

213+
KJ_TEST("ListenConnections enforces a local connection limit")
214+
{
215+
ListenSetup setup(/*max_connections=*/1);
216+
217+
auto client1 = std::make_unique<ClientSetup>(setup.listener.Connect());
218+
setup.WaitForConnectedCount(1);
219+
KJ_EXPECT(client1->client->add(1, 2) == 3);
220+
221+
auto client2 = std::make_unique<ClientSetup>(setup.listener.Connect());
222+
std::this_thread::sleep_for(std::chrono::milliseconds(100));
223+
KJ_EXPECT(setup.ConnectedCount() == 1);
224+
225+
client1.reset();
226+
setup.WaitForDisconnectedCount(1);
227+
setup.WaitForConnectedCount(2);
228+
229+
KJ_EXPECT(client2->client->add(2, 3) == 5);
230+
231+
client2.reset();
232+
setup.WaitForDisconnectedCount(2);
233+
std::this_thread::sleep_for(std::chrono::milliseconds(100));
234+
235+
auto client3 = std::make_unique<ClientSetup>(setup.listener.Connect());
236+
setup.WaitForConnectedCount(3);
237+
KJ_EXPECT(client3->client->add(3, 4) == 7);
238+
}
239+
240+
KJ_TEST("ListenConnections keeps capped listeners alive before reaching the limit")
241+
{
242+
ListenSetup setup(/*max_connections=*/2);
243+
244+
auto client1 = std::make_unique<ClientSetup>(setup.listener.Connect());
245+
setup.WaitForConnectedCount(1);
246+
KJ_EXPECT(client1->client->add(1, 2) == 3);
247+
248+
client1.reset();
249+
setup.WaitForDisconnectedCount(1);
250+
std::this_thread::sleep_for(std::chrono::milliseconds(100));
251+
252+
auto client2 = std::make_unique<ClientSetup>(setup.listener.Connect());
253+
setup.WaitForConnectedCount(2);
254+
KJ_EXPECT(client2->client->add(2, 3) == 5);
255+
}
256+
177257
} // namespace
178258
} // namespace test
179259
} // namespace mp

0 commit comments

Comments
 (0)