aboutsummaryrefslogtreecommitdiff
path: root/pw_rpc/pwpb/public/pw_rpc/pwpb/internal/method.h
blob: a8a7b99035a04ef99e99aa4a56c9fe9f35aa20c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
// Copyright 2022 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#pragma once

#include <cstddef>
#include <cstdint>
#include <type_traits>

#include "pw_bytes/span.h"
#include "pw_rpc/internal/call_context.h"
#include "pw_rpc/internal/lock.h"
#include "pw_rpc/internal/method.h"
#include "pw_rpc/internal/packet.h"
#include "pw_rpc/method_type.h"
#include "pw_rpc/pwpb/internal/common.h"
#include "pw_rpc/pwpb/server_reader_writer.h"
#include "pw_rpc/service.h"
#include "pw_span/span.h"
#include "pw_status/status_with_size.h"

namespace pw::rpc::internal {

// Expected function signatures for user-implemented RPC functions.
template <typename Request, typename Response>
using PwpbSynchronousUnary = Status(const Request&, Response&);

template <typename Request, typename Response>
using PwpbAsynchronousUnary = void(const Request&,
                                   PwpbUnaryResponder<Response>&);

template <typename Request, typename Response>
using PwpbServerStreaming = void(const Request&, PwpbServerWriter<Response>&);

template <typename Request, typename Response>
using PwpbClientStreaming = void(PwpbServerReader<Request, Response>&);

template <typename Request, typename Response>
using PwpbBidirectionalStreaming =
    void(PwpbServerReaderWriter<Request, Response>&);

// The PwpbMethod class invokes user-defined service methods. When a
// pw::rpc::Server receives an RPC request packet, it looks up the matching
// PwpbMethod instance and calls its Invoke method, which eventually calls into
// the user-defined RPC function.
//
// A PwpbMethod instance is created for each user-defined RPC in the pw_rpc
// generated code. The PwpbMethod stores a pointer to the RPC function,
// a pointer to an "invoker" function that calls that function, and a
// reference to a serializer/deserializer initiiated with the message struct
// tables used to encode and decode request and response message structs.
class PwpbMethod : public Method {
 public:
  template <auto kMethod, typename RequestType, typename ResponseType>
  static constexpr bool matches() {
    return std::conjunction_v<
        std::is_same<MethodImplementation<kMethod>, PwpbMethod>,
        std::is_same<RequestType, Request<kMethod>>,
        std::is_same<ResponseType, Response<kMethod>>>;
  }

  // Creates a PwpbMethod for a synchronous unary RPC.
  // TODO: b/234874001 - Find a way to reduce the number of monomorphized copies
  // of this method.
  template <auto kMethod>
  static constexpr PwpbMethod SynchronousUnary(uint32_t id,
                                               const PwpbMethodSerde& serde) {
    // Define a wrapper around the user-defined function that takes the
    // request and response protobuf structs as byte spans, and calls the
    // implementation with the correct type.
    //
    // This wrapper is stored generically in the Function union, defined below.
    // In optimized builds, the compiler inlines the user-defined function into
    // this wrapper, eliminating any overhead.
    constexpr SynchronousUnaryFunction wrapper =
        [](Service& service, const void* request, void* response) {
          return CallMethodImplFunction<kMethod>(
              service,
              *reinterpret_cast<const Request<kMethod>*>(request),
              *reinterpret_cast<Response<kMethod>*>(response));
        };
    return PwpbMethod(
        id,
        SynchronousUnaryInvoker<Request<kMethod>, Response<kMethod>>,
        Function{.synchronous_unary = wrapper},
        serde);
  }

  // Creates a PwpbMethod for an asynchronous unary RPC.
  // TODO: b/234874001 - Find a way to reduce the number of monomorphized copies
  // of this method.
  template <auto kMethod>
  static constexpr PwpbMethod AsynchronousUnary(uint32_t id,
                                                const PwpbMethodSerde& serde) {
    // Define a wrapper around the user-defined function that takes the
    // request struct as a byte span, the response as a server call, and calls
    // the implementation with the correct types.
    //
    // This wrapper is stored generically in the Function union, defined below.
    // In optimized builds, the compiler inlines the user-defined function into
    // this wrapper, eliminating any overhead.
    constexpr UnaryRequestFunction wrapper =
        [](Service& service,
           const void* request,
           internal::PwpbServerCall& writer) {
          return CallMethodImplFunction<kMethod>(
              service,
              *reinterpret_cast<const Request<kMethod>*>(request),
              static_cast<PwpbUnaryResponder<Response<kMethod>>&>(writer));
        };
    return PwpbMethod(id,
                      AsynchronousUnaryInvoker<Request<kMethod>>,
                      Function{.unary_request = wrapper},
                      serde);
  }

