grpc.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /*
  2. * Copyright 2014 Google Inc. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifndef FLATBUFFERS_GRPC_H_
  17. #define FLATBUFFERS_GRPC_H_
  18. // Helper functionality to glue FlatBuffers and GRPC.
  19. #include "flatbuffers/flatbuffers.h"
  20. #include "grpc++/support/byte_buffer.h"
  21. #include "grpc/byte_buffer_reader.h"
  22. namespace flatbuffers {
  23. namespace grpc {
  24. // Message is a typed wrapper around a buffer that manages the underlying
  25. // `grpc_slice` and also provides flatbuffers-specific helpers such as `Verify`
  26. // and `GetRoot`. Since it is backed by a `grpc_slice`, the underlying buffer
  27. // is refcounted and ownership is be managed automatically.
  28. template<class T> class Message {
  29. public:
  30. Message() : slice_(grpc_empty_slice()) {}
  31. Message(grpc_slice slice, bool add_ref)
  32. : slice_(add_ref ? grpc_slice_ref(slice) : slice) {}
  33. Message &operator=(const Message &other) = delete;
  34. Message(Message &&other) : slice_(other.slice_) {
  35. other.slice_ = grpc_empty_slice();
  36. }
  37. Message(const Message &other) = delete;
  38. Message &operator=(Message &&other) {
  39. grpc_slice_unref(slice_);
  40. slice_ = other.slice_;
  41. other.slice_ = grpc_empty_slice();
  42. return *this;
  43. }
  44. ~Message() { grpc_slice_unref(slice_); }
  45. const uint8_t *mutable_data() const { return GRPC_SLICE_START_PTR(slice_); }
  46. const uint8_t *data() const { return GRPC_SLICE_START_PTR(slice_); }
  47. size_t size() const { return GRPC_SLICE_LENGTH(slice_); }
  48. bool Verify() const {
  49. Verifier verifier(data(), size());
  50. return verifier.VerifyBuffer<T>(nullptr);
  51. }
  52. T *GetMutableRoot() { return flatbuffers::GetMutableRoot<T>(mutable_data()); }
  53. const T *GetRoot() const { return flatbuffers::GetRoot<T>(data()); }
  54. // This is only intended for serializer use, or if you know what you're doing
  55. const grpc_slice &BorrowSlice() const { return slice_; }
  56. private:
  57. grpc_slice slice_;
  58. };
  59. class MessageBuilder;
  60. // SliceAllocator is a gRPC-specific allocator that uses the `grpc_slice`
  61. // refcounted slices to manage memory ownership. This makes it easy and
  62. // efficient to transfer buffers to gRPC.
  63. class SliceAllocator : public Allocator {
  64. public:
  65. SliceAllocator() : slice_(grpc_empty_slice()) {}
  66. SliceAllocator(const SliceAllocator &other) = delete;
  67. SliceAllocator &operator=(const SliceAllocator &other) = delete;
  68. SliceAllocator(SliceAllocator &&other) : slice_(grpc_empty_slice()) {
  69. // default-construct and swap idiom
  70. swap(other);
  71. }
  72. SliceAllocator &operator=(SliceAllocator &&other) {
  73. // move-construct and swap idiom
  74. SliceAllocator temp(std::move(other));
  75. swap(temp);
  76. return *this;
  77. }
  78. void swap(SliceAllocator &other) {
  79. using std::swap;
  80. swap(slice_, other.slice_);
  81. }
  82. virtual ~SliceAllocator() { grpc_slice_unref(slice_); }
  83. virtual uint8_t *allocate(size_t size) override {
  84. FLATBUFFERS_ASSERT(GRPC_SLICE_IS_EMPTY(slice_));
  85. slice_ = grpc_slice_malloc(size);
  86. return GRPC_SLICE_START_PTR(slice_);
  87. }
  88. virtual void deallocate(uint8_t *p, size_t size) override {
  89. FLATBUFFERS_ASSERT(p == GRPC_SLICE_START_PTR(slice_));
  90. FLATBUFFERS_ASSERT(size == GRPC_SLICE_LENGTH(slice_));
  91. grpc_slice_unref(slice_);
  92. slice_ = grpc_empty_slice();
  93. }
  94. virtual uint8_t *reallocate_downward(uint8_t *old_p, size_t old_size,
  95. size_t new_size, size_t in_use_back,
  96. size_t in_use_front) override {
  97. FLATBUFFERS_ASSERT(old_p == GRPC_SLICE_START_PTR(slice_));
  98. FLATBUFFERS_ASSERT(old_size == GRPC_SLICE_LENGTH(slice_));
  99. FLATBUFFERS_ASSERT(new_size > old_size);
  100. grpc_slice old_slice = slice_;
  101. grpc_slice new_slice = grpc_slice_malloc(new_size);
  102. uint8_t *new_p = GRPC_SLICE_START_PTR(new_slice);
  103. memcpy_downward(old_p, old_size, new_p, new_size, in_use_back,
  104. in_use_front);
  105. slice_ = new_slice;
  106. grpc_slice_unref(old_slice);
  107. return new_p;
  108. }
  109. private:
  110. grpc_slice &get_slice(uint8_t *p, size_t size) {
  111. FLATBUFFERS_ASSERT(p == GRPC_SLICE_START_PTR(slice_));
  112. FLATBUFFERS_ASSERT(size == GRPC_SLICE_LENGTH(slice_));
  113. return slice_;
  114. }
  115. grpc_slice slice_;
  116. friend class MessageBuilder;
  117. };
  118. // SliceAllocatorMember is a hack to ensure that the MessageBuilder's
  119. // slice_allocator_ member is constructed before the FlatBufferBuilder, since
  120. // the allocator is used in the FlatBufferBuilder ctor.
  121. namespace detail {
  122. struct SliceAllocatorMember {
  123. SliceAllocator slice_allocator_;
  124. };
  125. } // namespace detail
  126. // MessageBuilder is a gRPC-specific FlatBufferBuilder that uses SliceAllocator
  127. // to allocate gRPC buffers.
  128. class MessageBuilder : private detail::SliceAllocatorMember,
  129. public FlatBufferBuilder {
  130. public:
  131. explicit MessageBuilder(uoffset_t initial_size = 1024)
  132. : FlatBufferBuilder(initial_size, &slice_allocator_, false) {}
  133. MessageBuilder(const MessageBuilder &other) = delete;
  134. MessageBuilder &operator=(const MessageBuilder &other) = delete;
  135. MessageBuilder(MessageBuilder &&other)
  136. : FlatBufferBuilder(1024, &slice_allocator_, false) {
  137. // Default construct and swap idiom.
  138. Swap(other);
  139. }
  140. /// Create a MessageBuilder from a FlatBufferBuilder.
  141. explicit MessageBuilder(FlatBufferBuilder &&src,
  142. void (*dealloc)(void *,
  143. size_t) = &DefaultAllocator::dealloc)
  144. : FlatBufferBuilder(1024, &slice_allocator_, false) {
  145. src.Swap(*this);
  146. src.SwapBufAllocator(*this);
  147. if (buf_.capacity()) {
  148. uint8_t *buf = buf_.scratch_data(); // pointer to memory
  149. size_t capacity = buf_.capacity(); // size of memory
  150. slice_allocator_.slice_ = grpc_slice_new_with_len(buf, capacity, dealloc);
  151. } else {
  152. slice_allocator_.slice_ = grpc_empty_slice();
  153. }
  154. }
  155. /// Move-assign a FlatBufferBuilder to a MessageBuilder.
  156. /// Only FlatBufferBuilder with default allocator (basically, nullptr) is
  157. /// supported.
  158. MessageBuilder &operator=(FlatBufferBuilder &&src) {
  159. // Move construct a temporary and swap
  160. MessageBuilder temp(std::move(src));
  161. Swap(temp);
  162. return *this;
  163. }
  164. MessageBuilder &operator=(MessageBuilder &&other) {
  165. // Move construct a temporary and swap
  166. MessageBuilder temp(std::move(other));
  167. Swap(temp);
  168. return *this;
  169. }
  170. void Swap(MessageBuilder &other) {
  171. slice_allocator_.swap(other.slice_allocator_);
  172. FlatBufferBuilder::Swap(other);
  173. // After swapping the FlatBufferBuilder, we swap back the allocator, which
  174. // restores the original allocator back in place. This is necessary because
  175. // MessageBuilder's allocator is its own member (SliceAllocatorMember). The
  176. // allocator passed to FlatBufferBuilder::vector_downward must point to this
  177. // member.
  178. buf_.swap_allocator(other.buf_);
  179. }
  180. // Releases the ownership of the buffer pointer.
  181. // Returns the size, offset, and the original grpc_slice that
  182. // allocated the buffer. Also see grpc_slice_unref().
  183. uint8_t *ReleaseRaw(size_t &size, size_t &offset, grpc_slice &slice) {
  184. uint8_t *buf = FlatBufferBuilder::ReleaseRaw(size, offset);
  185. slice = slice_allocator_.slice_;
  186. slice_allocator_.slice_ = grpc_empty_slice();
  187. return buf;
  188. }
  189. ~MessageBuilder() {}
  190. // GetMessage extracts the subslice of the buffer corresponding to the
  191. // flatbuffers-encoded region and wraps it in a `Message<T>` to handle buffer
  192. // ownership.
  193. template<class T> Message<T> GetMessage() {
  194. auto buf_data = buf_.scratch_data(); // pointer to memory
  195. auto buf_size = buf_.capacity(); // size of memory
  196. auto msg_data = buf_.data(); // pointer to msg
  197. auto msg_size = buf_.size(); // size of msg
  198. // Do some sanity checks on data/size
  199. FLATBUFFERS_ASSERT(msg_data);
  200. FLATBUFFERS_ASSERT(msg_size);
  201. FLATBUFFERS_ASSERT(msg_data >= buf_data);
  202. FLATBUFFERS_ASSERT(msg_data + msg_size <= buf_data + buf_size);
  203. // Calculate offsets from the buffer start
  204. auto begin = msg_data - buf_data;
  205. auto end = begin + msg_size;
  206. // Get the slice we are working with (no refcount change)
  207. grpc_slice slice = slice_allocator_.get_slice(buf_data, buf_size);
  208. // Extract a subslice of the existing slice (increment refcount)
  209. grpc_slice subslice = grpc_slice_sub(slice, begin, end);
  210. // Wrap the subslice in a `Message<T>`, but don't increment refcount
  211. Message<T> msg(subslice, false);
  212. return msg;
  213. }
  214. template<class T> Message<T> ReleaseMessage() {
  215. Message<T> msg = GetMessage<T>();
  216. Reset();
  217. return msg;
  218. }
  219. private:
  220. // SliceAllocator slice_allocator_; // part of SliceAllocatorMember
  221. };
  222. } // namespace grpc
  223. } // namespace flatbuffers
  224. namespace grpc {
  225. template<class T> class SerializationTraits<flatbuffers::grpc::Message<T>> {
  226. public:
  227. static grpc::Status Serialize(const flatbuffers::grpc::Message<T> &msg,
  228. grpc_byte_buffer **buffer, bool *own_buffer) {
  229. // We are passed in a `Message<T>`, which is a wrapper around a
  230. // `grpc_slice`. We extract it here using `BorrowSlice()`. The const cast
  231. // is necessary because the `grpc_raw_byte_buffer_create` func expects
  232. // non-const slices in order to increment their refcounts.
  233. grpc_slice *slice = const_cast<grpc_slice *>(&msg.BorrowSlice());
  234. // Now use `grpc_raw_byte_buffer_create` to package the single slice into a
  235. // `grpc_byte_buffer`, incrementing the refcount in the process.
  236. *buffer = grpc_raw_byte_buffer_create(slice, 1);
  237. *own_buffer = true;
  238. return grpc::Status::OK;
  239. }
  240. // Deserialize by pulling the
  241. static grpc::Status Deserialize(grpc_byte_buffer *buffer,
  242. flatbuffers::grpc::Message<T> *msg) {
  243. if (!buffer) {
  244. return ::grpc::Status(::grpc::StatusCode::INTERNAL, "No payload");
  245. }
  246. // Check if this is a single uncompressed slice.
  247. if ((buffer->type == GRPC_BB_RAW) &&
  248. (buffer->data.raw.compression == GRPC_COMPRESS_NONE) &&
  249. (buffer->data.raw.slice_buffer.count == 1)) {
  250. // If it is, then we can reference the `grpc_slice` directly.
  251. grpc_slice slice = buffer->data.raw.slice_buffer.slices[0];
  252. // We wrap a `Message<T>` around the slice, incrementing the refcount.
  253. *msg = flatbuffers::grpc::Message<T>(slice, true);
  254. } else {
  255. // Otherwise, we need to use `grpc_byte_buffer_reader_readall` to read
  256. // `buffer` into a single contiguous `grpc_slice`. The gRPC reader gives
  257. // us back a new slice with the refcount already incremented.
  258. grpc_byte_buffer_reader reader;
  259. grpc_byte_buffer_reader_init(&reader, buffer);
  260. grpc_slice slice = grpc_byte_buffer_reader_readall(&reader);
  261. grpc_byte_buffer_reader_destroy(&reader);
  262. // We wrap a `Message<T>` around the slice, but don't increment refcount
  263. *msg = flatbuffers::grpc::Message<T>(slice, false);
  264. }
  265. grpc_byte_buffer_destroy(buffer);
  266. #if FLATBUFFERS_GRPC_DISABLE_AUTO_VERIFICATION
  267. return ::grpc::Status::OK;
  268. #else
  269. if (msg->Verify()) {
  270. return ::grpc::Status::OK;
  271. } else {
  272. return ::grpc::Status(::grpc::StatusCode::INTERNAL,
  273. "Message verification failed");
  274. }
  275. #endif
  276. }
  277. };
  278. } // namespace grpc
  279. #endif // FLATBUFFERS_GRPC_H_