KiCad PCB EDA Suite
Loading...
Searching...
No Matches
api_handler.h
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2023 Jon Evans <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software: you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21#ifndef KICAD_API_HANDLER_H
22#define KICAD_API_HANDLER_H
23
24#include <functional>
25#include <optional>
26
27#include <fmt/format.h>
28#include <tl/expected.hpp>
29
30#include <wx/debug.h>
31#include <wx/string.h>
32
33#include <google/protobuf/message.h>
34
35#include <kicommon.h>
36#include <api/common/envelope.pb.h>
37#include <core/typeinfo.h>
38
40
41using kiapi::common::ApiRequest, kiapi::common::ApiResponse;
42using kiapi::common::ApiResponseStatus, kiapi::common::ApiStatusCode;
43
44typedef tl::expected<ApiResponse, ApiResponseStatus> API_RESULT;
45
46template <typename T>
47using HANDLER_RESULT = tl::expected<T, ApiResponseStatus>;
48
49
50template <typename RequestMessageType>
52{
53 std::string ClientName;
54 RequestMessageType Request;
55};
56
57
59{
60public:
62
63 virtual ~API_HANDLER() {}
64
70 API_RESULT Handle( ApiRequest& aMsg );
71
73 bool CanHandle( const std::string& aTypeName ) const
74 {
75 return m_handlers.find( aTypeName ) != m_handlers.end();
76 }
77
81 bool AllowsDuringTask( const std::string& aTypeName ) const
82 {
83 auto it = m_handlers.find( aTypeName );
84 return it != m_handlers.end() && it->second.AllowedDuringTask;
85 }
86
91 virtual void onNetSettingsChanged() {}
92
94
97 {
98 bool pending = m_notifyNetSettings;
99 m_notifyNetSettings = false;
100 return pending;
101 }
102
104 void setApiServer( KICAD_API_SERVER* aServer ) { m_apiServer = aServer; }
106
107protected:
112 typedef std::function<HANDLER_RESULT<ApiResponse>( ApiRequest& )> REQUEST_HANDLER;
113
119
135 template <class RequestType, class ResponseType, class HandlerType>
136 void registerHandler( HANDLER_RESULT<ResponseType> ( HandlerType::*aHandler )(
137 const HANDLER_CONTEXT<RequestType>& ), bool aAllowedDuringTask = false )
138 {
139 std::string typeName { RequestType().GetTypeName() };
140
141 wxASSERT_MSG( !m_handlers.contains( typeName ),
142 wxString::Format( "Duplicate API handler for type %s", typeName ) );
143
144 m_handlers[typeName] =
145 HANDLER_ENTRY{ [this, aHandler, typeName]( ApiRequest& aRequest ) -> API_RESULT
146 {
148 ApiResponse envelope;
149
150 if( !tryUnpack( aRequest, envelope, ctx.Request ) )
151 return envelope;
152
153 ctx.ClientName = aRequest.header().client_name();
154
156 std::invoke( aHandler, static_cast<HandlerType*>( this ), ctx );
157
158 if( response.has_value() )
159 {
160 if( !envelope.mutable_message()->PackFrom( *response ) )
161 {
162 wxFAIL_MSG( wxString::Format( "Failed to pack '%s'", typeName ) );
163
164 ApiResponseStatus status;
165 status.set_status( ApiStatusCode::AS_INTERNAL_ERROR );
166 status.set_error_message( "the response could not be serialized" );
167 return tl::unexpected( status );
168 }
169
170 envelope.mutable_status()->set_status( ApiStatusCode::AS_OK );
171 return envelope;
172 }
173 else
174 {
175 return tl::unexpected( response.error() );
176 }
177 }, aAllowedDuringTask };
178 }
179
181 std::map<std::string, HANDLER_ENTRY> m_handlers;
182
184
186
187 static const wxString m_defaultCommitMessage;
188
189private:
190
191 template<typename MessageType>
192 bool tryUnpack( ApiRequest& aRequest, ApiResponse& aReply, MessageType& aDest )
193 {
194 if( !aRequest.message().UnpackTo( &aDest ) )
195 {
196 std::string msg = fmt::format( "could not unpack message of type {} from request",
197 aDest.GetTypeName() );
198 aReply.mutable_status()->set_status( ApiStatusCode::AS_BAD_REQUEST );
199 aReply.mutable_status()->set_error_message( msg );
200 return false;
201 }
202
203 return true;
204 }
205};
206
207#endif //KICAD_API_HANDLER_H
tl::expected< ApiResponse, ApiResponseStatus > API_RESULT
Definition api_handler.h:44
tl::expected< T, ApiResponseStatus > HANDLER_RESULT
Definition api_handler.h:47
std::map< std::string, HANDLER_ENTRY > m_handlers
Maps type name (without the URL prefix) to a handler method.
static const wxString m_defaultCommitMessage
bool AllowsDuringTask(const std::string &aTypeName) const
Definition api_handler.h:81
KICAD_API_SERVER * m_apiServer
virtual void onNetSettingsChanged()
Called on all registered handlers after project net settings (netclasses or netclass assignments) hav...
Definition api_handler.h:91
KICAD_API_SERVER * apiServer() const
void registerHandler(HANDLER_RESULT< ResponseType >(HandlerType::*aHandler)(const HANDLER_CONTEXT< RequestType > &), bool aAllowedDuringTask=false)
Registers an API command handler for the given message types.
virtual ~API_HANDLER()
Definition api_handler.h:63
bool m_notifyNetSettings
void requestNetSettingsNotification()
Definition api_handler.h:93
bool clearNetSettingsNotification()
Returns true if the notification had been requested at the time of the call.
Definition api_handler.h:96
bool tryUnpack(ApiRequest &aRequest, ApiResponse &aReply, MessageType &aDest)
bool CanHandle(const std::string &aTypeName) const
Definition api_handler.h:73
std::function< HANDLER_RESULT< ApiResponse >(ApiRequest &)> REQUEST_HANDLER
A handler for outer messages (envelopes) that will unpack to inner messages and call a specific handl...
void setApiServer(KICAD_API_SERVER *aServer)
Set by KICAD_API_SERVER::RegisterHandler; null when the handler is not registered.
Handle(KICAD3D_INFO) KICAD3D_INFO
#define KICOMMON_API
Definition kicommon.h:27
bool AllowedDuringTask
REQUEST_HANDLER Handler
std::string ClientName
Definition api_handler.h:53
RequestMessageType Request
Definition api_handler.h:54