blob: 7745e95efd99fa063216e27967b0b62c7059634e [file] [log] [blame]
Wyatt Heplerf9fb90f2020-09-30 18:59:33 -07001.. _module-pw_rpc:
Alexei Frolov26e3ae62020-05-04 17:06:17 -07002
3------
4pw_rpc
5------
6The ``pw_rpc`` module provides a system for defining and invoking remote
7procedure calls (RPCs) on a device.
8
Wyatt Hepler830d26d2021-02-17 09:07:43 -08009This document discusses the ``pw_rpc`` protocol and its C++ implementation.
10``pw_rpc`` implementations for other languages are described in their own
11documents:
12
13.. toctree::
14 :maxdepth: 1
15
16 py/docs
Jared Weinsteind4649112021-08-19 12:27:23 -070017 ts/docs
Wyatt Hepler830d26d2021-02-17 09:07:43 -080018
Wyatt Hepler455b4922020-09-18 00:19:21 -070019.. admonition:: Try it out!
20
Wyatt Heplerf9fb90f2020-09-30 18:59:33 -070021 For a quick intro to ``pw_rpc``, see the
Alexei Frolovd3e5cb72021-01-08 13:08:45 -080022 :ref:`module-pw_hdlc-rpc-example` in the :ref:`module-pw_hdlc` module.
Wyatt Hepler455b4922020-09-18 00:19:21 -070023
Wyatt Hepler067dd7e2020-07-14 19:34:32 -070024.. attention::
Alexei Frolov26e3ae62020-05-04 17:06:17 -070025
Wyatt Hepler455b4922020-09-18 00:19:21 -070026 This documentation is under construction.
27
Wyatt Hepler85e91402021-08-05 12:48:03 -070028RPC semantics
29=============
30The semantics of ``pw_rpc`` are similar to `gRPC
31<https://grpc.io/docs/what-is-grpc/core-concepts/>`_.
32
33RPC call lifecycle
34------------------
35In ``pw_rpc``, an RPC begins when the client sends a request packet. The server
36receives the request, looks up the relevant service method, then calls into the
37RPC function. The RPC is considered active until the server sends a response
38packet with the RPC's status. The client may terminate an ongoing RPC by
39cancelling it.
40
41``pw_rpc`` supports only one RPC invocation per service/method/channel. If a
42client calls an ongoing RPC on the same channel, the server cancels the ongoing
43call and reinvokes the RPC with the new request. This applies to unary and
44streaming RPCs, though the server may not have an opportunity to cancel a
45synchronously handled unary RPC before it completes. The same RPC may be invoked
46multiple times simultaneously if the invocations are on different channels.
47
Wyatt Hepler5a3a36b2021-09-08 11:15:05 -070048Unrequested responses
49---------------------
50``pw_rpc`` supports sending responses to RPCs that have not yet been invoked by
51a client. This is useful in testing and in situations like an RPC that triggers
52reboot. After the reboot, the device opens the writer object and sends its
53response to the client.
54
Wyatt Heplerd95e1e92021-09-14 22:10:51 -070055The C++ API for opening a server reader/writer takes the generated RPC function
56as a template parameter. The server to use, channel ID, and service instance are
57passed as arguments. The API is the same for all RPC types, except the
58appropriate reader/writer class must be used.
Wyatt Hepler5a3a36b2021-09-08 11:15:05 -070059
Wyatt Heplerd95e1e92021-09-14 22:10:51 -070060.. code-block:: c++
61
62 // Open a ServerWriter for a server streaming RPC.
63 auto writer = RawServerWriter::Open<pw_rpc::raw::ServiceName::MethodName>(
64 server, channel_id, service_instance);
65
66 // Send some responses, even though the client has not yet called this RPC.
67 CHECK_OK(writer.Write(encoded_response_1));
68 CHECK_OK(writer.Write(encoded_response_2));
69
70 // Finish the RPC.
71 CHECK_OK(writer.Finish(OkStatus()));
Wyatt Hepler5a3a36b2021-09-08 11:15:05 -070072
Wyatt Hepler455b4922020-09-18 00:19:21 -070073Creating an RPC
74===============
75
761. RPC service declaration
77--------------------------
78Pigweed RPCs are declared in a protocol buffer service definition.
79
80* `Protocol Buffer service documentation
81 <https://developers.google.com/protocol-buffers/docs/proto3#services>`_
82* `gRPC service definition documentation
83 <https://grpc.io/docs/what-is-grpc/core-concepts/#service-definition>`_
84
85.. code-block:: protobuf
86
87 syntax = "proto3";
88
89 package foo.bar;
90
91 message Request {}
92
93 message Response {
94 int32 number = 1;
95 }
96
97 service TheService {
98 rpc MethodOne(Request) returns (Response) {}
99 rpc MethodTwo(Request) returns (stream Response) {}
100 }
101
102This protocol buffer is declared in a ``BUILD.gn`` file as follows:
103
104.. code-block:: python
105
106 import("//build_overrides/pigweed.gni")
107 import("$dir_pw_protobuf_compiler/proto.gni")
108
109 pw_proto_library("the_service_proto") {
110 sources = [ "foo_bar/the_service.proto" ]
111 }
112
Wyatt Hepler830d26d2021-02-17 09:07:43 -0800113.. admonition:: proto2 or proto3 syntax?
114
115 Always use proto3 syntax rather than proto2 for new protocol buffers. Proto2
116 protobufs can be compiled for ``pw_rpc``, but they are not as well supported
117 as proto3. Specifically, ``pw_rpc`` lacks support for non-zero default values
118 in proto2. When using Nanopb with ``pw_rpc``, proto2 response protobufs with
119 non-zero field defaults should be manually initialized to the default struct.
120
121 In the past, proto3 was sometimes avoided because it lacked support for field
122 presence detection. Fortunately, this has been fixed: proto3 now supports
123 ``optional`` fields, which are equivalent to proto2 ``optional`` fields.
124
125 If you need to distinguish between a default-valued field and a missing field,
126 mark the field as ``optional``. The presence of the field can be detected
127 with a ``HasField(name)`` or ``has_<field>`` member, depending on the library.
128
129 Optional fields have some overhead --- default-valued fields are included in
130 the encoded proto, and, if using Nanopb, the proto structs have a
131 ``has_<field>`` flag for each optional field. Use plain fields if field
132 presence detection is not needed.
133
134 .. code-block:: protobuf
135
136 syntax = "proto3";
137
138 message MyMessage {
139 // Leaving this field unset is equivalent to setting it to 0.
140 int32 number = 1;
141
142 // Setting this field to 0 is different from leaving it unset.
143 optional int32 other_number = 2;
144 }
145
Wyatt Hepler8779bcd2020-11-25 07:25:16 -08001462. RPC code generation
147----------------------
148``pw_rpc`` generates a C++ header file for each ``.proto`` file. This header is
149generated in the build output directory. Its exact location varies by build
150system and toolchain, but the C++ include path always matches the sources
151declaration in the ``pw_proto_library``. The ``.proto`` extension is replaced
152with an extension corresponding to the protobuf library in use.
Wyatt Hepler455b4922020-09-18 00:19:21 -0700153
Wyatt Hepler8779bcd2020-11-25 07:25:16 -0800154================== =============== =============== =============
155Protobuf libraries Build subtarget Protobuf header pw_rpc header
156================== =============== =============== =============
157Raw only .raw_rpc (none) .raw_rpc.pb.h
158Nanopb or raw .nanopb_rpc .pb.h .rpc.pb.h
159pw_protobuf or raw .pwpb_rpc .pwpb.h .rpc.pwpb.h
160================== =============== =============== =============
161
162For example, the generated RPC header for ``"foo_bar/the_service.proto"`` is
163``"foo_bar/the_service.rpc.pb.h"`` for Nanopb or
164``"foo_bar/the_service.raw_rpc.pb.h"`` for raw RPCs.
165
166The generated header defines a base class for each RPC service declared in the
167``.proto`` file. A service named ``TheService`` in package ``foo.bar`` would
Wyatt Heplerd2496322021-09-10 17:22:14 -0700168generate the following base class for Nanopb:
Wyatt Hepler455b4922020-09-18 00:19:21 -0700169
Wyatt Heplerd2496322021-09-10 17:22:14 -0700170.. cpp:class:: template <typename Implementation> foo::bar::pw_rpc::nanopb::TheService::Service
Wyatt Hepler455b4922020-09-18 00:19:21 -0700171
Wyatt Hepler8779bcd2020-11-25 07:25:16 -08001723. RPC service definition
173-------------------------
174The serivce class is implemented by inheriting from the generated RPC service
175base class and defining a method for each RPC. The methods must match the name
176and function signature for one of the supported protobuf implementations.
177Services may mix and match protobuf implementations within one service.
178
179.. tip::
180
181 The generated code includes RPC service implementation stubs. You can
182 reference or copy and paste these to get started with implementing a service.
183 These stub classes are generated at the bottom of the pw_rpc proto header.
184
Wyatt Heplerdf38ed12021-03-24 08:42:48 -0700185 To use the stubs, do the following:
186
187 #. Locate the generated RPC header in the build directory. For example:
188
189 .. code-block:: sh
190
191 find out/ -name <proto_name>.rpc.pb.h
192
193 #. Scroll to the bottom of the generated RPC header.
194 #. Copy the stub class declaration to a header file.
195 #. Copy the member function definitions to a source file.
196 #. Rename the class or change the namespace, if desired.
197 #. List these files in a build target with a dependency on the
198 ``pw_proto_library``.
199
Wyatt Hepler455b4922020-09-18 00:19:21 -0700200A Nanopb implementation of this service would be as follows:
201
202.. code-block:: cpp
203
Wyatt Hepler8779bcd2020-11-25 07:25:16 -0800204 #include "foo_bar/the_service.rpc.pb.h"
205
Wyatt Hepler455b4922020-09-18 00:19:21 -0700206 namespace foo::bar {
207
Wyatt Heplerd2496322021-09-10 17:22:14 -0700208 class TheService : public pw_rpc::nanopb::TheService::Service<TheService> {
Wyatt Hepler455b4922020-09-18 00:19:21 -0700209 public:
Wyatt Heplerebf33b72021-09-09 13:33:56 -0700210 pw::Status MethodOne(ServerContext&,
Wyatt Hepler455b4922020-09-18 00:19:21 -0700211 const foo_bar_Request& request,
212 foo_bar_Response& response) {
213 // implementation
Wyatt Hepler1b3da3a2021-01-07 13:26:57 -0800214 return pw::OkStatus();
Wyatt Hepler455b4922020-09-18 00:19:21 -0700215 }
216
Wyatt Heplerebf33b72021-09-09 13:33:56 -0700217 void MethodTwo(ServerContext&,
Wyatt Hepler455b4922020-09-18 00:19:21 -0700218 const foo_bar_Request& request,
219 ServerWriter<foo_bar_Response>& response) {
220 // implementation
221 response.Write(foo_bar_Response{.number = 123});
222 }
223 };
224
225 } // namespace foo::bar
226
227The Nanopb implementation would be declared in a ``BUILD.gn``:
228
229.. code-block:: python
230
231 import("//build_overrides/pigweed.gni")
232
233 import("$dir_pw_build/target_types.gni")
234
235 pw_source_set("the_service") {
236 public_configs = [ ":public" ]
237 public = [ "public/foo_bar/service.h" ]
Wyatt Hepler8779bcd2020-11-25 07:25:16 -0800238 public_deps = [ ":the_service_proto.nanopb_rpc" ]
Wyatt Hepler455b4922020-09-18 00:19:21 -0700239 }
240
241.. attention::
242
243 pw_rpc's generated classes will support using ``pw_protobuf`` or raw buffers
244 (no protobuf library) in the future.
245
Wyatt Hepler8779bcd2020-11-25 07:25:16 -08002464. Register the service with a server
Wyatt Hepler455b4922020-09-18 00:19:21 -0700247-------------------------------------
Alexei Frolovd3e5cb72021-01-08 13:08:45 -0800248This example code sets up an RPC server with an :ref:`HDLC<module-pw_hdlc>`
Wyatt Heplerf9fb90f2020-09-30 18:59:33 -0700249channel output and the example service.
Wyatt Hepler455b4922020-09-18 00:19:21 -0700250
251.. code-block:: cpp
252
253 // Set up the output channel for the pw_rpc server to use. This configures the
254 // pw_rpc server to use HDLC over UART; projects not using UART and HDLC must
255 // adapt this as necessary.
256 pw::stream::SysIoWriter writer;
257 pw::rpc::RpcChannelOutput<kMaxTransmissionUnit> hdlc_channel_output(
Alexei Frolovd3e5cb72021-01-08 13:08:45 -0800258 writer, pw::hdlc::kDefaultRpcAddress, "HDLC output");
Wyatt Hepler455b4922020-09-18 00:19:21 -0700259
260 pw::rpc::Channel channels[] = {
261 pw::rpc::Channel::Create<1>(&hdlc_channel_output)};
262
263 // Declare the pw_rpc server with the HDLC channel.
264 pw::rpc::Server server(channels);
265
266 pw::rpc::TheService the_service;
267
268 void RegisterServices() {
269 // Register the foo.bar.TheService example service.
270 server.Register(the_service);
271
272 // Register other services
273 }
274
275 int main() {
276 // Set up the server.
277 RegisterServices();
278
279 // Declare a buffer for decoding incoming HDLC frames.
280 std::array<std::byte, kMaxTransmissionUnit> input_buffer;
281
282 PW_LOG_INFO("Starting pw_rpc server");
Alexei Frolovd3e5cb72021-01-08 13:08:45 -0800283 pw::hdlc::ReadAndProcessPackets(
Wyatt Hepler455b4922020-09-18 00:19:21 -0700284 server, hdlc_channel_output, input_buffer);
285 }
Wyatt Hepler948f5472020-06-02 16:52:28 -0700286
Alexei Frolov1c670a22021-04-09 10:18:17 -0700287Channels
288========
289``pw_rpc`` sends all of its packets over channels. These are logical,
290application-layer routes used to tell the RPC system where a packet should go.
291
292Channels over a client-server connection must all have a unique ID, which can be
293assigned statically at compile time or dynamically.
294
295.. code-block:: cpp
296
297 // Creating a channel with the static ID 3.
298 pw::rpc::Channel static_channel = pw::rpc::Channel::Create<3>(&output);
299
300 // Grouping channel IDs within an enum can lead to clearer code.
301 enum ChannelId {
302 kUartChannel = 1,
303 kSpiChannel = 2,
304 };
305
306 // Creating a channel with a static ID defined within an enum.
307 pw::rpc::Channel another_static_channel =
308 pw::rpc::Channel::Create<ChannelId::kUartChannel>(&output);
309
310 // Creating a channel with a dynamic ID (note that no output is provided; it
311 // will be set when the channel is used.
312 pw::rpc::Channel dynamic_channel;
313
Alexei Frolov567e6702021-04-13 09:13:02 -0700314Sometimes, the ID and output of a channel are not known at compile time as they
315depend on information stored on the physical device. To support this use case, a
316dynamically-assignable channel can be configured once at runtime with an ID and
317output.
318
319.. code-block:: cpp
320
321 // Create a dynamic channel without a compile-time ID or output.
322 pw::rpc::Channel dynamic_channel;
323
324 void Init() {
325 // Called during boot to pull the channel configuration from the system.
326 dynamic_channel.Configure(GetChannelId(), some_output);
327 }
328
Alexei Frolov7c7a3862020-07-16 15:36:02 -0700329Services
330========
331A service is a logical grouping of RPCs defined within a .proto file. ``pw_rpc``
332uses these .proto definitions to generate code for a base service, from which
333user-defined RPCs are implemented.
334
335``pw_rpc`` supports multiple protobuf libraries, and the generated code API
336depends on which is used.
337
Wyatt Heplerf9fb90f2020-09-30 18:59:33 -0700338.. _module-pw_rpc-protobuf-library-apis:
Alexei Frolov4d2adde2020-08-04 10:19:24 -0700339
340Protobuf library APIs
341=====================
342
Alexei Frolov7c7a3862020-07-16 15:36:02 -0700343.. toctree::
344 :maxdepth: 1
345
346 nanopb/docs
347
348Testing a pw_rpc integration
349============================
350After setting up a ``pw_rpc`` server in your project, you can test that it is
351working as intended by registering the provided ``EchoService``, defined in
Wyatt Hepler752d7d32021-03-02 09:02:23 -0800352``echo.proto``, which echoes back a message that it receives.
Alexei Frolov7c7a3862020-07-16 15:36:02 -0700353
Wyatt Hepler752d7d32021-03-02 09:02:23 -0800354.. literalinclude:: echo.proto
Alexei Frolov7c7a3862020-07-16 15:36:02 -0700355 :language: protobuf
356 :lines: 14-
357
358For example, in C++ with nanopb:
359
360.. code:: c++
361
362 #include "pw_rpc/server.h"
363
364 // Include the apporpriate header for your protobuf library.
365 #include "pw_rpc/echo_service_nanopb.h"
366
367 constexpr pw::rpc::Channel kChannels[] = { /* ... */ };
368 static pw::rpc::Server server(kChannels);
369
370 static pw::rpc::EchoService echo_service;
371
372 void Init() {
Wyatt Hepler31b16ea2021-07-21 08:52:02 -0700373 server.RegisterService(echo_service);
Alexei Frolov7c7a3862020-07-16 15:36:02 -0700374 }
375
Wyatt Hepler31b16ea2021-07-21 08:52:02 -0700376Benchmarking and stress testing
377-------------------------------
378
379.. toctree::
380 :maxdepth: 1
381 :hidden:
382
383 benchmark
384
385``pw_rpc`` provides an RPC service and Python module for stress testing and
386benchmarking a ``pw_rpc`` deployment. See :ref:`module-pw_rpc-benchmark`.
387
Wyatt Hepler05d860d2021-09-22 09:43:10 -0700388Naming
389======
390
391Reserved names
392--------------
393``pw_rpc`` reserves a few service method names so they can be used for generated
394classes. The following names cannnot be used for service methods:
395
396- ``Client``
397- ``Service``
398- Any reserved words in the languages ``pw_rpc`` supports (e.g. ``class``).
399
400``pw_rpc`` does not reserve any service names, but the restriction of avoiding
401reserved words in supported languages applies.
402
403Service naming style
404--------------------
405``pw_rpc`` service names should use capitalized camel case and should not use
406the term "Service". Appending "Service" to a service name is redundant, similar
407to appending "Class" or "Function" to a class or function name. The
408C++ implementation class may use "Service" in its name, however.
409
410For example, a service for accessing a file system should simply be named
411``service FileSystem``, rather than ``service FileSystemService``, in the
412``.proto`` file.
413
414.. code-block:: protobuf
415
416 // file.proto
417 package pw.file;
418
419 service FileSystem {
420 rpc List(ListRequest) returns (stream ListResponse);
421 }
422
423The C++ service implementation class may append "Service" to the name.
424
425.. code-block:: cpp
426
427 // file_system_service.h
428 #include "pw_file/file.raw_rpc.pb.h"
429
430 namespace pw::file {
431
432 class FileSystemService : public pw_rpc::raw::FileSystem::Service<FileSystemService> {
433 void List(ServerContext&, ConstByteSpan request, RawServerWriter& writer);
434 };
435
436 }
437
438For upstream Pigweed services, this naming style is a requirement. Note that
439some services created before this was established may use non-compliant
440names. For Pigweed users, this naming style is a suggestion.
441
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700442Protocol description
443====================
444Pigweed RPC servers and clients communicate using ``pw_rpc`` packets. These
445packets are used to send requests and responses, control streams, cancel ongoing
446RPCs, and report errors.
447
448Packet format
449-------------
450Pigweed RPC packets consist of a type and a set of fields. The packets are
451encoded as protocol buffers. The full packet format is described in
Wyatt Heplerba325e42021-03-08 14:23:34 -0800452``pw_rpc/pw_rpc/internal/packet.proto``.
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700453
Wyatt Hepler752d7d32021-03-02 09:02:23 -0800454.. literalinclude:: internal/packet.proto
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700455 :language: protobuf
456 :lines: 14-
457
458The packet type and RPC type determine which fields are present in a Pigweed RPC
Wyatt Hepler0f262352020-07-29 09:51:27 -0700459packet. Each packet type is only sent by either the client or the server.
460These tables describe the meaning of and fields included with each packet type.
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700461
Wyatt Hepler0f262352020-07-29 09:51:27 -0700462Client-to-server packets
463^^^^^^^^^^^^^^^^^^^^^^^^
Wyatt Heplera9211162021-06-12 15:40:11 -0700464+-------------------+-------------------------------------+
465| packet type | description |
466+===================+=====================================+
467| REQUEST | Invoke an RPC |
468| | |
469| | .. code-block:: text |
470| | |
471| | - channel_id |
472| | - service_id |
473| | - method_id |
474| | - payload |
475| | (unary & server streaming only) |
Alexei Frolov86e05de2021-10-19 16:52:31 -0700476| | - call_id (optional) |
Wyatt Heplera9211162021-06-12 15:40:11 -0700477| | |
478+-------------------+-------------------------------------+
479| CLIENT_STREAM | Message in a client stream |
480| | |
481| | .. code-block:: text |
482| | |
483| | - channel_id |
484| | - service_id |
485| | - method_id |
486| | - payload |
Alexei Frolov86e05de2021-10-19 16:52:31 -0700487| | - call_id (if set in REQUEST) |
Wyatt Heplera9211162021-06-12 15:40:11 -0700488| | |
489+-------------------+-------------------------------------+
Wyatt Hepler5ba80642021-06-18 12:56:17 -0700490| CLIENT_STREAM_END | Client stream is complete |
491| | |
492| | .. code-block:: text |
493| | |
494| | - channel_id |
495| | - service_id |
496| | - method_id |
Alexei Frolov86e05de2021-10-19 16:52:31 -0700497| | - call_id (if set in REQUEST) |
Wyatt Hepler5ba80642021-06-18 12:56:17 -0700498| | |
499+-------------------+-------------------------------------+
Wyatt Hepler17169152021-10-20 18:46:08 -0700500| CLIENT_ERROR | Abort an ongoing RPC |
Wyatt Heplera9211162021-06-12 15:40:11 -0700501| | |
502| | .. code-block:: text |
503| | |
504| | - channel_id |
505| | - service_id |
506| | - method_id |
507| | - status |
Alexei Frolov86e05de2021-10-19 16:52:31 -0700508| | - call_id (if set in REQUEST) |
Wyatt Heplera9211162021-06-12 15:40:11 -0700509| | |
510+-------------------+-------------------------------------+
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700511
Wyatt Hepler82db4b12021-09-23 09:10:12 -0700512**Client errors**
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700513
Wyatt Hepler0f262352020-07-29 09:51:27 -0700514The client sends ``CLIENT_ERROR`` packets to a server when it receives a packet
Wyatt Hepler82db4b12021-09-23 09:10:12 -0700515it did not request. If possible, the server should abort it.
Wyatt Hepler0f262352020-07-29 09:51:27 -0700516
Wyatt Heplera9211162021-06-12 15:40:11 -0700517The status code indicates the type of error. The status code is logged, but all
518status codes result in the same action by the server: aborting the RPC.
Wyatt Hepler0f262352020-07-29 09:51:27 -0700519
Wyatt Hepler17169152021-10-20 18:46:08 -0700520* ``CANCELLED`` -- The client requested that the RPC be cancelled.
Wyatt Hepler0f262352020-07-29 09:51:27 -0700521* ``NOT_FOUND`` -- Received a packet for a service method the client does not
522 recognize.
523* ``FAILED_PRECONDITION`` -- Received a packet for a service method that the
524 client did not invoke.
Wyatt Hepler35240da2021-07-21 08:51:22 -0700525* ``DATA_LOSS`` -- Received a corrupt packet for a pending service method.
Wyatt Hepler82db4b12021-09-23 09:10:12 -0700526* ``INVALID_ARGUMENT`` -- The server sent a packet type to an RPC that does not
527 support it (a ``SERVER_STREAM`` was sent to an RPC with no server stream).
Wyatt Hepler0f262352020-07-29 09:51:27 -0700528
529Server-to-client packets
530^^^^^^^^^^^^^^^^^^^^^^^^
Wyatt Heplera9211162021-06-12 15:40:11 -0700531+-------------------+-------------------------------------+
532| packet type | description |
533+===================+=====================================+
Wyatt Hepler5ba80642021-06-18 12:56:17 -0700534| RESPONSE | The RPC is complete |
535| | |
536| | .. code-block:: text |
537| | |
538| | - channel_id |
539| | - service_id |
540| | - method_id |
541| | - status |
542| | - payload |
543| | (unary & client streaming only) |
Alexei Frolov86e05de2021-10-19 16:52:31 -0700544| | - call_id (if set in REQUEST) |
Wyatt Hepler5ba80642021-06-18 12:56:17 -0700545| | |
546+-------------------+-------------------------------------+
547| SERVER_STREAM | Message in a server stream |
Wyatt Heplera9211162021-06-12 15:40:11 -0700548| | |
549| | .. code-block:: text |
550| | |
551| | - channel_id |
552| | - service_id |
553| | - method_id |
554| | - payload |
Alexei Frolov86e05de2021-10-19 16:52:31 -0700555| | - call_id (if set in REQUEST) |
Wyatt Heplera9211162021-06-12 15:40:11 -0700556| | |
557+-------------------+-------------------------------------+
558| SERVER_ERROR | Received unexpected packet |
559| | |
560| | .. code-block:: text |
561| | |
562| | - channel_id |
563| | - service_id (if relevant) |
564| | - method_id (if relevant) |
565| | - status |
Alexei Frolov86e05de2021-10-19 16:52:31 -0700566| | - call_id (if set in REQUEST) |
Wyatt Heplera9211162021-06-12 15:40:11 -0700567| | |
568+-------------------+-------------------------------------+
Wyatt Hepler0f262352020-07-29 09:51:27 -0700569
Alexei Frolov86e05de2021-10-19 16:52:31 -0700570All server packets contain the same client ID that was set in the initial
571request made by the client, if any.
572
Wyatt Hepler82db4b12021-09-23 09:10:12 -0700573**Server errors**
Wyatt Hepler0f262352020-07-29 09:51:27 -0700574
575The server sends ``SERVER_ERROR`` packets when it receives a packet it cannot
576process. The client should abort any RPC for which it receives an error. The
577status field indicates the type of error.
578
579* ``NOT_FOUND`` -- The requested service or method does not exist.
Wyatt Heplera9211162021-06-12 15:40:11 -0700580* ``FAILED_PRECONDITION`` -- A client stream or cancel packet was sent for an
581 RPC that is not pending.
Wyatt Hepler01fc15b2021-06-10 18:15:59 -0700582* ``INVALID_ARGUMENT`` -- The client sent a packet type to an RPC that does not
Wyatt Hepler82db4b12021-09-23 09:10:12 -0700583 support it (a ``CLIENT_STREAM`` was sent to an RPC with no client stream).
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700584* ``RESOURCE_EXHAUSTED`` -- The request came on a new channel, but a channel
585 could not be allocated for it.
Wyatt Hepler712d3672020-07-13 15:52:11 -0700586* ``INTERNAL`` -- The server was unable to respond to an RPC due to an
587 unrecoverable internal error.
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700588
589Inovking a service method
590-------------------------
591Calling an RPC requires a specific sequence of packets. This section describes
592the protocol for calling service methods of each type: unary, server streaming,
593client streaming, and bidirectional streaming.
594
Wyatt Hepler5ba80642021-06-18 12:56:17 -0700595The basic flow for all RPC invocations is as follows:
596
597 * Client sends a ``REQUEST`` packet. Includes a payload for unary & server
598 streaming RPCs.
599 * For client and bidirectional streaming RPCs, the client may send any number
600 of ``CLIENT_STREAM`` packets with payloads.
601 * For server and bidirectional streaming RPCs, the server may send any number
602 of ``SERVER_STREAM`` packets.
603 * The server sends a ``RESPONSE`` packet. Includes a payload for unary &
604 client streaming RPCs. The RPC is complete.
605
Wyatt Hepler17169152021-10-20 18:46:08 -0700606The client may cancel an ongoing RPC at any time by sending a ``CLIENT_ERROR``
607packet with status ``CANCELLED``. The server may finish an ongoing RPC at any
608time by sending the ``RESPONSE`` packet.
Wyatt Hepler5ba80642021-06-18 12:56:17 -0700609
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700610Unary RPC
611^^^^^^^^^
612In a unary RPC, the client sends a single request and the server sends a single
613response.
614
Wyatt Hepler1d221242021-09-07 15:42:21 -0700615.. image:: unary_rpc.svg
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700616
Wyatt Hepler17169152021-10-20 18:46:08 -0700617The client may attempt to cancel a unary RPC by sending a ``CLIENT_ERROR``
618packet with status ``CANCELLED``. The server sends no response to a cancelled
619RPC. If the server processes the unary RPC synchronously (the handling thread
620sends the response), it may not be possible to cancel the RPC.
Wyatt Heplera9211162021-06-12 15:40:11 -0700621
Wyatt Hepler1d221242021-09-07 15:42:21 -0700622.. image:: unary_rpc_cancelled.svg
Wyatt Heplera9211162021-06-12 15:40:11 -0700623
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700624Server streaming RPC
625^^^^^^^^^^^^^^^^^^^^
626In a server streaming RPC, the client sends a single request and the server
Wyatt Hepler5ba80642021-06-18 12:56:17 -0700627sends any number of ``SERVER_STREAM`` packets followed by a ``RESPONSE`` packet.
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700628
Wyatt Hepler1d221242021-09-07 15:42:21 -0700629.. image:: server_streaming_rpc.svg
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700630
Wyatt Hepler17169152021-10-20 18:46:08 -0700631The client may terminate a server streaming RPC by sending a ``CLIENT_STREAM``
632packet with status ``CANCELLED``. The server sends no response.
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700633
Wyatt Hepler1d221242021-09-07 15:42:21 -0700634.. image:: server_streaming_rpc_cancelled.svg
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700635
636Client streaming RPC
637^^^^^^^^^^^^^^^^^^^^
Wyatt Heplera9211162021-06-12 15:40:11 -0700638In a client streaming RPC, the client starts the RPC by sending a ``REQUEST``
639packet with no payload. It then sends any number of messages in
640``CLIENT_STREAM`` packets, followed by a ``CLIENT_STREAM_END``. The server sends
Wyatt Hepler5ba80642021-06-18 12:56:17 -0700641a single ``RESPONSE`` to finish the RPC.
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700642
Wyatt Hepler1d221242021-09-07 15:42:21 -0700643.. image:: client_streaming_rpc.svg
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700644
Wyatt Heplera9211162021-06-12 15:40:11 -0700645The server may finish the RPC at any time by sending its ``RESPONSE`` packet,
646even if it has not yet received the ``CLIENT_STREAM_END`` packet. The client may
Wyatt Hepler17169152021-10-20 18:46:08 -0700647terminate the RPC at any time by sending a ``CLIENT_ERROR`` packet with status
648``CANCELLED``.
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700649
Wyatt Hepler1d221242021-09-07 15:42:21 -0700650.. image:: client_streaming_rpc_cancelled.svg
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700651
652Bidirectional streaming RPC
653^^^^^^^^^^^^^^^^^^^^^^^^^^^
654In a bidirectional streaming RPC, the client sends any number of requests and
Wyatt Heplera9211162021-06-12 15:40:11 -0700655the server sends any number of responses. The client invokes the RPC by sending
656a ``REQUEST`` with no payload. It sends a ``CLIENT_STREAM_END`` packet when it
Wyatt Hepler5ba80642021-06-18 12:56:17 -0700657has finished sending requests. The server sends a ``RESPONSE`` packet to finish
658the RPC.
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700659
Wyatt Hepler1d221242021-09-07 15:42:21 -0700660.. image:: bidirectional_streaming_rpc.svg
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700661
Wyatt Hepler5ba80642021-06-18 12:56:17 -0700662The server may finish the RPC at any time by sending the ``RESPONSE`` packet,
663even if it has not received the ``CLIENT_STREAM_END`` packet. The client may
Wyatt Hepler17169152021-10-20 18:46:08 -0700664terminate the RPC at any time by sending a ``CLIENT_ERROR`` packet with status
665``CANCELLED``.
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700666
Wyatt Hepler1d221242021-09-07 15:42:21 -0700667.. image:: bidirectional_streaming_rpc_cancelled.svg
Wyatt Hepler067dd7e2020-07-14 19:34:32 -0700668
Wyatt Hepler948f5472020-06-02 16:52:28 -0700669RPC server
670==========
671Declare an instance of ``rpc::Server`` and register services with it.
672
673.. admonition:: TODO
674
675 Document the public interface
676
Alexei Frolovbf33d212020-09-15 17:13:45 -0700677Size report
678-----------
679The following size report showcases the memory usage of the core RPC server. It
680is configured with a single channel using a basic transport interface that
681directly reads from and writes to ``pw_sys_io``. The transport has a 128-byte
682packet buffer, which comprises the plurality of the example's RAM usage. This is
683not a suitable transport for an actual product; a real implementation would have
684additional overhead proportional to the complexity of the transport.
685
686.. include:: server_size
687
Wyatt Hepler948f5472020-06-02 16:52:28 -0700688RPC server implementation
689-------------------------
690
691The Method class
692^^^^^^^^^^^^^^^^
693The RPC Server depends on the ``pw::rpc::internal::Method`` class. ``Method``
694serves as the bridge between the ``pw_rpc`` server library and the user-defined
Wyatt Heplere95bd722020-11-23 07:49:47 -0800695RPC functions. Each supported protobuf implementation extends ``Method`` to
696implement its request and response proto handling. The ``pw_rpc`` server
697calls into the ``Method`` implementation through the base class's ``Invoke``
698function.
Wyatt Hepler948f5472020-06-02 16:52:28 -0700699
Wyatt Heplere95bd722020-11-23 07:49:47 -0800700``Method`` implementations store metadata about each method, including a
701function pointer to the user-defined method implementation. They also provide
702``static constexpr`` functions for creating each type of method. ``Method``
703implementations must satisfy the ``MethodImplTester`` test class in
Wyatt Heplerfa6edcc2021-08-20 08:30:08 -0700704``pw_rpc/internal/method_impl_tester.h``.
Wyatt Hepler948f5472020-06-02 16:52:28 -0700705
Wyatt Heplere95bd722020-11-23 07:49:47 -0800706See ``pw_rpc/internal/method.h`` for more details about ``Method``.
Wyatt Hepler948f5472020-06-02 16:52:28 -0700707
708Packet flow
709^^^^^^^^^^^
710
711Requests
712~~~~~~~~
713
Wyatt Hepler1d221242021-09-07 15:42:21 -0700714.. image:: request_packets.svg
Wyatt Hepler948f5472020-06-02 16:52:28 -0700715
716Responses
717~~~~~~~~~
718
Wyatt Hepler1d221242021-09-07 15:42:21 -0700719.. image:: response_packets.svg
Alexei Frolov4d2adde2020-08-04 10:19:24 -0700720
721RPC client
722==========
723The RPC client is used to send requests to a server and manages the contexts of
724ongoing RPCs.
725
726Setting up a client
727-------------------
728The ``pw::rpc::Client`` class is instantiated with a list of channels that it
729uses to communicate. These channels can be shared with a server, but multiple
730clients cannot use the same channels.
731
732To send incoming RPC packets from the transport layer to be processed by a
733client, the client's ``ProcessPacket`` function is called with the packet data.
734
735.. code:: c++
736
737 #include "pw_rpc/client.h"
738
739 namespace {
740
741 pw::rpc::Channel my_channels[] = {
742 pw::rpc::Channel::Create<1>(&my_channel_output)};
743 pw::rpc::Client my_client(my_channels);
744
745 } // namespace
746
747 // Called when the transport layer receives an RPC packet.
748 void ProcessRpcPacket(ConstByteSpan packet) {
749 my_client.ProcessPacket(packet);
750 }
751
Alexei Frolov5a3a61c2020-10-01 18:51:41 -0700752.. _module-pw_rpc-making-calls:
753
Alexei Frolov4d2adde2020-08-04 10:19:24 -0700754Making RPC calls
755----------------
756RPC calls are not made directly through the client, but using one of its
757registered channels instead. A service client class is generated from a .proto
758file for each selected protobuf library, which is then used to send RPC requests
759through a given channel. The API for this depends on the protobuf library;
Wyatt Heplerf9fb90f2020-09-30 18:59:33 -0700760please refer to the
761:ref:`appropriate documentation<module-pw_rpc-protobuf-library-apis>`. Multiple
762service client implementations can exist simulatenously and share the same
763``Client`` class.
Alexei Frolov4d2adde2020-08-04 10:19:24 -0700764
765When a call is made, a ``pw::rpc::ClientCall`` object is returned to the caller.
766This object tracks the ongoing RPC call, and can be used to manage it. An RPC
767call is only active as long as its ``ClientCall`` object is alive.
768
769.. tip::
770 Use ``std::move`` when passing around ``ClientCall`` objects to keep RPCs
771 alive.
772
Alexei Frolov2d737bc2021-04-27 23:03:09 -0700773Example
774^^^^^^^
775.. code-block:: c++
776
777 #include "pw_rpc/echo_service_nanopb.h"
778
779 namespace {
Alexei Frolov2b54ee62021-04-29 14:58:21 -0700780 // Generated clients are namespaced with their proto library.
781 using pw::rpc::nanopb::EchoServiceClient;
782
Alexei Frolov73687fb2021-09-03 11:22:33 -0700783 // RPC channel ID on which to make client calls.
784 constexpr uint32_t kDefaultChannelId = 1;
785
Alexei Frolov2b54ee62021-04-29 14:58:21 -0700786 EchoServiceClient::EchoCall echo_call;
Alexei Frolovbebba902021-06-09 17:03:52 -0700787
788 // Callback invoked when a response is received. This is called synchronously
789 // from Client::ProcessPacket.
790 void EchoResponse(const pw_rpc_EchoMessage& response,
791 pw::Status status) {
792 if (status.ok()) {
793 PW_LOG_INFO("Received echo response: %s", response.msg);
794 } else {
795 PW_LOG_ERROR("Echo failed with status %d",
796 static_cast<int>(status.code()));
797 }
798 }
Alexei Frolov2d737bc2021-04-27 23:03:09 -0700799
800 } // namespace
801
802 void CallEcho(const char* message) {
Alexei Frolov73687fb2021-09-03 11:22:33 -0700803 // Create a client to call the EchoService.
804 EchoServiceClient echo_client(my_rpc_client, kDefaultChannelId);
805
Alexei Frolov2d737bc2021-04-27 23:03:09 -0700806 pw_rpc_EchoMessage request = pw_rpc_EchoMessage_init_default;
807 pw::string::Copy(message, request.msg);
808
809 // By assigning the returned ClientCall to the global echo_call, the RPC
810 // call is kept alive until it completes. When a response is received, it
811 // will be logged by the handler function and the call will complete.
Alexei Frolov73687fb2021-09-03 11:22:33 -0700812 echo_call = echo_client.Echo(request, EchoResponse);
813 if (!echo_call.active()) {
814 // The RPC call was not sent. This could occur due to, for example, an
815 // invalid channel ID. Handle if necessary.
816 }
Alexei Frolov2d737bc2021-04-27 23:03:09 -0700817 }
818
Alexei Frolov4d2adde2020-08-04 10:19:24 -0700819Client implementation details
820-----------------------------
821
822The ClientCall class
823^^^^^^^^^^^^^^^^^^^^
824``ClientCall`` stores the context of an active RPC, and serves as the user's
825interface to the RPC client. The core RPC library provides a base ``ClientCall``
826class with common functionality, which is then extended for RPC client
827implementations tied to different protobuf libraries to provide convenient
828interfaces for working with RPCs.
829
830The RPC server stores a list of all of active ``ClientCall`` objects. When an
831incoming packet is recieved, it dispatches to one of its active calls, which
832then decodes the payload and presents it to the user.
Alexei Frolov3e280922021-04-12 14:53:06 -0700833
834ClientServer
835============
836Sometimes, a device needs to both process RPCs as a server, as well as making
837calls to another device as a client. To do this, both a client and server must
838be set up, and incoming packets must be sent to both of them.
839
840Pigweed simplifies this setup by providing a ``ClientServer`` class which wraps
841an RPC client and server with the same set of channels.
842
843.. code-block:: cpp
844
845 pw::rpc::Channel channels[] = {
846 pw::rpc::Channel::Create<1>(&channel_output)};
847
848 // Creates both a client and a server.
849 pw::rpc::ClientServer client_server(channels);
850
851 void ProcessRpcData(pw::ConstByteSpan packet) {
852 // Calls into both the client and the server, sending the packet to the
853 // appropriate one.
854 client_server.ProcessPacket(packet, output);
855 }
Wyatt Hepler9732a8e2021-11-10 16:31:41 -0800856
857Unit testing
858============
859``pw_rpc`` provides utilities for unit testing RPC services and client calls.
860
861Client testing in C++
862---------------------
863``pw_rpc`` supports invoking RPCs, simulating server responses, and checking
864what packets are sent by an RPC client in tests. Both raw and Nanopb interfaces
865are supported. Code that uses the raw API may be tested with the Nanopb test
866helpers, and vice versa.
867
868To test code that invokes RPCs, declare a ``RawClientTestContext`` or
869``NanopbClientTestContext``. These test context objects provide a
870preconfigured RPC client, channel, server fake, and buffer for encoding packets.
871These test classes are defined in ``pw_rpc/raw/client_testing.h`` and
872``pw_rpc/nanopb/client_testing.h``.
873
874Use the context's ``client()`` and ``channel()`` to invoke RPCs. Use the
875context's ``server()`` to simulate responses. To verify that the client sent the
876expected data, use the context's ``output()``, which is a ``FakeChannelOutput``.
877
878For example, the following tests a class that invokes an RPC. It checks that
879the expected data was sent and then simulates a response from the server.
880
881.. code-block:: cpp
882
883 #include "pw_rpc/raw/client_testing.h"
884
885 class ThingThatCallsRpcs {
886 public:
887 // To support injecting an RPC client for testing, classes that make RPC
888 // calls should take an RPC client and channel ID or an RPC service client
889 // (e.g. pw_rpc::raw::MyService::Client).
890 ThingThatCallsRpcs(pw::rpc::Client& client, uint32_t channel_id);
891
892 void DoSomethingThatInvokesAnRpc();
893
894 bool SetToTrueWhenRpcCompletes();
895 };
896
897 TEST(TestAThing, InvokesRpcAndHandlesResponse) {
898 RawClientTestContext context;
899 ThingThatCallsRpcs thing(context.client(), context.channel().id());
900
901 // Execute the code that invokes the MyService.TheMethod RPC.
902 things.DoSomethingThatInvokesAnRpc();
903
904 // Find and verify the payloads sent for the MyService.TheMethod RPC.
905 auto msgs = context.output().payloads<pw_rpc::raw::MyService::TheMethod>();
906 ASSERT_EQ(msgs.size(), 1u);
907
908 VerifyThatTheExpectedMessageWasSent(msgs.back());
909
910 // Send the response packet from the server and verify that the class reacts
911 // accordingly.
912 EXPECT_FALSE(thing.SetToTrueWhenRpcCompletes());
913
914 context_.server().SendResponse<pw_rpc::raw::MyService::TheMethod>(
915 final_message, OkStatus());
916
917 EXPECT_TRUE(thing.SetToTrueWhenRpcCompletes());
918 }
Ewout van Bekkum7f5b3052021-11-11 17:35:23 -0800919
920Module Configuration Options
921============================
922The following configurations can be adjusted via compile-time configuration of
923this module, see the
924:ref:`module documentation <module-structure-compile-time-configuration>` for
925more details.
926
927.. c:macro:: PW_RPC_CLIENT_STREAM_END_CALLBACK
928
929 In client and bidirectional RPCs, pw_rpc clients may signal that they have
930 finished sending requests with a CLIENT_STREAM_END packet. While this can be
931 useful in some circumstances, it is often not necessary.
932
933 This option controls whether or not include a callback that is called when
934 the client stream ends. The callback is included in all ServerReader/Writer
935 objects as a pw::Function, so may have a significant cost.
936
937 This is disabled by default.
938
939.. c:macro:: PW_RPC_NANOPB_STRUCT_MIN_BUFFER_SIZE
940
941 The Nanopb-based pw_rpc implementation allocates memory to use for Nanopb
942 structs for the request and response protobufs. The template function that
943 allocates these structs rounds struct sizes up to this value so that
944 different structs can be allocated with the same function. Structs with sizes
945 larger than this value cause an extra function to be created, which slightly
946 increases code size.
947
948 Ideally, this value will be set to the size of the largest Nanopb struct used
949 as an RPC request or response. The buffer can be stack or globally allocated
950 (see ``PW_RPC_NANOPB_STRUCT_BUFFER_STACK_ALLOCATE``).
951
952 This defaults to 64 Bytes.
953
954.. c:macro:: PW_RPC_USE_GLOBAL_MUTEX
955
956 Enable global synchronization for RPC calls. If this is set, a backend must
957 be configured for pw_sync:mutex.
958
959 This is disabled by default.
960
961.. c:macro:: PW_RPC_CONFIG_LOG_LEVEL
962
963 The log level to use for this module. Logs below this level are omitted.
964
965 This defaults to ``PW_LOG_LEVEL_INFO``.
966
967.. c:macro:: PW_RPC_CONFIG_LOG_MODULE_NAME
968
969 The log module name to use for this module.
970
971 This defaults to ``"PW_RPC"``.
972
973.. c:macro:: PW_RPC_NANOPB_STRUCT_BUFFER_STACK_ALLOCATE
974
975 This option determines whether to allocate the Nanopb structs on the stack or
976 in a global variable. Globally allocated structs are NOT thread safe, but
977 work fine when the RPC server's ProcessPacket function is only called from
978 one thread.
979
980 This is enabled by default.
Wyatt Hepler14439762021-11-09 09:16:32 -0800981
982Sharing server and client code
983==============================
984Streaming RPCs support writing multiple requests or responses. To facilitate
985sharing code between servers and clients, ``pw_rpc`` provides the
986``pw::rpc::Writer`` interface. On the client side, a client or bidirectional
987streaming RPC call object (``ClientWriter`` or ``ClientReaderWriter``) can be
988used as a ``pw::rpc::Writer&``. On the server side, a server or bidirectional
989streaming RPC call object (``ServerWriter`` or ``ServerReaderWriter``) can be
990used as a ``pw::rpc::Writer&``.