  // Creates a PwpbMethod for a server-streaming RPC.
  template <auto kMethod>
  static constexpr PwpbMethod ServerStreaming(uint32_t id,
                                              const PwpbMethodSerde& serde) {
    // Define a wrapper around the user-defined function that takes the
    // request struct as a byte span, the response as a server call, and calls
    // the implementation with the correct types.
    //
    // This wrapper is stored generically in the Function union, defined below.
    // In optimized builds, the compiler inlines the user-defined function into
    // this wrapper, eliminating any overhead.
    constexpr UnaryRequestFunction wrapper =
        [](Service& service,
           const void* request,
           internal::PwpbServerCall& writer) {
          return CallMethodImplFunction<kMethod>(
              service,
              *reinterpret_cast<const Request<kMethod>*>(request),
              static_cast<PwpbServerWriter<Response<kMethod>>&>(writer));
        };
    return PwpbMethod(id,
                      ServerStreamingInvoker<Request<kMethod>>,
                      Function{.unary_request = wrapper},
                      serde);
  }

  // Creates a PwpbMethod for a client-streaming RPC.
  template <auto kMethod>
  static constexpr PwpbMethod ClientStreaming(uint32_t id,
                                              const PwpbMethodSerde& serde) {
    // Define a wrapper around the user-defined function that takes the
    // request as a server call, and calls the implementation with the correct
    // types.
    //
    // This wrapper is stored generically in the Function union, defined below.
    // In optimized builds, the compiler inlines the user-defined function into
    // this wrapper, eliminating any overhead.
    constexpr StreamRequestFunction wrapper = [](Service& service,
                                                 internal::PwpbServerCall&
                                                     reader) {
      return CallMethodImplFunction<kMethod>(
          service,
          static_cast<PwpbServerReader<Request<kMethod>, Response<kMethod>>&>(
              reader));
    };
    return PwpbMethod(id,
                      ClientStreamingInvoker<Request<kMethod>>,
                      Function{.stream_request = wrapper},
                      serde);
  }

  // Creates a PwpbMethod for a bidirectional-streaming RPC.
  template <auto kMethod>
  static constexpr PwpbMethod BidirectionalStreaming(
      uint32_t id, const PwpbMethodSerde& serde) {
    // Define a wrapper around the user-defined function that takes the
    // request and response as a server call, and calls the implementation with
    // the correct types.
    //
    // This wrapper is stored generically in the Function union, defined below.
    // In optimized builds, the compiler inlines the user-defined function into
    // this wrapper, eliminating any overhead.
    constexpr StreamRequestFunction wrapper =
        [](Service& service, internal::PwpbServerCall& reader_writer) {
          return CallMethodImplFunction<kMethod>(
              service,
              static_cast<
                  PwpbServerReaderWriter<Request<kMethod>, Response<kMethod>>&>(
                  reader_writer));
        };
    return PwpbMethod(id,
                      BidirectionalStreamingInvoker<Request<kMethod>>,
                      Function{.stream_request = wrapper},
                      serde);
  }

  // Represents an invalid method. Used to reduce error message verbosity.
  static constexpr PwpbMethod Invalid() {
    return {0, InvalidInvoker, {}, PwpbMethodSerde(nullptr, nullptr)};
  }

  // Give access to the serializer/deserializer object for converting requests
  // and responses between the wire format and pw_protobuf structs.
  const PwpbMethodSerde& serde() const { return serde_; }

 private:
  // Generic function signature for synchronous unary RPCs.
  using SynchronousUnaryFunction = Status (*)(Service&,
                                              const void* request,
                                              void* response);

  // Generic function signature for asynchronous unary and server streaming
  // RPCs.
  using UnaryRequestFunction = void (*)(Service&,
                                        const void* request,
                                        internal::PwpbServerCall& writer);

  // Generic function signature for client and bidirectional streaming RPCs.
  using StreamRequestFunction =
      void (*)(Service&, internal::PwpbServerCall& reader_writer);

