xref: /aosp_15_r20/external/pigweed/pw_grpc/public/pw_grpc/pw_rpc_handler.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2024 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 <cinttypes>
17 #include <string_view>
18 
19 #include "pw_bytes/span.h"
20 #include "pw_grpc/connection.h"
21 #include "pw_grpc/grpc_channel_output.h"
22 #include "pw_log/log.h"
23 #include "pw_result/result.h"
24 #include "pw_rpc/internal/hash.h"
25 #include "pw_rpc/server.h"
26 #include "pw_rpc_transport/rpc_transport.h"
27 #include "pw_status/status.h"
28 #include "pw_sync/inline_borrowable.h"
29 
30 namespace pw::grpc {
31 
32 class PwRpcHandler : public Connection::RequestCallbacks,
33                      public GrpcChannelOutput::StreamCallbacks {
34  public:
PwRpcHandler(uint32_t channel_id,rpc::Server & server)35   PwRpcHandler(uint32_t channel_id, rpc::Server& server)
36       : channel_id_(channel_id), server_(server) {}
37 
38   // GrpcChannelOutput::StreamCallbacks
39   void OnClose(StreamId id) override;
40 
41   // Connection::RequestCallbacks
42   void OnNewConnection() override;
43   Status OnNew(StreamId id,
44                InlineString<kMaxMethodNameSize> full_method_name) override;
45   Status OnMessage(StreamId id, ByteSpan message) override;
46   void OnHalfClose(StreamId id) override;
47 
48   void OnCancel(StreamId id) override;
49 
50  private:
51   struct Stream {
52     StreamId id;
53     uint32_t service_id;
54     uint32_t method_id;
55     pw::rpc::MethodType method_type;
56     // Used for client streaming to determine whether initial request packet has
57     // been sent on yet.
58     bool sent_request = false;
59   };
60 
61   // Returns copy of stream state so service/method id can be used unlocked.
62   Result<Stream> LookupStream(StreamId id);
63   void ResetAllStreams();
64   void ResetStream(StreamId id);
65   void MarkSentRequest(StreamId id);
66   Status CreateStream(StreamId id,
67                       uint32_t service_id,
68                       uint32_t method_id,
69                       pw::rpc::MethodType method_type);
70 
71   sync::InlineBorrowable<std::array<Stream, internal::kMaxConcurrentStreams>>
72       streams_;
73   const uint32_t channel_id_;
74   rpc::Server& server_;
75 };
76 
77 }  // namespace pw::grpc
78