假设我有一个这样的流 API:
interface MyInterface {
addListener @0 (listener: Listener) -> (registration: RegisteredListener);
interface Listener {
update @0 () -> stream;
}
interface RegisteredListener {
}
}
我遇到了一个挑战,即服务器实现的析构函数MyInterface
在最后一个注册接口发布之前运行。如何正确地将关系传达给 cap'n'proto RPC,这样即使客户端MyInterface::Client
在 或者,我是否以某种基本方式滥用 API?RegisteredListener::Client
MyInterface::Server
RegisteredListener::Server
C++ 代码大致如下所示。服务器:
class MyInterfaceImpl : public MyInterface {
class Registered final : public MyInterface::RegisteredListener::Server {
public:
Registered(MyInterfaceImpl* parent, uint64_t registrationId) : parent_(parent), id_(registrationId) {}
~Registered() {
parent->unregister(id_);
}
private:
MyInterfaceImpl *parent_;
uint64_t id_;
};
public:
kj::Promise<void> addListener(MyInterface::AddListenerContext context) {
auto registrationId = ++registrationId_;
clients_.emplace_back(context.getParams().getListener());
registrations_.emplace_back(registrationId);
context.getResult().setRegistration(kj::heap<Registered>(this, registrationId));
return kj::READY_NOW;
}
void unregister(uint64_t registrationId) {
auto found = std::find(registrations_.begin(), registrations_.end(), registrationId);
clients_.erase(clients_.begin() + (found - registrations_.begin()));
}
private:
std::vector<MyInterface::Listener::Client> clients_;
std::vector<uint64_t> registrations_;
uint64_t registrationId_ = 0;
};
客户端代码如下所示:
capnp::EzRpcClient client("localhost:5923");
MyInterface::Client intf = client.getMain<MyInterface>();
auto& waitScope = client.getWaitScope();
auto listenerRequest = intf.addListenerRequest();
auto listenerPromise = listenerRequest.send();
listenerPromise.wait(waitScope);
{
auto listenerRequest2 = intf.addListenerRequest();
auto listenerPromise2 = listenerRequest2.send();
listenerPromise2.wait(waitScope);
}
由于这都是单线程的,因此很容易发现 use-after-free。我将调试语句放入~MyInterfaceImpl
并且~RegisteredListener
第二个侦听器在~MyInterfaceImpl
. 我知道我的添加侦听器请求没有实际的客户端对象,但我希望这实际上不是一个重要的细节。