xref: /aosp_15_r20/external/pigweed/pw_rpc_transport/public/pw_rpc_transport/service_registry.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://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, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15 
16 #include "pw_rpc/client_server.h"
17 #include "pw_rpc/packet_meta.h"
18 #include "pw_rpc_transport/rpc_transport.h"
19 #include "pw_span/span.h"
20 #include "pw_status/status.h"
21 
22 namespace pw::rpc {
23 
24 // An RpcPacketProcessor implementation that uses an incoming RPC packet
25 // metadata to find its target service and sends the packet to that service for
26 // processing.
27 class ServiceRegistry : public RpcPacketProcessor {
28  public:
ServiceRegistry(span<Channel> channels)29   explicit ServiceRegistry(span<Channel> channels) : client_server_(channels) {}
30 
client_server()31   ClientServer& client_server() { return client_server_; }
32 
33   template <typename Service>
CreateClient(uint32_t channel_id)34   typename Service::Client CreateClient(uint32_t channel_id) {
35     return typename Service::Client(client_server_.client(), channel_id);
36   }
37 
RegisterService(Service & service)38   void RegisterService(Service& service) {
39     client_server_.server().RegisterService(service);
40   }
41 
ProcessRpcPacket(ConstByteSpan rpc_packet)42   Status ProcessRpcPacket(ConstByteSpan rpc_packet) override {
43     PW_TRY_ASSIGN(const auto meta, PacketMeta::FromBuffer(rpc_packet));
44     if (meta.destination_is_client()) {
45       return client_server_.client().ProcessPacket(rpc_packet);
46     }
47     if (meta.destination_is_server()) {
48       return client_server_.server().ProcessPacket(rpc_packet);
49     }
50     return Status::DataLoss();
51   }
52 
53  private:
54   ClientServer client_server_;
55 };
56 
57 }  // namespace pw::rpc
58