diff --git a/services/blob/CMakeLists.txt b/services/blob/CMakeLists.txt --- a/services/blob/CMakeLists.txt +++ b/services/blob/CMakeLists.txt @@ -52,6 +52,8 @@ include_directories( ./src ./src/DatabaseEntities + ./src/Reactors/server + ./src/Reactors/server/base-reactors ./_generated ${FOLLY_INCLUDES} ./lib/double-conversion diff --git a/services/blob/src/Reactors/server/base-reactors/ServerBidiReactorBase.h b/services/blob/src/Reactors/server/base-reactors/ServerBidiReactorBase.h new file mode 100644 --- /dev/null +++ b/services/blob/src/Reactors/server/base-reactors/ServerBidiReactorBase.h @@ -0,0 +1,106 @@ +#pragma once + +#include + +#include +#include +#include + +namespace comm { +namespace network { +namespace reactor { + +struct ServerBidiReactorStatus { + grpc::Status status = grpc::Status::OK; + bool sendLastResponse = false; + ServerBidiReactorStatus( + grpc::Status status = grpc::Status::OK, + bool sendLastResponse = false) + : status(status), sendLastResponse(sendLastResponse) { + } +}; + +template +class ServerBidiReactorBase + : public grpc::ServerBidiReactor { + Request request; + Response response; + +protected: + ServerBidiReactorStatus status; + bool readingAborted = false; + +public: + ServerBidiReactorBase(); + + void OnDone() override; + void OnReadDone(bool ok) override; + void OnWriteDone(bool ok) override; + + void terminate(ServerBidiReactorStatus status); + + virtual std::unique_ptr + handleRequest(Request request, Response *response) = 0; + virtual void initialize(){}; + virtual void doneCallback(){}; +}; + +template +ServerBidiReactorBase::ServerBidiReactorBase() { + this->initialize(); + this->StartRead(&this->request); +} + +template +void ServerBidiReactorBase::OnDone() { + this->doneCallback(); + delete this; +} + +template +void ServerBidiReactorBase::terminate( + ServerBidiReactorStatus status) { + this->status = status; + if (this->status.sendLastResponse) { + this->StartWriteAndFinish( + &this->response, grpc::WriteOptions(), this->status.status); + } else { + this->Finish(this->status.status); + } +} + +template +void ServerBidiReactorBase::OnReadDone(bool ok) { + if (!ok) { + this->readingAborted = true; + this->terminate(ServerBidiReactorStatus( + grpc::Status(grpc::StatusCode::ABORTED, "no more reads"))); + return; + } + try { + this->response = Response(); + std::unique_ptr status = + this->handleRequest(this->request, &this->response); + if (status != nullptr) { + this->terminate(*status); + return; + } + this->StartWrite(&this->response); + } catch (std::runtime_error &e) { + this->terminate(ServerBidiReactorStatus( + grpc::Status(grpc::StatusCode::INTERNAL, e.what()))); + } +} + +template +void ServerBidiReactorBase::OnWriteDone(bool ok) { + if (!ok) { + std::cout << "Server write failed" << std::endl; + return; + } + this->StartRead(&this->request); +} + +} // namespace reactor +} // namespace network +} // namespace comm