xref: /aosp_15_r20/external/pigweed/pw_rpc/nanopb/common.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2020 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 
15 // clang-format off
16 #include "pw_rpc/internal/log_config.h" // PW_LOG_* macros must be first.
17 
18 #include "pw_rpc/nanopb/internal/common.h"
19 // clang-format on
20 
21 #include "pb_decode.h"
22 #include "pb_encode.h"
23 #include "pw_assert/check.h"
24 #include "pw_log/log.h"
25 #include "pw_result/result.h"
26 #include "pw_rpc/internal/client_call.h"
27 #include "pw_rpc/internal/encoding_buffer.h"
28 #include "pw_rpc/nanopb/server_reader_writer.h"
29 #include "pw_status/try.h"
30 
31 namespace pw::rpc::internal {
32 namespace {
33 
34 // Nanopb 3 uses pb_field_s and Nanopb 4 uses pb_msgdesc_s for fields. The
35 // Nanopb version macro is difficult to use, so deduce the correct type from the
36 // pb_decode function.
37 template <typename DecodeFunction>
38 struct NanopbTraits;
39 
40 template <typename FieldsType>
41 struct NanopbTraits<bool(pb_istream_t*, FieldsType, void*)> {
42   using Fields = FieldsType;
43 };
44 
45 using Fields = typename NanopbTraits<decltype(pb_decode)>::Fields;
46 
47 }  // namespace
48 
49 // PB_NO_ERRMSG is used in pb_decode.h and pb_encode.h to enable or disable the
50 // errmsg member of the istream and ostream structs. If errmsg is available, use
51 // it to give more detailed log messages.
52 #ifdef PB_NO_ERRMSG
53 
54 #define PW_RPC_LOG_NANOPB_FAILURE(msg, stream) PW_LOG_ERROR(msg)
55 
56 #else
57 
58 #define PW_RPC_LOG_NANOPB_FAILURE(msg, stream) \
59   PW_LOG_ERROR(msg ": %s", stream.errmsg)
60 
61 #endif  // PB_NO_ERRMSG
62 
Encode(const void * proto_struct,ByteSpan buffer) const63 StatusWithSize NanopbSerde::Encode(const void* proto_struct,
64                                    ByteSpan buffer) const {
65   auto output = pb_ostream_from_buffer(
66       reinterpret_cast<pb_byte_t*>(buffer.data()), buffer.size());
67   if (!pb_encode(&output, static_cast<Fields>(fields_), proto_struct)) {
68     PW_RPC_LOG_NANOPB_FAILURE("Nanopb protobuf encode failed", output);
69     return StatusWithSize::Internal();
70   }
71   return StatusWithSize(output.bytes_written);
72 }
73 
EncodedSizeBytes(const void * proto_struct) const74 StatusWithSize NanopbSerde::EncodedSizeBytes(const void* proto_struct) const {
75   size_t encoded_size = 0;
76   return pb_get_encoded_size(&encoded_size, fields_, proto_struct)
77              ? StatusWithSize(encoded_size)
78              : StatusWithSize::Unknown();
79 }
80 
Decode(ConstByteSpan buffer,void * proto_struct) const81 Status NanopbSerde::Decode(ConstByteSpan buffer, void* proto_struct) const {
82   auto input = pb_istream_from_buffer(
83       reinterpret_cast<const pb_byte_t*>(buffer.data()), buffer.size());
84   bool result = pb_decode(&input, static_cast<Fields>(fields_), proto_struct);
85   if (!result) {
86     PW_RPC_LOG_NANOPB_FAILURE("Nanopb protobuf decode failed", input);
87     return Status::DataLoss();
88   }
89   return OkStatus();
90 }
91 
92 #undef PW_RPC_LOG_NANOPB_FAILURE
93 
NanopbSendInitialRequest(ClientCall & call,NanopbSerde serde,const void * payload)94 void NanopbSendInitialRequest(ClientCall& call,
95                               NanopbSerde serde,
96                               const void* payload) {
97   PW_DCHECK(call.active_locked());
98 
99   Result<ByteSpan> result = EncodeToPayloadBuffer(payload, serde);
100 
101   if (result.ok()) {
102     call.SendInitialClientRequest(*result);
103   } else {
104     call.CloseAndMarkForCleanup(result.status());
105   }
106 }
107 
NanopbSendStream(Call & call,const void * payload,const NanopbMethodSerde * serde)108 Status NanopbSendStream(Call& call,
109                         const void* payload,
110                         const NanopbMethodSerde* serde) {
111   if (!call.active_locked()) {
112     return Status::FailedPrecondition();
113   }
114 
115   Result<ByteSpan> result = EncodeToPayloadBuffer(
116       payload,
117       call.type() == kClientCall ? serde->request() : serde->response());
118 
119   PW_TRY(result.status());
120   return call.WriteLocked(*result);
121 }
122 
SendFinalResponse(NanopbServerCall & call,const void * payload,const Status status)123 Status SendFinalResponse(NanopbServerCall& call,
124                          const void* payload,
125                          const Status status) {
126   RpcLockGuard lock;
127   if (!call.active_locked()) {
128     return Status::FailedPrecondition();
129   }
130 
131   Result<ByteSpan> result =
132       EncodeToPayloadBuffer(payload, call.serde().response());
133   if (!result.ok()) {
134     return call.CloseAndSendServerErrorLocked(Status::Internal());
135   }
136   return call.CloseAndSendResponseLocked(*result, status);
137 }
138 
TrySendFinalResponse(NanopbServerCall & call,const void * payload,const Status status)139 Status TrySendFinalResponse(NanopbServerCall& call,
140                             const void* payload,
141                             const Status status) {
142   RpcLockGuard lock;
143   if (!call.active_locked()) {
144     return Status::FailedPrecondition();
145   }
146 
147   Result<ByteSpan> result =
148       EncodeToPayloadBuffer(payload, call.serde().response());
149   if (!result.ok()) {
150     return call.TryCloseAndSendServerErrorLocked(Status::Internal());
151   }
152   return call.TryCloseAndSendResponseLocked(*result, status);
153 }
154 
155 }  // namespace pw::rpc::internal
156