Skip to content

Commit 57e7070

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 8c47a3a commit 57e7070

6 files changed

Lines changed: 58 additions & 18 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: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,14 @@ Library versions are tracked with simple
77
Versioning policy is described in the [version.h](../include/mp/version.h)
88
include.
99

10-
## v10
10+
## v11
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.
15+
16+
## [v10.0](https://github.com/bitcoin-core/libmultiprocess/commits/v10.0)
17+
- Prior unstable version before local listener connection-limit support.
1218

1319
## [v9.0](https://github.com/bitcoin-core/libmultiprocess/commits/v9.0)
1420
- Fixes race conditions where worker thread could be used after destruction, where getParams() could be called after request cancel, and where m_on_cancel could be called after request finishes.

include/mp/proxy-io.h

Lines changed: 43 additions & 12 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>
@@ -820,8 +822,8 @@ std::unique_ptr<ProxyClient<InitInterface>> ConnectStream(EventLoop& loop, int f
820822
//! handles requests from the stream by calling the init object. Embed the
821823
//! ProxyServer in a Connection object that is stored and erased if
822824
//! disconnected. This should be called from the event loop thread.
823-
template <typename InitInterface, typename InitImpl>
824-
void _Serve(EventLoop& loop, kj::Own<kj::AsyncIoStream>&& stream, InitImpl& init)
825+
template <typename InitInterface, typename InitImpl, typename OnDisconnect>
826+
void _Serve(EventLoop& loop, kj::Own<kj::AsyncIoStream>&& stream, InitImpl& init, OnDisconnect&& on_disconnect)
825827
{
826828
loop.m_incoming_connections.emplace_front(loop, kj::mv(stream), [&](Connection& connection) {
827829
// Disable deleter so proxy server object doesn't attempt to delete the
@@ -831,23 +833,49 @@ void _Serve(EventLoop& loop, kj::Own<kj::AsyncIoStream>&& stream, InitImpl& init
831833
});
832834
auto it = loop.m_incoming_connections.begin();
833835
MP_LOG(loop, Log::Info) << "IPC server: socket connected.";
834-
it->onDisconnect([&loop, it] {
836+
it->onDisconnect([&loop, it, on_disconnect = std::forward<OnDisconnect>(on_disconnect)]() mutable {
835837
MP_LOG(loop, Log::Info) << "IPC server: socket disconnected.";
836838
loop.m_incoming_connections.erase(it);
839+
on_disconnect();
837840
});
838841
}
839842

840843
//! Given connection receiver and an init object, handle incoming connections by
841844
//! calling _Serve, to create ProxyServer objects and forward requests to the
842845
//! init object.
846+
struct ListenState
847+
{
848+
explicit ListenState(kj::Own<kj::ConnectionReceiver>&& listener_, std::optional<size_t> max_connections_)
849+
: listener(kj::mv(listener_)), max_connections(max_connections_) {}
850+
851+
kj::Own<kj::ConnectionReceiver> listener;
852+
std::optional<size_t> max_connections;
853+
size_t active_connections{0};
854+
//! Tracks whether accept() has already been posted. This is needed because
855+
//! active_connections only counts accepted connections, so without a
856+
//! separate flag, nested _Listen() calls could queue multiple pending
857+
//! accepts before active_connections increases.
858+
bool accept_pending{false};
859+
};
860+
843861
template <typename InitInterface, typename InitImpl>
844-
void _Listen(EventLoop& loop, kj::Own<kj::ConnectionReceiver>&& listener, InitImpl& init)
862+
void _Listen(EventLoop& loop, InitImpl& init, const std::shared_ptr<ListenState>& state)
845863
{
846-
auto* ptr = listener.get();
864+
if (state->accept_pending) return;
865+
if (state->max_connections && state->active_connections >= *state->max_connections) return;
866+
867+
state->accept_pending = true;
868+
auto* ptr = state->listener.get();
847869
loop.m_task_set->add(ptr->accept().then(
848-
[&loop, &init, listener = kj::mv(listener)](kj::Own<kj::AsyncIoStream>&& stream) mutable {
849-
_Serve<InitInterface>(loop, kj::mv(stream), init);
850-
_Listen<InitInterface>(loop, kj::mv(listener), init);
870+
[&loop, &init, state](kj::Own<kj::AsyncIoStream>&& stream) mutable {
871+
state->accept_pending = false;
872+
++state->active_connections;
873+
_Serve<InitInterface>(loop, kj::mv(stream), init, [&loop, &init, state] {
874+
assert(state->active_connections > 0);
875+
--state->active_connections;
876+
_Listen<InitInterface>(loop, init, state);
877+
});
878+
_Listen<InitInterface>(loop, init, state);
851879
}));
852880
}
853881

@@ -857,18 +885,21 @@ template <typename InitInterface, typename InitImpl>
857885
void ServeStream(EventLoop& loop, int fd, InitImpl& init)
858886
{
859887
_Serve<InitInterface>(
860-
loop, loop.m_io_context.lowLevelProvider->wrapSocketFd(fd, kj::LowLevelAsyncIoProvider::TAKE_OWNERSHIP), init);
888+
loop,
889+
loop.m_io_context.lowLevelProvider->wrapSocketFd(fd, kj::LowLevelAsyncIoProvider::TAKE_OWNERSHIP),
890+
init,
891+
[] {});
861892
}
862893

863894
//! Given listening socket file descriptor and an init object, handle incoming
864895
//! connections and requests by calling methods on the Init object.
865896
template <typename InitInterface, typename InitImpl>
866-
void ListenConnections(EventLoop& loop, int fd, InitImpl& init)
897+
void ListenConnections(EventLoop& loop, int fd, InitImpl& init, std::optional<size_t> max_connections = std::nullopt)
867898
{
868899
loop.sync([&]() {
869-
_Listen<InitInterface>(loop,
900+
_Listen<InitInterface>(loop, init, std::make_shared<ListenState>(
870901
loop.m_io_context.lowLevelProvider->wrapListenSocketFd(fd, kj::LowLevelAsyncIoProvider::TAKE_OWNERSHIP),
871-
init);
902+
max_connections));
872903
});
873904
}
874905

include/mp/version.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
//! pointing at the prior merge commit. The /doc/versions.md file should also be
2525
//! updated, noting any significant or incompatible changes made since the
2626
//! previous version.
27-
#define MP_MAJOR_VERSION 10
27+
#define MP_MAJOR_VERSION 11
2828

2929
//! Minor version number. Should be incremented in stable branches after
3030
//! backporting changes. The /doc/versions.md file should also be updated to

test/mp/test/listen_tests.cpp

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,20 @@
55
#include <mp/test/foo.capnp.h>
66
#include <mp/test/foo.capnp.proxy.h>
77

8-
#include <capnp/rpc.h>
98
#include <chrono>
109
#include <condition_variable>
1110
#include <cstdlib>
1211
#include <cstring>
1312
#include <future>
13+
#include <kj/async.h>
14+
#include <kj/common.h>
15+
#include <kj/debug.h>
16+
#include <kj/memory.h>
1417
#include <kj/test.h>
1518
#include <memory>
1619
#include <mp/proxy-io.h>
1720
#include <mutex>
21+
#include <optional>
1822
#include <ratio> // IWYU pragma: keep
1923
#include <stdexcept>
2024
#include <string>
@@ -23,8 +27,6 @@
2327
#include <thread>
2428
#include <unistd.h>
2529

26-
#include "foo.h"
27-
2830
namespace mp {
2931
namespace test {
3032
namespace {

test/mp/test/test.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <capnp/capability.h>
1010
#include <capnp/rpc.h>
1111
#include <cassert>
12+
#include <chrono>
1213
#include <condition_variable>
1314
#include <cstdint>
1415
#include <functional>

0 commit comments

Comments
 (0)