• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
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 
16 #ifndef PANDA_TOOLING_INSPECTOR_CONNECTION_ASIO_SERVER_ENDPOINT_H
17 #define PANDA_TOOLING_INSPECTOR_CONNECTION_ASIO_SERVER_ENDPOINT_H
18 
19 #include "websocketpp/common/connection_hdl.hpp"
20 #include "websocketpp/frame.hpp"
21 #include "websocketpp/server.hpp"
22 
23 #include "connection/server_endpoint_base.h"
24 
25 namespace ark::tooling::inspector {
26 // Server endpoint based on websocketpp implementation.
27 // NOLINTNEXTLINE(fuchsia-multiple-inheritance)
28 template <typename Config>
29 class ServerEndpoint : public ServerEndpointBase {
30 protected:
31     using Endpoint = websocketpp::server<Config>;
32     using ConnectionPtr = typename Endpoint::connection_ptr;
33 
34 public:
35     ServerEndpoint() noexcept;
36 
37 protected:
GetPinnedConnection()38     ConnectionPtr GetPinnedConnection()
39     {
40         return connection_;
41     }
42 
Pin(const websocketpp::connection_hdl & hdl)43     bool Pin(const websocketpp::connection_hdl &hdl)
44     {
45         ConnectionPtr expected;
46         // set new connection only if there is no already existing one
47         return std::atomic_compare_exchange_strong(&connection_, &expected, endpoint_.get_con_from_hdl(hdl));
48     }
49 
Unpin(const websocketpp::connection_hdl & hdl)50     void Unpin(const websocketpp::connection_hdl &hdl)
51     {
52         auto expected = endpoint_.get_con_from_hdl(hdl);
53         // expect that the given connection is the one already stored
54         std::atomic_compare_exchange_strong(&connection_, &expected, {});
55     }
56 
57     bool Close();
58 
59     Endpoint endpoint_;  // NOLINT(misc-non-private-member-variables-in-classes)
60 
61 private:
SendMessage(const std::string & message)62     void SendMessage(const std::string &message) override
63     {
64         if (auto connection = GetPinnedConnection()) {
65             connection->send(message, websocketpp::frame::opcode::text);
66         } else {
67             LOG(INFO, DEBUGGER) << "Did not send message: " << message;
68         }
69     }
70 
71     ConnectionPtr connection_;
72 };
73 }  // namespace ark::tooling::inspector
74 
75 #endif  // PANDA_TOOLING_INSPECTOR_CONNECTION_ASIO_SERVER_ENDPOINT_H
76