1 // Copyright 2021 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef GRPC_SRC_CORE_EXT_TRANSPORT_BINDER_CLIENT_ENDPOINT_BINDER_POOL_H
16 #define GRPC_SRC_CORE_EXT_TRANSPORT_BINDER_CLIENT_ENDPOINT_BINDER_POOL_H
17 
18 #include <grpc/support/port_platform.h>
19 
20 #include <functional>
21 #include <string>
22 
23 #include "absl/container/flat_hash_map.h"
24 
25 #include "src/core/ext/transport/binder/wire_format/binder.h"
26 #include "src/core/lib/gprpp/sync.h"
27 
28 namespace grpc_binder {
29 
30 // This class serves as a buffer of endpoint binders between C++ and
31 // Java. `AddEndpointBinder` will be indirectly invoked by Java code, and
32 // `GetEndpointBinder` is for C++ code to register callback to get endpoint
33 // binder when become available. This simplifies JNI related threading issues
34 // since both side only need to interact with this buffer in non-blocking
35 // manner and avoids cross-language callbacks.
36 class EndpointBinderPool {
37  public:
38   // Invokes the callback when the binder corresponding to the conn_id become
39   // available. If the binder is already available, invokes the callback
40   // immediately.
41   // Ownership of the endpoint binder will be transferred to the callback
42   // function and it will be removed from the pool
43   void GetEndpointBinder(
44       std::string conn_id,
45       std::function<void(std::unique_ptr<grpc_binder::Binder>)> cb);
46 
47   // Add an endpoint binder to the pool
48   void AddEndpointBinder(std::string conn_id,
49                          std::unique_ptr<grpc_binder::Binder> b);
50 
51  private:
52   grpc_core::Mutex m_;
53   absl::flat_hash_map<std::string, std::unique_ptr<grpc_binder::Binder>>
54       binder_map_ ABSL_GUARDED_BY(m_);
55   absl::flat_hash_map<std::string,
56                       std::function<void(std::unique_ptr<grpc_binder::Binder>)>>
57       pending_requests_ ABSL_GUARDED_BY(m_);
58 };
59 
60 // Returns the singleton
61 EndpointBinderPool* GetEndpointBinderPool();
62 
63 }  // namespace grpc_binder
64 
65 #endif  // GRPC_SRC_CORE_EXT_TRANSPORT_BINDER_CLIENT_ENDPOINT_BINDER_POOL_H
66