qabstractgrpcclient.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. /*
  2. * MIT License
  3. *
  4. * Copyright (c) 2019 Alexey Edelev <semlanik@gmail.com>
  5. *
  6. * This file is part of QtProtobuf project https://git.semlanik.org/semlanik/qtprotobuf
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy of this
  9. * software and associated documentation files (the "Software"), to deal in the Software
  10. * without restriction, including without limitation the rights to use, copy, modify,
  11. * merge, publish, distribute, sublicense, and/or sell copies of the Software, and
  12. * to permit persons to whom the Software is furnished to do so, subject to the following
  13. * conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in all copies
  16. * or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  19. * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  20. * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  21. * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  22. * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. * DEALINGS IN THE SOFTWARE.
  24. */
  25. #include "qabstractgrpcclient.h"
  26. #include "qgrpccallreply.h"
  27. #include "qgrpcstream.h"
  28. #include "qprotobufserializerregistry_p.h"
  29. #include <QTimer>
  30. #include <QThread>
  31. namespace QtProtobuf {
  32. //! \private
  33. class QAbstractGrpcClientPrivate final {
  34. public:
  35. QAbstractGrpcClientPrivate(const QString &service) : service(service) {
  36. serializer = QProtobufSerializerRegistry::instance().getSerializer("protobuf");
  37. }
  38. std::shared_ptr<QAbstractGrpcChannel> channel;
  39. const QString service;
  40. std::shared_ptr<QAbstractProtobufSerializer> serializer;
  41. std::vector<QGrpcStreamShared> activeStreams;
  42. };
  43. }
  44. using namespace QtProtobuf;
  45. QAbstractGrpcClient::QAbstractGrpcClient(const QString &service, QObject *parent) : QObject(parent)
  46. , dPtr(std::make_unique<QAbstractGrpcClientPrivate>(service))
  47. {
  48. }
  49. QAbstractGrpcClient::~QAbstractGrpcClient()
  50. {}
  51. void QAbstractGrpcClient::attachChannel(const std::shared_ptr<QAbstractGrpcChannel> &channel)
  52. {
  53. if (channel->thread() != QThread::currentThread()) {
  54. qProtoCritical() << "QAbstractGrpcClient::attachChannel is called from different thread.\n"
  55. "QtGrpc doesn't guarantie thread safety on channel level.\n"
  56. "You have to be confident that channel routines are working in the same thread as QAbstractGrpcClient";
  57. throw std::runtime_error("Call from another thread");
  58. }
  59. dPtr->channel = channel;
  60. dPtr->serializer = channel->serializer();
  61. for (auto stream : dPtr->activeStreams) {
  62. stream->cancel();
  63. }
  64. }
  65. QGrpcStatus QAbstractGrpcClient::call(const QString &method, const QByteArray &arg, QByteArray &ret)
  66. {
  67. QGrpcStatus callStatus{QGrpcStatus::Unknown};
  68. if (thread() != QThread::currentThread()) {
  69. QMetaObject::invokeMethod(this, [&]()->QGrpcStatus {
  70. qProtoDebug() << "Method: " << dPtr->service << method << " called from different thread";
  71. return call(method, arg, ret);
  72. }, Qt::BlockingQueuedConnection, &callStatus);
  73. return callStatus;
  74. }
  75. if (dPtr->channel) {
  76. callStatus = dPtr->channel->call(method, dPtr->service, arg, ret);
  77. } else {
  78. callStatus = QGrpcStatus{QGrpcStatus::Unknown, QLatin1String("No channel(s) attached.")};
  79. }
  80. if (callStatus != QGrpcStatus::Ok) {
  81. error(callStatus);
  82. }
  83. return callStatus;
  84. }
  85. QGrpcCallReplyShared QAbstractGrpcClient::call(const QString &method, const QByteArray &arg)
  86. {
  87. QGrpcCallReplyShared reply;
  88. if (thread() != QThread::currentThread()) {
  89. QMetaObject::invokeMethod(this, [&]()->QGrpcCallReplyShared {
  90. qProtoDebug() << "Method: " << dPtr->service << method << " called from different thread";
  91. return call(method, arg);
  92. }, Qt::BlockingQueuedConnection, &reply);
  93. } else if (dPtr->channel) {
  94. reply.reset(new QGrpcCallReply(dPtr->channel, this), [](QGrpcCallReply *reply) { reply->deleteLater(); });
  95. auto errorConnection = std::make_shared<QMetaObject::Connection>();
  96. auto finishedConnection = std::make_shared<QMetaObject::Connection>();
  97. *errorConnection = connect(reply.get(), &QGrpcCallReply::error, this, [this, reply, errorConnection, finishedConnection](const QGrpcStatus &status) mutable {
  98. error(status);
  99. QObject::disconnect(*finishedConnection);
  100. QObject::disconnect(*errorConnection);
  101. reply.reset();
  102. });
  103. *finishedConnection = connect(reply.get(), &QGrpcCallReply::finished, [reply, errorConnection, finishedConnection]() mutable {
  104. QObject::disconnect(*finishedConnection);
  105. QObject::disconnect(*errorConnection);
  106. reply.reset();
  107. });
  108. dPtr->channel->call(method, dPtr->service, arg, reply.get());
  109. } else {
  110. error({QGrpcStatus::Unknown, QLatin1String("No channel(s) attached.")});
  111. }
  112. return reply;
  113. }
  114. QGrpcStreamShared QAbstractGrpcClient::stream(const QString &method, const QByteArray &arg, const QtProtobuf::StreamHandler &handler)
  115. {
  116. QGrpcStreamShared grpcStream;
  117. if (thread() != QThread::currentThread()) {
  118. QMetaObject::invokeMethod(this, [&]()->QGrpcStreamShared {
  119. qProtoDebug() << "Stream: " << dPtr->service << method << " called from different thread";
  120. return stream(method, arg, handler);
  121. }, Qt::BlockingQueuedConnection, &grpcStream);
  122. } else if (dPtr->channel) {
  123. grpcStream.reset(new QGrpcStream(dPtr->channel, method, arg, handler, this), [](QGrpcStream *stream) { stream->deleteLater(); });
  124. auto it = std::find_if(std::begin(dPtr->activeStreams), std::end(dPtr->activeStreams), [grpcStream](const QGrpcStreamShared &activeStream) {
  125. return *activeStream == *grpcStream;
  126. });
  127. if (it != std::end(dPtr->activeStreams)) {
  128. (*it)->addHandler(handler);
  129. return *it; //If stream already exists return it for handling
  130. }
  131. auto errorConnection = std::make_shared<QMetaObject::Connection>();
  132. *errorConnection = connect(grpcStream.get(), &QGrpcStream::error, this, [this, grpcStream](const QGrpcStatus &status) {
  133. qProtoWarning() << grpcStream->method() << "call" << dPtr->service << "stream error: " << status.message();
  134. error(status);
  135. std::weak_ptr<QGrpcStream> weakStream = grpcStream;
  136. //TODO: Make timeout configurable from channel settings
  137. QTimer::singleShot(1000, this, [this, weakStream, method = grpcStream->method()] {
  138. auto stream = weakStream.lock();
  139. if (stream) {
  140. dPtr->channel->stream(stream.get(), dPtr->service, this);
  141. } else {
  142. qProtoDebug() << "Stream for " << dPtr->service << "method" << method << " will not be restored by timeout.";
  143. }
  144. });
  145. });
  146. auto finishedConnection = std::make_shared<QMetaObject::Connection>();
  147. *finishedConnection = connect(grpcStream.get(), &QGrpcStream::finished, this, [this, grpcStream, errorConnection, finishedConnection]() mutable {
  148. qProtoWarning() << grpcStream->method() << "call" << dPtr->service << "stream finished";
  149. auto it = std::find_if(std::begin(dPtr->activeStreams), std::end(dPtr->activeStreams), [grpcStream](QGrpcStreamShared activeStream) {
  150. return *activeStream == *grpcStream;
  151. });
  152. if (it != std::end(dPtr->activeStreams)) {
  153. dPtr->activeStreams.erase(it);
  154. }
  155. QObject::disconnect(*errorConnection);
  156. QObject::disconnect(*finishedConnection);
  157. grpcStream.reset();
  158. });
  159. dPtr->channel->stream(grpcStream.get(), dPtr->service, this);
  160. dPtr->activeStreams.push_back(grpcStream);
  161. } else {
  162. error({QGrpcStatus::Unknown, QLatin1String("No channel(s) attached.")});
  163. }
  164. return grpcStream;
  165. }
  166. QAbstractProtobufSerializer *QAbstractGrpcClient::serializer() const
  167. {
  168. return dPtr->serializer.get();
  169. }