• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     // Used for client streaming to determine whether initial request packet has
56     // been sent on yet.
57     bool sent_request = false;
58   };
59 
60   // Returns copy of stream state so service/method id can be used unlocked.
61   Result<Stream> LookupStream(StreamId id);
62   void ResetAllStreams();
63   void ResetStream(StreamId id);
64   void MarkSentRequest(StreamId id);
65   Status CreateStream(StreamId id, uint32_t service_id, uint32_t method_id);
66 
67   sync::InlineBorrowable<std::array<Stream, internal::kMaxConcurrentStreams>>
68       streams_;
69   const uint32_t channel_id_;
70   rpc::Server& server_;
71 };
72 
73 }  // namespace pw::grpc
74