BatchContextSafeHandle.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. #region Copyright notice and license
  2. // Copyright 2015 gRPC authors.
  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. #endregion
  16. using System;
  17. using System.Runtime.InteropServices;
  18. using System.Text;
  19. using Grpc.Core;
  20. using Grpc.Core.Logging;
  21. using Grpc.Core.Utils;
  22. namespace Grpc.Core.Internal
  23. {
  24. internal interface IOpCompletionCallback
  25. {
  26. void OnComplete(bool success);
  27. }
  28. internal interface IBufferReader
  29. {
  30. int? TotalLength { get; }
  31. bool TryGetNextSlice(out Slice slice);
  32. }
  33. /// <summary>
  34. /// grpcsharp_batch_context
  35. /// </summary>
  36. internal class BatchContextSafeHandle : SafeHandleZeroIsInvalid, IOpCompletionCallback, IPooledObject<BatchContextSafeHandle>, IBufferReader
  37. {
  38. static readonly NativeMethods Native = NativeMethods.Get();
  39. static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<BatchContextSafeHandle>();
  40. Action<BatchContextSafeHandle> returnToPoolAction;
  41. CompletionCallbackData completionCallbackData;
  42. private BatchContextSafeHandle()
  43. {
  44. }
  45. public static BatchContextSafeHandle Create()
  46. {
  47. var ctx = Native.grpcsharp_batch_context_create();
  48. return ctx;
  49. }
  50. public IntPtr Handle
  51. {
  52. get
  53. {
  54. return handle;
  55. }
  56. }
  57. public void SetReturnToPoolAction(Action<BatchContextSafeHandle> returnAction)
  58. {
  59. GrpcPreconditions.CheckState(returnToPoolAction == null);
  60. returnToPoolAction = returnAction;
  61. }
  62. public void SetCompletionCallback(BatchCompletionDelegate callback, object state)
  63. {
  64. GrpcPreconditions.CheckState(completionCallbackData.Callback == null);
  65. GrpcPreconditions.CheckNotNull(callback, nameof(callback));
  66. completionCallbackData = new CompletionCallbackData(callback, state);
  67. }
  68. // Gets data of recv_initial_metadata completion.
  69. public Metadata GetReceivedInitialMetadata()
  70. {
  71. IntPtr metadataArrayPtr = Native.grpcsharp_batch_context_recv_initial_metadata(this);
  72. return MetadataArraySafeHandle.ReadMetadataFromPtrUnsafe(metadataArrayPtr);
  73. }
  74. // Gets data of recv_status_on_client completion.
  75. public ClientSideStatus GetReceivedStatusOnClient()
  76. {
  77. UIntPtr detailsLength;
  78. IntPtr detailsPtr = Native.grpcsharp_batch_context_recv_status_on_client_details(this, out detailsLength);
  79. string details = MarshalUtils.PtrToStringUTF8(detailsPtr, (int)detailsLength.ToUInt32());
  80. var status = new Status(Native.grpcsharp_batch_context_recv_status_on_client_status(this), details);
  81. IntPtr metadataArrayPtr = Native.grpcsharp_batch_context_recv_status_on_client_trailing_metadata(this);
  82. var metadata = MetadataArraySafeHandle.ReadMetadataFromPtrUnsafe(metadataArrayPtr);
  83. return new ClientSideStatus(status, metadata);
  84. }
  85. public IBufferReader GetReceivedMessageReader()
  86. {
  87. return this;
  88. }
  89. // Gets data of receive_close_on_server completion.
  90. public bool GetReceivedCloseOnServerCancelled()
  91. {
  92. return Native.grpcsharp_batch_context_recv_close_on_server_cancelled(this) != 0;
  93. }
  94. public void Recycle()
  95. {
  96. if (returnToPoolAction != null)
  97. {
  98. Native.grpcsharp_batch_context_reset(this);
  99. var origReturnAction = returnToPoolAction;
  100. // Not clearing all the references to the pool could prevent garbage collection of the pool object
  101. // and thus cause memory leaks.
  102. returnToPoolAction = null;
  103. origReturnAction(this);
  104. }
  105. else
  106. {
  107. Dispose();
  108. }
  109. }
  110. protected override bool ReleaseHandle()
  111. {
  112. Native.grpcsharp_batch_context_destroy(handle);
  113. return true;
  114. }
  115. void IOpCompletionCallback.OnComplete(bool success)
  116. {
  117. try
  118. {
  119. completionCallbackData.Callback(success, this, completionCallbackData.State);
  120. }
  121. catch (Exception e)
  122. {
  123. Logger.Error(e, "Exception occurred while invoking batch completion delegate.");
  124. }
  125. finally
  126. {
  127. completionCallbackData = default(CompletionCallbackData);
  128. Recycle();
  129. }
  130. }
  131. int? IBufferReader.TotalLength
  132. {
  133. get
  134. {
  135. var len = Native.grpcsharp_batch_context_recv_message_length(this);
  136. return len != new IntPtr(-1) ? (int?) len : null;
  137. }
  138. }
  139. bool IBufferReader.TryGetNextSlice(out Slice slice)
  140. {
  141. UIntPtr sliceLen;
  142. IntPtr sliceDataPtr;
  143. if (0 == Native.grpcsharp_batch_context_recv_message_next_slice_peek(this, out sliceLen, out sliceDataPtr))
  144. {
  145. slice = default(Slice);
  146. return false;
  147. }
  148. slice = new Slice(sliceDataPtr, (int) sliceLen);
  149. return true;
  150. }
  151. struct CompletionCallbackData
  152. {
  153. public CompletionCallbackData(BatchCompletionDelegate callback, object state)
  154. {
  155. this.Callback = callback;
  156. this.State = state;
  157. }
  158. public BatchCompletionDelegate Callback { get; }
  159. public object State { get; }
  160. }
  161. }
  162. }