AsyncCallBase.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. #region Copyright notice and license
  2. // Copyright 2015, Google Inc.
  3. // All rights reserved.
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. #endregion
  31. using System;
  32. using System.Diagnostics;
  33. using System.IO;
  34. using System.Runtime.CompilerServices;
  35. using System.Runtime.InteropServices;
  36. using System.Threading;
  37. using System.Threading.Tasks;
  38. using Grpc.Core.Internal;
  39. using Grpc.Core.Logging;
  40. using Grpc.Core.Profiling;
  41. using Grpc.Core.Utils;
  42. namespace Grpc.Core.Internal
  43. {
  44. /// <summary>
  45. /// Base for handling both client side and server side calls.
  46. /// Manages native call lifecycle and provides convenience methods.
  47. /// </summary>
  48. internal abstract class AsyncCallBase<TWrite, TRead>
  49. {
  50. static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>();
  51. protected static readonly Status DeserializeResponseFailureStatus = new Status(StatusCode.Internal, "Failed to deserialize response message.");
  52. readonly Func<TWrite, byte[]> serializer;
  53. readonly Func<byte[], TRead> deserializer;
  54. protected readonly object myLock = new object();
  55. protected INativeCall call;
  56. protected bool disposed;
  57. protected bool started;
  58. protected bool cancelRequested;
  59. protected TaskCompletionSource<TRead> streamingReadTcs; // Completion of a pending streaming read if not null.
  60. protected TaskCompletionSource<object> streamingWriteTcs; // Completion of a pending streaming write or send close from client if not null.
  61. protected TaskCompletionSource<object> sendStatusFromServerTcs;
  62. protected bool isStreamingWriteCompletionDelayed; // Only used for the client side.
  63. protected bool readingDone; // True if last read (i.e. read with null payload) was already received.
  64. protected bool halfcloseRequested; // True if send close have been initiated.
  65. protected bool finished; // True if close has been received from the peer.
  66. protected bool initialMetadataSent;
  67. protected long streamingWritesCounter; // Number of streaming send operations started so far.
  68. public AsyncCallBase(Func<TWrite, byte[]> serializer, Func<byte[], TRead> deserializer)
  69. {
  70. this.serializer = GrpcPreconditions.CheckNotNull(serializer);
  71. this.deserializer = GrpcPreconditions.CheckNotNull(deserializer);
  72. }
  73. /// <summary>
  74. /// Requests cancelling the call.
  75. /// </summary>
  76. public void Cancel()
  77. {
  78. lock (myLock)
  79. {
  80. GrpcPreconditions.CheckState(started);
  81. cancelRequested = true;
  82. if (!disposed)
  83. {
  84. call.Cancel();
  85. }
  86. }
  87. }
  88. /// <summary>
  89. /// Requests cancelling the call with given status.
  90. /// </summary>
  91. protected void CancelWithStatus(Status status)
  92. {
  93. lock (myLock)
  94. {
  95. cancelRequested = true;
  96. if (!disposed)
  97. {
  98. call.CancelWithStatus(status);
  99. }
  100. }
  101. }
  102. protected void InitializeInternal(INativeCall call)
  103. {
  104. lock (myLock)
  105. {
  106. this.call = call;
  107. }
  108. }
  109. /// <summary>
  110. /// Initiates sending a message. Only one send operation can be active at a time.
  111. /// </summary>
  112. protected Task SendMessageInternalAsync(TWrite msg, WriteFlags writeFlags)
  113. {
  114. byte[] payload = UnsafeSerialize(msg);
  115. lock (myLock)
  116. {
  117. GrpcPreconditions.CheckState(started);
  118. var earlyResult = CheckSendAllowedOrEarlyResult();
  119. if (earlyResult != null)
  120. {
  121. return earlyResult;
  122. }
  123. call.StartSendMessage(HandleSendFinished, payload, writeFlags, !initialMetadataSent);
  124. initialMetadataSent = true;
  125. streamingWritesCounter++;
  126. streamingWriteTcs = new TaskCompletionSource<object>();
  127. return streamingWriteTcs.Task;
  128. }
  129. }
  130. /// <summary>
  131. /// Initiates reading a message. Only one read operation can be active at a time.
  132. /// </summary>
  133. protected Task<TRead> ReadMessageInternalAsync()
  134. {
  135. lock (myLock)
  136. {
  137. GrpcPreconditions.CheckState(started);
  138. if (readingDone)
  139. {
  140. // the last read that returns null or throws an exception is idempotent
  141. // and maintains its state.
  142. GrpcPreconditions.CheckState(streamingReadTcs != null, "Call does not support streaming reads.");
  143. return streamingReadTcs.Task;
  144. }
  145. GrpcPreconditions.CheckState(streamingReadTcs == null, "Only one read can be pending at a time");
  146. GrpcPreconditions.CheckState(!disposed);
  147. call.StartReceiveMessage(HandleReadFinished);
  148. streamingReadTcs = new TaskCompletionSource<TRead>();
  149. return streamingReadTcs.Task;
  150. }
  151. }
  152. /// <summary>
  153. /// If there are no more pending actions and no new actions can be started, releases
  154. /// the underlying native resources.
  155. /// </summary>
  156. protected bool ReleaseResourcesIfPossible()
  157. {
  158. if (!disposed && call != null)
  159. {
  160. bool noMoreSendCompletions = streamingWriteTcs == null && (halfcloseRequested || cancelRequested || finished);
  161. if (noMoreSendCompletions && readingDone && finished)
  162. {
  163. ReleaseResources();
  164. return true;
  165. }
  166. }
  167. return false;
  168. }
  169. protected abstract bool IsClient
  170. {
  171. get;
  172. }
  173. /// <summary>
  174. /// Returns an exception to throw for a failed send operation.
  175. /// It is only allowed to call this method for a call that has already finished.
  176. /// </summary>
  177. protected abstract Exception GetRpcExceptionClientOnly();
  178. private void ReleaseResources()
  179. {
  180. if (call != null)
  181. {
  182. call.Dispose();
  183. }
  184. disposed = true;
  185. OnAfterReleaseResources();
  186. }
  187. protected virtual void OnAfterReleaseResources()
  188. {
  189. }
  190. /// <summary>
  191. /// Checks if sending is allowed and possibly returns a Task that allows short-circuiting the send
  192. /// logic by directly returning the write operation result task. Normally, null is returned.
  193. /// </summary>
  194. protected abstract Task CheckSendAllowedOrEarlyResult();
  195. protected byte[] UnsafeSerialize(TWrite msg)
  196. {
  197. return serializer(msg);
  198. }
  199. protected Exception TryDeserialize(byte[] payload, out TRead msg)
  200. {
  201. try
  202. {
  203. msg = deserializer(payload);
  204. return null;
  205. }
  206. catch (Exception e)
  207. {
  208. msg = default(TRead);
  209. return e;
  210. }
  211. }
  212. /// <summary>
  213. /// Handles send completion (including SendCloseFromClient).
  214. /// </summary>
  215. protected void HandleSendFinished(bool success)
  216. {
  217. bool delayCompletion = false;
  218. TaskCompletionSource<object> origTcs = null;
  219. lock (myLock)
  220. {
  221. if (!success && !finished && IsClient) {
  222. // We should be setting this only once per call, following writes will be short circuited
  223. // because they cannot start until the entire call finishes.
  224. GrpcPreconditions.CheckState(!isStreamingWriteCompletionDelayed);
  225. // leave streamingWriteTcs set, it will be completed once call finished.
  226. isStreamingWriteCompletionDelayed = true;
  227. delayCompletion = true;
  228. }
  229. else
  230. {
  231. origTcs = streamingWriteTcs;
  232. streamingWriteTcs = null;
  233. }
  234. ReleaseResourcesIfPossible();
  235. }
  236. if (!success)
  237. {
  238. if (!delayCompletion)
  239. {
  240. if (IsClient)
  241. {
  242. GrpcPreconditions.CheckState(finished); // implied by !success && !delayCompletion && IsClient
  243. origTcs.SetException(GetRpcExceptionClientOnly());
  244. }
  245. else
  246. {
  247. origTcs.SetException (new IOException("Error sending from server."));
  248. }
  249. }
  250. // if delayCompletion == true, postpone SetException until call finishes.
  251. }
  252. else
  253. {
  254. origTcs.SetResult(null);
  255. }
  256. }
  257. /// <summary>
  258. /// Handles send status from server completion.
  259. /// </summary>
  260. protected void HandleSendStatusFromServerFinished(bool success)
  261. {
  262. lock (myLock)
  263. {
  264. ReleaseResourcesIfPossible();
  265. }
  266. if (!success)
  267. {
  268. sendStatusFromServerTcs.SetException(new IOException("Error sending status from server."));
  269. }
  270. else
  271. {
  272. sendStatusFromServerTcs.SetResult(null);
  273. }
  274. }
  275. /// <summary>
  276. /// Handles streaming read completion.
  277. /// </summary>
  278. protected void HandleReadFinished(bool success, byte[] receivedMessage)
  279. {
  280. // if success == false, received message will be null. It that case we will
  281. // treat this completion as the last read an rely on C core to handle the failed
  282. // read (e.g. deliver approriate statusCode on the clientside).
  283. TRead msg = default(TRead);
  284. var deserializeException = (success && receivedMessage != null) ? TryDeserialize(receivedMessage, out msg) : null;
  285. TaskCompletionSource<TRead> origTcs = null;
  286. lock (myLock)
  287. {
  288. origTcs = streamingReadTcs;
  289. if (receivedMessage == null)
  290. {
  291. // This was the last read.
  292. readingDone = true;
  293. }
  294. if (deserializeException != null && IsClient)
  295. {
  296. readingDone = true;
  297. // TODO(jtattermusch): it might be too late to set the status
  298. CancelWithStatus(DeserializeResponseFailureStatus);
  299. }
  300. if (!readingDone)
  301. {
  302. streamingReadTcs = null;
  303. }
  304. ReleaseResourcesIfPossible();
  305. }
  306. if (deserializeException != null && !IsClient)
  307. {
  308. origTcs.SetException(new IOException("Failed to deserialize request message.", deserializeException));
  309. return;
  310. }
  311. origTcs.SetResult(msg);
  312. }
  313. }
  314. }