  // The Function union stores a pointer to a generic version of the
  // user-defined RPC function. Using a union instead of void* avoids
  // reinterpret_cast, which keeps this class fully constexpr.
  union Function {
    SynchronousUnaryFunction synchronous_unary;
    UnaryRequestFunction unary_request;
    StreamRequestFunction stream_request;
  };

  constexpr PwpbMethod(uint32_t id,
                       Invoker invoker,
                       Function function,
                       const PwpbMethodSerde& serde)
      : Method(id, invoker), function_(function), serde_(serde) {}

  template <typename Request, typename Response>
  void CallSynchronousUnary(const CallContext& context,
                            const Packet& request,
                            Request& request_struct,
                            Response& response_struct) const
      PW_UNLOCK_FUNCTION(rpc_lock()) {
    if (!DecodeRequest(context, request, request_struct).ok()) {
      context.server().CleanUpCalls();
      return;
    }

    internal::PwpbServerCall responder(context.ClaimLocked(),
                                       MethodType::kUnary);
    context.server().CleanUpCalls();
    const Status status = function_.synchronous_unary(
        context.service(), &request_struct, &response_struct);
    responder.SendUnaryResponse(response_struct, status).IgnoreError();
  }

  template <typename Request>
  void CallUnaryRequest(const CallContext& context,
                        MethodType method_type,
                        const Packet& request,
                        Request& request_struct) const
      PW_UNLOCK_FUNCTION(rpc_lock()) {
    if (!DecodeRequest(context, request, request_struct).ok()) {
      context.server().CleanUpCalls();
      return;
    }

    internal::PwpbServerCall server_writer(context.ClaimLocked(), method_type);
    context.server().CleanUpCalls();
    function_.unary_request(context.service(), &request_struct, server_writer);
  }

  // Decodes a request protobuf into the provided buffer. Sends an error packet
  // if the request failed to decode.
  template <typename Request>
  Status DecodeRequest(const CallContext& context,
                       const Packet& request,
                       Request& request_struct) const
      PW_EXCLUSIVE_LOCKS_REQUIRED(rpc_lock()) {
    const auto status =
        serde_.request().Decode(request.payload(), request_struct);
    if (status.ok()) {
      return status;
    }

    // The channel is known to exist. It was found when the request was
    // processed and the lock has been held since, so GetInternalChannel cannot
    // fail.
    context.server()
        .GetInternalChannel(context.channel_id())
        ->Send(Packet::ServerError(request, Status::DataLoss()))
        .IgnoreError();
    return status;
  }

  // Invoker function for synchronous unary RPCs.
  template <typename Request, typename Response>
  static void SynchronousUnaryInvoker(const CallContext& context,
                                      const Packet& request)
      PW_UNLOCK_FUNCTION(rpc_lock()) {
    Request request_struct{};
    Response response_struct{};

    static_cast<const PwpbMethod&>(context.method())
        .CallSynchronousUnary(
            context, request, request_struct, response_struct);
  }

  // Invoker function for asynchronous unary RPCs.
  template <typename Request>
  static void AsynchronousUnaryInvoker(const CallContext& context,
                                       const Packet& request)
      PW_UNLOCK_FUNCTION(rpc_lock()) {
    Request request_struct{};

    static_cast<const PwpbMethod&>(context.method())
        .CallUnaryRequest(context, MethodType::kUnary, request, request_struct);
  }

  // Invoker function for server streaming RPCs.
  template <typename Request>
  static void ServerStreamingInvoker(const CallContext& context,
                                     const Packet& request)
      PW_UNLOCK_FUNCTION(rpc_lock()) {
    Request request_struct{};

    static_cast<const PwpbMethod&>(context.method())
        .CallUnaryRequest(
            context, MethodType::kServerStreaming, request, request_struct);
  }

  // Invoker function for client streaming RPCs.
  template <typename Request>
  static void ClientStreamingInvoker(const CallContext& context, const Packet&)
      PW_UNLOCK_FUNCTION(rpc_lock()) {
    internal::BasePwpbServerReader<Request> reader(
        context.ClaimLocked(), MethodType::kClientStreaming);
    context.server().CleanUpCalls();
    static_cast<const PwpbMethod&>(context.method())
        .function_.stream_request(context.service(), reader);
  }

