rpc_connection.h
1 // Copyright 2018, Beeri 15. All rights reserved.
2 // Author: Roman Gershman (romange@gmail.com)
3 //
4 #pragma once
5 
6 #include <memory>
7 
8 #include "util/asio/connection_handler.h"
9 
10 #include "util/rpc/rpc_envelope.h"
11 #include "strings/stringpiece.h"
12 
13 namespace util {
14 
15 // RPC-Server side part.
16 
17 namespace rpc {
18 
19 // Also defined in frame_format.h. Seems to work.
20 typedef uint64_t RpcId;
21 
22 // ConnectionBridge is responsible to abstract higher level server-app logic and to provide
23 // an interface that allows to map Envelope to ServiceInterface methods.
24 // ConnectionBridge is a single-fiber creature, so currently only one caller fiber can
25 // use it simultaneusly.
26 // ConnectionBridge can be asynchronous, i.e. it's main calling function HandleEnvelope
27 // can exit before it finishes writing to EnvelopeWriter.
29  public:
30  typedef std::function<void(Envelope&&)> EnvelopeWriter;
31 
32  virtual ~ConnectionBridge() {}
33 
34  // Is called once from the connection thread before HandleEnvelope is being called.
35  // Is intended to finalize the setup for the bridge inside its intended thread.
36  virtual void InitInThread() {}
37 
38  // Main entry function that handles the input envelope and is responsible for
39  // writing the results via writer.
40  // HandleEnvelope first reads the input and if everything is parsed fine, it writes
41  // back one or more envelopes via the writer. Specifics of the protocol are defined
42  // in the derived class. Since HandleEnvelope can be asynchronous,
43  // the caller should make sure the writer is valid through the call.
44  virtual void HandleEnvelope(RpcId rpc_id, Envelope* input,
45  EnvelopeWriter writer) = 0;
46 
47  // In case HandleEnvelope is asynchronous, waits for all the issued calls to finish.
48  // HandleEnvelope should not be called after calling Join().
49  virtual void Join() {};
50 };
51 
53  public:
54  virtual ~ServiceInterface() {}
55 
56  protected:
57  // A factory method creating a handler that handles requests for a single connection.
58  // The ownership over handler is passed to the caller.
59  virtual ConnectionBridge* CreateConnectionBridge() = 0;
60 
61  ConnectionHandler* NewConnection(IoContext& context) final;
62 };
63 
64 } // namespace rpc
65 } // namespace util
Abstracts away connections implementation and their life-cycle.