1 /* 2 * Copyright 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #pragma once 18 19 #include <grpc++/grpc++.h> 20 21 #include <atomic> 22 #include <chrono> 23 #include <utility> 24 25 #include "blueberry/facade/common.pb.h" 26 #include "common/blocking_queue.h" 27 #include "os/log.h" 28 29 namespace bluetooth { 30 namespace grpc { 31 32 template <typename T> 33 class GrpcEventQueue { 34 public: 35 /** 36 * Create a GrpcEventQueue that can be used to shuffle event from one thread to another 37 * @param log_name 38 */ GrpcEventQueue(std::string log_name)39 explicit GrpcEventQueue(std::string log_name) : log_name_(std::move(log_name)){}; 40 41 /** 42 * Run the event loop and blocks until client cancels the stream request 43 * Event queue will be cleared before entering the loop. Hence, only events occurred after gRPC request will be 44 * delivered to the user. Hence user is advised to run the loop before generating pending events. 45 * 46 * @param context client context 47 * @param writer output writer 48 * @return gRPC status 49 */ RunLoop(::grpc::ServerContext * context,::grpc::ServerWriter<T> * writer)50 ::grpc::Status RunLoop(::grpc::ServerContext* context, ::grpc::ServerWriter<T>* writer) { 51 using namespace std::chrono_literals; 52 LOG_INFO("%s: Entering Loop", log_name_.c_str()); 53 while (!context->IsCancelled()) { 54 // Wait for 100 ms so that cancellation can be caught in amortized 50 ms latency 55 if (pending_events_.wait_to_take(100ms)) { 56 LOG_INFO("%s: Got event from queue", log_name_.c_str()); 57 writer->Write(pending_events_.take()); 58 } 59 } 60 running_ = false; 61 LOG_INFO("%s: Exited Loop", log_name_.c_str()); 62 return ::grpc::Status::OK; 63 } 64 65 /** 66 * Called when there is an incoming event 67 * @param event incoming event 68 */ OnIncomingEvent(T event)69 void OnIncomingEvent(T event) { 70 if (!running_) { 71 LOG_INFO("%s: Discarding an event while not running the loop", log_name_.c_str()); 72 return; 73 } 74 LOG_INFO("%s: Got event, enqueuing", log_name_.c_str()); 75 pending_events_.push(std::move(event)); 76 } 77 78 private: 79 std::string log_name_; 80 std::atomic<bool> running_{true}; 81 common::BlockingQueue<T> pending_events_; 82 }; 83 84 } // namespace grpc 85 } // namespace bluetooth 86