  // Invoker function for bidirectional streaming RPCs.
  template <typename Request>
  static void BidirectionalStreamingInvoker(const CallContext& context,
                                            const Packet&)
      PW_UNLOCK_FUNCTION(rpc_lock()) {
    internal::BasePwpbServerReader<Request> reader_writer(
        context.ClaimLocked(), MethodType::kBidirectionalStreaming);
    context.server().CleanUpCalls();
    static_cast<const PwpbMethod&>(context.method())
        .function_.stream_request(context.service(), reader_writer);
  }

  // Stores the user-defined RPC in a generic wrapper.
  Function function_;

  // Serde used to encode and decode pw_protobuf structs.
  const PwpbMethodSerde& serde_;
};

// MethodTraits specialization for a static synchronous unary method.
// TODO: b/234874320 - Further qualify this (and nanopb) definition so that they
// can co-exist in the same project.
template <typename Req, typename Res>
struct MethodTraits<PwpbSynchronousUnary<Req, Res>*> {
  using Implementation = PwpbMethod;
  using Request = Req;
  using Response = Res;

  static constexpr MethodType kType = MethodType::kUnary;
  static constexpr bool kSynchronous = true;

  static constexpr bool kServerStreaming = false;
  static constexpr bool kClientStreaming = false;
};

// MethodTraits specialization for a synchronous raw unary method.
template <typename T, typename Req, typename Res>
struct MethodTraits<PwpbSynchronousUnary<Req, Res>(T::*)>
    : MethodTraits<PwpbSynchronousUnary<Req, Res>*> {
  using Service = T;
};

// MethodTraits specialization for a static asynchronous unary method.
template <typename Req, typename Resp>
struct MethodTraits<PwpbAsynchronousUnary<Req, Resp>*>
    : MethodTraits<PwpbSynchronousUnary<Req, Resp>*> {
  static constexpr bool kSynchronous = false;
};

// MethodTraits specialization for an asynchronous unary method.
template <typename T, typename Req, typename Resp>
struct MethodTraits<PwpbAsynchronousUnary<Req, Resp>(T::*)>
    : MethodTraits<PwpbSynchronousUnary<Req, Resp>(T::*)> {
  static constexpr bool kSynchronous = false;
};

// MethodTraits specialization for a static server streaming method.
template <typename Req, typename Resp>
struct MethodTraits<PwpbServerStreaming<Req, Resp>*> {
  using Implementation = PwpbMethod;
  using Request = Req;
  using Response = Resp;

  static constexpr MethodType kType = MethodType::kServerStreaming;
  static constexpr bool kServerStreaming = true;
  static constexpr bool kClientStreaming = false;
};

// MethodTraits specialization for a server streaming method.
template <typename T, typename Req, typename Resp>
struct MethodTraits<PwpbServerStreaming<Req, Resp>(T::*)>
    : MethodTraits<PwpbServerStreaming<Req, Resp>*> {
  using Service = T;
};

// MethodTraits specialization for a static server streaming method.
template <typename Req, typename Resp>
struct MethodTraits<PwpbClientStreaming<Req, Resp>*> {
  using Implementation = PwpbMethod;
  using Request = Req;
  using Response = Resp;

  static constexpr MethodType kType = MethodType::kClientStreaming;
  static constexpr bool kServerStreaming = false;
  static constexpr bool kClientStreaming = true;
};

// MethodTraits specialization for a server streaming method.
template <typename T, typename Req, typename Resp>
struct MethodTraits<PwpbClientStreaming<Req, Resp>(T::*)>
    : MethodTraits<PwpbClientStreaming<Req, Resp>*> {
  using Service = T;
};

// MethodTraits specialization for a static server streaming method.
template <typename Req, typename Resp>
struct MethodTraits<PwpbBidirectionalStreaming<Req, Resp>*> {
  using Implementation = PwpbMethod;
  using Request = Req;
  using Response = Resp;

  static constexpr MethodType kType = MethodType::kBidirectionalStreaming;
  static constexpr bool kServerStreaming = true;
  static constexpr bool kClientStreaming = true;
};

// MethodTraits specialization for a server streaming method.
template <typename T, typename Req, typename Resp>
struct MethodTraits<PwpbBidirectionalStreaming<Req, Resp>(T::*)>
    : MethodTraits<PwpbBidirectionalStreaming<Req, Resp>*> {
  using Service = T;
};

}  // namespace pw::rpc::internal