Metadata.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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.Collections;
  33. using System.Collections.Generic;
  34. using System.Collections.Specialized;
  35. using System.Globalization;
  36. using System.Runtime.InteropServices;
  37. using System.Text;
  38. using System.Text.RegularExpressions;
  39. using Grpc.Core.Utils;
  40. namespace Grpc.Core
  41. {
  42. /// <summary>
  43. /// A collection of metadata entries that can be exchanged during a call.
  44. /// gRPC supports these types of metadata:
  45. /// <list type="bullet">
  46. /// <item><term>Request headers</term><description>are sent by the client at the beginning of a remote call before any request messages are sent.</description></item>
  47. /// <item><term>Response headers</term><description>are sent by the server at the beginning of a remote call handler before any response messages are sent.</description></item>
  48. /// <item><term>Response trailers</term><description>are sent by the server at the end of a remote call along with resulting call status.</description></item>
  49. /// </list>
  50. /// </summary>
  51. public sealed class Metadata : IList<Metadata.Entry>
  52. {
  53. /// <summary>
  54. /// All binary headers should have this suffix.
  55. /// </summary>
  56. public const string BinaryHeaderSuffix = "-bin";
  57. /// <summary>
  58. /// An read-only instance of metadata containing no entries.
  59. /// </summary>
  60. public static readonly Metadata Empty = new Metadata().Freeze();
  61. /// <summary>
  62. /// To be used in initial metadata to request specific compression algorithm
  63. /// for given call. Direct selection of compression algorithms is an internal
  64. /// feature and is not part of public API.
  65. /// </summary>
  66. internal const string CompressionRequestAlgorithmMetadataKey = "grpc-internal-encoding-request";
  67. readonly List<Entry> entries;
  68. bool readOnly;
  69. /// <summary>
  70. /// Initializes a new instance of <c>Metadata</c>.
  71. /// </summary>
  72. public Metadata()
  73. {
  74. this.entries = new List<Entry>();
  75. }
  76. /// <summary>
  77. /// Makes this object read-only.
  78. /// </summary>
  79. /// <returns>this object</returns>
  80. internal Metadata Freeze()
  81. {
  82. this.readOnly = true;
  83. return this;
  84. }
  85. // TODO: add support for access by key
  86. #region IList members
  87. public int IndexOf(Metadata.Entry item)
  88. {
  89. return entries.IndexOf(item);
  90. }
  91. public void Insert(int index, Metadata.Entry item)
  92. {
  93. GrpcPreconditions.CheckNotNull(item);
  94. CheckWriteable();
  95. entries.Insert(index, item);
  96. }
  97. public void RemoveAt(int index)
  98. {
  99. CheckWriteable();
  100. entries.RemoveAt(index);
  101. }
  102. public Metadata.Entry this[int index]
  103. {
  104. get
  105. {
  106. return entries[index];
  107. }
  108. set
  109. {
  110. GrpcPreconditions.CheckNotNull(value);
  111. CheckWriteable();
  112. entries[index] = value;
  113. }
  114. }
  115. public void Add(Metadata.Entry item)
  116. {
  117. GrpcPreconditions.CheckNotNull(item);
  118. CheckWriteable();
  119. entries.Add(item);
  120. }
  121. public void Add(string key, string value)
  122. {
  123. Add(new Entry(key, value));
  124. }
  125. public void Add(string key, byte[] valueBytes)
  126. {
  127. Add(new Entry(key, valueBytes));
  128. }
  129. public void Clear()
  130. {
  131. CheckWriteable();
  132. entries.Clear();
  133. }
  134. public bool Contains(Metadata.Entry item)
  135. {
  136. return entries.Contains(item);
  137. }
  138. public void CopyTo(Metadata.Entry[] array, int arrayIndex)
  139. {
  140. entries.CopyTo(array, arrayIndex);
  141. }
  142. public int Count
  143. {
  144. get { return entries.Count; }
  145. }
  146. public bool IsReadOnly
  147. {
  148. get { return readOnly; }
  149. }
  150. public bool Remove(Metadata.Entry item)
  151. {
  152. CheckWriteable();
  153. return entries.Remove(item);
  154. }
  155. public IEnumerator<Metadata.Entry> GetEnumerator()
  156. {
  157. return entries.GetEnumerator();
  158. }
  159. IEnumerator System.Collections.IEnumerable.GetEnumerator()
  160. {
  161. return entries.GetEnumerator();
  162. }
  163. private void CheckWriteable()
  164. {
  165. GrpcPreconditions.CheckState(!readOnly, "Object is read only");
  166. }
  167. #endregion
  168. /// <summary>
  169. /// Metadata entry
  170. /// </summary>
  171. public class Entry
  172. {
  173. private static readonly Encoding Encoding = Encoding.ASCII;
  174. private static readonly Regex ValidKeyRegex = new Regex("^[a-z0-9_-]+$");
  175. readonly string key;
  176. readonly string value;
  177. readonly byte[] valueBytes;
  178. private Entry(string key, string value, byte[] valueBytes)
  179. {
  180. this.key = key;
  181. this.value = value;
  182. this.valueBytes = valueBytes;
  183. }
  184. /// <summary>
  185. /// Initializes a new instance of the <see cref="Grpc.Core.Metadata.Entry"/> struct with a binary value.
  186. /// </summary>
  187. /// <param name="key">Metadata key, needs to have suffix indicating a binary valued metadata entry.</param>
  188. /// <param name="valueBytes">Value bytes.</param>
  189. public Entry(string key, byte[] valueBytes)
  190. {
  191. this.key = NormalizeKey(key);
  192. GrpcPreconditions.CheckArgument(this.key.EndsWith(BinaryHeaderSuffix),
  193. "Key for binary valued metadata entry needs to have suffix indicating binary value.");
  194. this.value = null;
  195. GrpcPreconditions.CheckNotNull(valueBytes, "valueBytes");
  196. this.valueBytes = new byte[valueBytes.Length];
  197. Buffer.BlockCopy(valueBytes, 0, this.valueBytes, 0, valueBytes.Length); // defensive copy to guarantee immutability
  198. }
  199. /// <summary>
  200. /// Initializes a new instance of the <see cref="Grpc.Core.Metadata.Entry"/> struct holding an ASCII value.
  201. /// </summary>
  202. /// <param name="key">Metadata key, must not use suffix indicating a binary valued metadata entry.</param>
  203. /// <param name="value">Value string. Only ASCII characters are allowed.</param>
  204. public Entry(string key, string value)
  205. {
  206. this.key = NormalizeKey(key);
  207. GrpcPreconditions.CheckArgument(!this.key.EndsWith(BinaryHeaderSuffix),
  208. "Key for ASCII valued metadata entry cannot have suffix indicating binary value.");
  209. this.value = GrpcPreconditions.CheckNotNull(value, "value");
  210. this.valueBytes = null;
  211. }
  212. /// <summary>
  213. /// Gets the metadata entry key.
  214. /// </summary>
  215. public string Key
  216. {
  217. get
  218. {
  219. return this.key;
  220. }
  221. }
  222. /// <summary>
  223. /// Gets the binary value of this metadata entry.
  224. /// </summary>
  225. public byte[] ValueBytes
  226. {
  227. get
  228. {
  229. if (valueBytes == null)
  230. {
  231. return Encoding.GetBytes(value);
  232. }
  233. // defensive copy to guarantee immutability
  234. var bytes = new byte[valueBytes.Length];
  235. Buffer.BlockCopy(valueBytes, 0, bytes, 0, valueBytes.Length);
  236. return bytes;
  237. }
  238. }
  239. /// <summary>
  240. /// Gets the string value of this metadata entry.
  241. /// </summary>
  242. public string Value
  243. {
  244. get
  245. {
  246. GrpcPreconditions.CheckState(!IsBinary, "Cannot access string value of a binary metadata entry");
  247. return value ?? Encoding.GetString(valueBytes);
  248. }
  249. }
  250. /// <summary>
  251. /// Returns <c>true</c> if this entry is a binary-value entry.
  252. /// </summary>
  253. public bool IsBinary
  254. {
  255. get
  256. {
  257. return value == null;
  258. }
  259. }
  260. /// <summary>
  261. /// Returns a <see cref="System.String"/> that represents the current <see cref="Grpc.Core.Metadata.Entry"/>.
  262. /// </summary>
  263. public override string ToString()
  264. {
  265. if (IsBinary)
  266. {
  267. return string.Format("[Entry: key={0}, valueBytes={1}]", key, valueBytes);
  268. }
  269. return string.Format("[Entry: key={0}, value={1}]", key, value);
  270. }
  271. /// <summary>
  272. /// Gets the serialized value for this entry. For binary metadata entries, this leaks
  273. /// the internal <c>valueBytes</c> byte array and caller must not change contents of it.
  274. /// </summary>
  275. internal byte[] GetSerializedValueUnsafe()
  276. {
  277. return valueBytes ?? Encoding.GetBytes(value);
  278. }
  279. /// <summary>
  280. /// Creates a binary value or ascii value metadata entry from data received from the native layer.
  281. /// We trust C core to give us well-formed data, so we don't perform any checks or defensive copying.
  282. /// </summary>
  283. internal static Entry CreateUnsafe(string key, byte[] valueBytes)
  284. {
  285. if (key.EndsWith(BinaryHeaderSuffix))
  286. {
  287. return new Entry(key, null, valueBytes);
  288. }
  289. return new Entry(key, Encoding.GetString(valueBytes), null);
  290. }
  291. private static string NormalizeKey(string key)
  292. {
  293. var normalized = GrpcPreconditions.CheckNotNull(key, "key").ToLowerInvariant();
  294. GrpcPreconditions.CheckArgument(ValidKeyRegex.IsMatch(normalized),
  295. "Metadata entry key not valid. Keys can only contain lowercase alphanumeric characters, underscores and hyphens.");
  296. return normalized;
  297. }
  298. }
  299. }
  300. }