Add more grpc - Asyncstuff
[src/agl-compositor.git] / clients / grpc-async.h
1 #pragma once
2
3 #include <memory>
4
5 #include <grpc/grpc.h>
6 #include <grpcpp/grpcpp.h>
7 #include <grpcpp/server.h>
8 #include <grpcpp/server_builder.h>
9 #include <grpcpp/server_context.h>
10
11 #include <grpcpp/ext/proto_server_reflection_plugin.h>
12 #include <grpcpp/health_check_service_interface.h>
13
14 #include "shell.h"
15 #include "agl_shell.grpc.pb.h"
16
17 namespace {
18        const char kDefaultGrpcServiceAddress[] = "127.0.0.1:14005";
19 }
20
21 class CallData {
22 public:
23         // Take in the "service" instance (in this case representing an
24         // asynchronous server) and the completion queue "cq" used for
25         // asynchronous communication with the gRPC runtime.
26         CallData(Greeter::AsyncService* service, grpc::ServerCompletionQueue* cq)
27                 : m_service(service), m_cq(cq), m_repliesSent(0), 
28                 m_responder(&m_ctx), m_status(CREATE) { Proceed(); }
29         void Proceed();
30 private:
31         // The means of communication with the gRPC runtime for an asynchronous
32         // server.
33         Greeter::AsyncService *m_service;
34         // The producer-consumer queue where for asynchronous server
35         // notifications.
36         grpc::ServerCompletionQueue *m_cq;
37         // Context for the rpc, allowing to tweak aspects of it such as the use
38         // of compression, authentication, as well as to send metadata back to
39         // the client.
40         grpc::ServerContext m_ctx;
41
42         // What we send back to the client.
43         ::agl_shell_ipc::AppState m_reply;
44
45         uint32_t m_repliesSent;
46         const uint32_t MAX_REPLIES = 5;
47
48         // The means to get back to the client.
49         grpc::ServerAsyncWriter<::agl_shell_ipc::AppState> m_responder;
50
51         // Let's implement a tiny state machine with the following states.
52         enum CallStatus {
53                 CREATE,
54                 PROCESS,
55                 PROCESSING,
56                 FINISH
57         };
58
59         // The current serving state.
60         CallStatus m_status;
61 };
62
63
64 class GrpcServiceImpl final {
65 public:
66         GrpcServiceImpl(Shell *aglShell) : m_aglShell(aglShell) {}
67         ~GrpcServiceImpl();
68         void Run();
69
70         // This can be run in multiple threads if needed.
71         void HandleRpcs();
72
73 private:
74        Shell *m_aglShell;
75
76        std::unique_ptr<grpc::ServerCompletionQueue> m_cq;
77        Greeter::AsyncService m_service;
78        std::unique_ptr<grpc::Server> m_server;
79 };