Crow
Crow copied to clipboard
Crow async usability
Hello everyone, um, I have a question, what about asynchronous requests? https://github.com/CrowCpp/Crow/issues/258 I'm working with MongoDB and right now it is being called synchronously, i would like to get some recommendations from you regarding asynchronous executions in Crow, maybe i don't understand something 🤔
// easy simplification for object_id
static value mongo_create_filter_objectid(std::string id){
return make_document(kvp("_id", bsoncxx::oid{bsoncxx::stdx::string_view(id.data())}));
}
// example implementation of document get
const std::string mongo_get_document(std::string db, std::string collection, const std::string& id){
auto result = client->database(db).collection(collection).find_one(mongo_create_filter_objectid(id).view());
if(result) return bsoncxx::to_json(result.value());
else return {};
}
CROW_BP_ROUTE(bp, "user").methods(HTTPMethod::GET)([](const crow::request& req) {
// direct call my mongodb methods
// i guess, this need something like std::future or std::async, i dont know
const std::string document = mongo_get_document("mydb", "users", "any_oid");
if(document.empty()){
return response(BAD_REQUEST);
}
return response(OK);
});
Yes, it works great, I don't have any errors or anything like that, all queries in Crow work incredibly fast, but... As I understand, such operations can completely block the thread until the end of execution, which in theory can lead to bad consequences
This is probably the next big problem after CORS, which worries me a lot, if anyone has experience working with the async/await mechanism, please share your thoughts here
i read discussion Asynchronous Handlers #258 , but I still don't understand whether response::end was implemented are async or not, and in general, does it work async in the end or not. Or are all requests in the CROW_ROUTE lambda non-blocking by default and me don’t have to worry?
Well, I realized that no one would offer anything. In the end, I solved the problem by remembering that mongocxx has connection pool support, maybe this will be useful for someone, before that I used a single connection client And of course, I use memcached for simple caching of all data, so I think everything is okay, synchronous requests are not so bad in lambda Crow route
I don’t know how safe it is to use std::async while waiting for std::feature to be executed inside Crow route, I’m afraid to create a lot of unnecessary threads, so I didn’t take the risk 🤞