brpc icon indicating copy to clipboard operation
brpc copied to clipboard

server支持OnNewConnection(...), OnClosedConnection(...)回调

Open antkiller996 opened this issue 2 years ago • 11 comments

Is your feature request related to a problem? (你需要的功能是否与某个问题有关?) 我们在用户层面实现了基于Connection : Session = 1: 1的功能,需要在connection建立和断开时对session进行保存和删除。

Describe the solution you'd like (描述你期望的解决方法) 希望ServerOption提供OnNewConnection, OnClosedConnection的回调, 以便在用户代码中管理连接信息。

antkiller996 avatar Oct 24 '23 06:10 antkiller996

可以考虑用 streaming rpc 吗?一个stream对应一个session

wwbmmm avatar Oct 25 '23 06:10 wwbmmm

目前来说不太行,不一定要streaming的。

ghost avatar Oct 25 '23 08:10 ghost

如果说没有短期支持计划,那我来提PR支持下~

ghost avatar Oct 26 '23 08:10 ghost

OnClosedConnection关注的是Socket Failed的时机还是close(fd)的时机?

chenBright avatar Oct 26 '23 09:10 chenBright

client和server close都需要关注到。EPOLLHUP 可以解决这个事么

ghost avatar Oct 26 '23 12:10 ghost

client端的连接也需要回调?

chenBright avatar Oct 27 '23 01:10 chenBright

client端不需要。如果client与server端发起主动关闭链接,server端这边要回调;server端与client端主动发起的,也要回调;另外SocketFailed和close(fd)这两个时机其实无所谓,最好是能保证exactly once的语义。当OnCloseConnection回调执行完后,保证server端fd不能读/写即可

ghost avatar Oct 27 '23 01:10 ghost

ServerOptions.auth 这个倒是可以在每次新建连接的时候被调用,这就可以实现OnNewConnection的回调。而且可以返回一个AuthContext,这个AuthContext可以通过后续的请求的Controller中拿到。这个AuthContext会存在Socket对象中,当Socket回收(即连接断开)时,AuthContext会被释放。如果把AuthContext的析构函数改为虚函数,允许子类自定义析构的逻辑,是不是就可以实现OnClosedConnection的回调了?

https://github.com/apache/brpc/blob/master/src/brpc/authenticator.h#L30

wwbmmm avatar Oct 27 '23 03:10 wwbmmm

如果只需要在Socket Failed的时候回调的话,使用Socket::NotifyOnFailed可以实现OnClosedConnection的回调。 https://github.com/apache/brpc/blob/761b399e50ba95dddec363662a1bf0b42254f18f/src/brpc/socket.cpp#L1044-L1058

可以参考Controller::NotifyOnCancel的用法: https://github.com/apache/brpc/blob/761b399e50ba95dddec363662a1bf0b42254f18f/src/brpc/controller.cpp#L539-L561

chenBright avatar Oct 27 '23 03:10 chenBright

ServerOptions.auth 这个倒是可以在每次新建连接的时候被调用,这就可以实现OnNewConnection的回调。而且可以返回一个AuthContext,这个AuthContext可以通过后续的请求的Controller中拿到。这个AuthContext会存在Socket对象中,当Socket回收(即连接断开)时,AuthContext会被释放。如果把AuthContext的析构函数改为虚函数,允许子类自定义析构的逻辑,是不是就可以实现OnClosedConnection的回调了?

https://github.com/apache/brpc/blob/master/src/brpc/authenticator.h#L30

~~这个方案貌似可行,但是还是需要对brpc进行改造:~~ ~~1. AuthContext 对继承开放,析构函数需要virtual~~ ~~2. 现在AuthContext是在Socket::mutable_auth_context中创建的,没有在server层暴露接口让其创建用户的类型。~~

我们可以在AuthContext新增属性:on_destroy_context(AuthContext* ctx), 用户通过out_ctx->set_destroy_context注册回调。

在Socket::OnRecycle中delete _auth_context 之前,调用其on_destroy_context回调函数。

ghost avatar Oct 27 '23 06:10 ghost

我们可以在AuthContext新增属性:on_destroy_context(AuthContext* ctx), 用户通过out_ctx->set_destroy_context注册回调。

在Socket::OnRecycle中delete _auth_context 之前,调用其on_destroy_context回调函数。

看起来可行。可以直接在AuthContext的析构函数里调用 on_destroy_context

wwbmmm avatar Oct 27 '23 11:10 wwbmmm