• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "pw_rpc/internal/raw_method.h"
16 
17 #include <cstring>
18 
19 #include "pw_log/log.h"
20 #include "pw_rpc/internal/packet.h"
21 
22 namespace pw::rpc {
23 
~RawServerWriter()24 RawServerWriter::~RawServerWriter() {
25   if (!buffer().empty()) {
26     ReleasePayloadBuffer();
27   }
28 }
29 
Write(ConstByteSpan response)30 Status RawServerWriter::Write(ConstByteSpan response) {
31   if (!open()) {
32     return Status::FailedPrecondition();
33   }
34 
35   if (buffer().Contains(response)) {
36     return ReleasePayloadBuffer(response);
37   }
38 
39   std::span<std::byte> buffer = AcquirePayloadBuffer();
40 
41   if (response.size() > buffer.size()) {
42     ReleasePayloadBuffer();
43     return Status::OutOfRange();
44   }
45 
46   std::memcpy(buffer.data(), response.data(), response.size());
47   return ReleasePayloadBuffer(buffer.first(response.size()));
48 }
49 
50 namespace internal {
51 
CallUnary(ServerCall & call,const Packet & request) const52 void RawMethod::CallUnary(ServerCall& call, const Packet& request) const {
53   Channel::OutputBuffer response_buffer = call.channel().AcquireBuffer();
54   std::span payload_buffer = response_buffer.payload(request);
55 
56   StatusWithSize sws = function_.unary(call, request.payload(), payload_buffer);
57   Packet response = Packet::Response(request);
58 
59   response.set_payload(payload_buffer.first(sws.size()));
60   response.set_status(sws.status());
61   if (call.channel().Send(response_buffer, response).ok()) {
62     return;
63   }
64 
65   PW_LOG_WARN("Failed to send response packet for channel %u",
66               unsigned(call.channel().id()));
67   call.channel().Send(Packet::ServerError(request, Status::Internal()));
68 }
69 
CallServerStreaming(ServerCall & call,const Packet & request) const70 void RawMethod::CallServerStreaming(ServerCall& call,
71                                     const Packet& request) const {
72   internal::BaseServerWriter server_writer(call);
73   function_.server_streaming(call, request.payload(), server_writer);
74 }
75 
76 }  // namespace internal
77 }  // namespace pw::rpc
78