http_plugin
http_plugin
用來接受客戶端cleos
發(fā)過來的請求览效,eos
使用多插件機制來拆分業(yè)務(wù)邏輯为严,各plugin 想要相應(yīng)來自客戶端的請求,就需要在各自模塊的api_plugin
中向 http_plugin
注冊 url_handler
.
http_plugin
中有個map<string,url_handler> url_handlers;
變量垛膝,保管著其他插件注冊過來的接口以及回調(diào)鳍侣。
http_plugin
中的 add_api
方法 以及 add_handler
:
void add_api(const api_description& api) {
for (const auto& call : api)
add_handler(call.first, call.second);
}
void http_plugin::add_handler(const string& url, const url_handler& handler) {
ilog( "add api url: ${c}", ("c",url) );
app().get_io_service().post([=](){
my->url_handlers.insert(std::make_pair(url,handler));
});
}
http_plugin
中處理http
請求的函數(shù), 通過handler_itr->second(...)
來調(diào)用具體邏輯。
template<class T>
void handle_http_request(typename websocketpp::server<detail::asio_with_stub_log<T>>::connection_ptr con) {
try {
......
con->append_header( "Content-type", "application/json" );
auto body = con->get_request_body();
auto resource = con->get_uri()->get_resource();
auto handler_itr = url_handlers.find( resource );
if( handler_itr != url_handlers.end()) {
con->defer_http_response();
// 調(diào)用其他模塊注冊過來的回調(diào)
handler_itr->second( resource, body, [con]( auto code, auto&& body ) {
con->set_body( std::move( body ));
con->set_status( websocketpp::http::status_code::value( code ));
con->send_http_response();
} );
} else {
wlog( "404 - not found: ${ep}", ("ep", resource));
error_results results{websocketpp::http::status_code::not_found,
"Not Found", error_results::error_info(fc::exception( FC_LOG_MESSAGE( error, "Unknown Endpoint" )), verbose_http_errors )};
con->set_body( fc::json::to_string( results ));
con->set_status( websocketpp::http::status_code::not_found );
}
} catch( ... ) {
handle_exception<T>( con );
}
}
chain_plugin
要知道chain_plugin
對外提供什么功能吼拥,首先看 chain_api_plugin
chain_api_plugin
中主要分了兩個 api
: read_only
和 read_write
兩個類處理倚聚。
void chain_api_plugin::plugin_startup() {
ilog( "starting chain_api_plugin" );
my.reset(new chain_api_plugin_impl(app().get_plugin<chain_plugin>().chain()));
auto ro_api = app().get_plugin<chain_plugin>().get_read_only_api();
auto rw_api = app().get_plugin<chain_plugin>().get_read_write_api();
app().get_plugin<http_plugin>().add_api({
CHAIN_RO_CALL(get_info, 200l),
CHAIN_RO_CALL(get_block, 200),
CHAIN_RO_CALL(get_block_header_state, 200),
CHAIN_RO_CALL(get_account, 200),
CHAIN_RO_CALL(get_code, 200),
CHAIN_RO_CALL(get_abi, 200),
CHAIN_RO_CALL(get_raw_code_and_abi, 200),
CHAIN_RO_CALL(get_table_rows, 200),
CHAIN_RO_CALL(get_currency_balance, 200),
CHAIN_RO_CALL(get_currency_stats, 200),
CHAIN_RO_CALL(get_producers, 200),
CHAIN_RO_CALL(get_producer_schedule, 200),
CHAIN_RO_CALL(get_scheduled_transactions, 200),
CHAIN_RO_CALL(abi_json_to_bin, 200),
CHAIN_RO_CALL(abi_bin_to_json, 200),
CHAIN_RO_CALL(get_required_keys, 200),
CHAIN_RW_CALL_ASYNC(push_block, chain_apis::read_write::push_block_results, 202),
CHAIN_RW_CALL_ASYNC(push_transaction, chain_apis::read_write::push_transaction_results, 202),
CHAIN_RW_CALL_ASYNC(push_transactions, chain_apis::read_write::push_transactions_results, 202)
});
}
可以看到,plugin_startup
函數(shù)向 http_plugin
插件添加了若干個接口凿可,
CHAIN_RW_CALL_ASYNC
定義如下:
#define CHAIN_RW_CALL_ASYNC(call_name, call_result, http_response_code) CALL_ASYNC(chain, rw_api, chain_apis::read_write, call_name, call_result, http_response_code)
#define CALL_ASYNC(api_name, api_handle, api_namespace, call_name, call_result, http_response_code) \
{std::string("/v1/" #api_name "/" #call_name), \
[this, api_handle](string, string body, url_response_callback cb) mutable { \
if (body.empty()) body = "{}"; \
api_handle.call_name(fc::json::from_string(body).as<api_namespace::call_name ## _params>(),\
[cb, body](const fc::static_variant<fc::exception_ptr, call_result>& result){\
if (result.contains<fc::exception_ptr>()) {\
try {\
result.get<fc::exception_ptr>()->dynamic_rethrow_exception();\
} catch (...) {\
http_plugin::handle_exception(#api_name, #call_name, body, cb);\
}\
} else {\
cb(http_response_code, result.visit(async_result_visitor()));\
}\
});\
}\
}
最終定義的是一個map
, key
是注冊的url
地址惑折, value
是回調(diào) lambada
例如 CHAIN_RW_CALL_ASYNC(push_block, chain_apis::read_write::push_block_results, 202)
, 就是向 http_plugin
注冊了 /v1/chain/push_block
接口,該接口被調(diào)用后矿酵,會轉(zhuǎn)向 chain_plugin
中read_write
類的 push_block
方法唬复,
看看 push_block 方法的定義:
void read_write::push_block(const read_write::push_block_params& params, next_function<read_write::push_block_results> next) {
try {
app().get_method<incoming::methods::block_sync>()(std::make_shared<signed_block>(params));
// 直接向客戶端返回了空的結(jié)果
next(read_write::push_block_results{});
} catch ( boost::interprocess::bad_alloc& ) {
raise(SIGUSR1);
} CATCH_AND_CALL(next);
}
重點在于這行代碼
app().get_method<incoming::methods::block_sync>()(std::make_shared<signed_block>(params));
先看前面一半: app().get_method<incoming::methods::block_sync>()
調(diào)用application
的 get_method
方法,
template<typename MethodDecl>
auto get_method() -> std::enable_if_t<is_method_decl<MethodDecl>::value, typename MethodDecl::method_type&>
{
using method_type = typename MethodDecl::method_type;
auto key = std::type_index(typeid(MethodDecl));
auto itr = methods.find(key);
if(itr != methods.end()) {
return *method_type::get_method(itr->second);
} else {
methods.emplace(std::make_pair(key, method_type::make_unique()));
return *method_type::get_method(methods.at(key));
}
}
auto key = std::type_index(typeid(MethodDecl));
是一個類模版特化全肮,可以將模版名轉(zhuǎn)換為字符串 敞咧,參考鏈接
methods
會查找這個key
,如果不存在就新建辜腺,
incoming::methods::block_sync
類型定義如下:
namespace incoming {
namespace methods {
// synchronously push a block/trx to a single provider
using block_sync = method_decl<chain_plugin_interface, void(const signed_block_ptr&), first_provider_policy>;
}
}
method_decl
定義又如下
template< typename Tag, typename FunctionSig, template <typename> class DispatchPolicy = first_success_policy>
struct method_decl {
using method_type = method<FunctionSig, DispatchPolicy<FunctionSig>>;
using tag_type = Tag;
};
using method_type = typename MethodDecl::method_type;
翻譯如下:
using method_type = method<void(const signed_block_ptr&), first_success_policy>
查看method
定義休建,繼承自 method_caller
method_caller
中定義了signal_type
為 boost
庫中的signal
類型:
boost::signals2::signal<void(Args...), DispatchPolicy>;
并重載了()
函數(shù):
void operator()(Args&&... args)
{
_signal(std::forward<Args>(args)...);
}
由 signal
直接發(fā)出信號
回到上面
app().get_method<incoming::methods::block_sync>()(std::make_shared<signed_block>(params))
最終拿到一個 chain_plugin_interface
類型的信號乍恐,將事件發(fā)出,供其他plugin
接受测砂,plugin
之間的通信用這種方式可以減少耦合
全局查找 incoming::methods::block_sync
會發(fā)現(xiàn)茵烈,在 producer_plugin
中注冊了此類信號的回調(diào)
my->_incoming_block_sync_provider = app().get_method<incoming::methods::block_sync>().register_provider([this](const signed_block_ptr& block){
my->on_incoming_block(block);
});
這里沒有深入討論 boost
庫的 signal
機制。只是簡單闡述調(diào)用流程砌些。