Metadata.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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.Collections;
  18. using System.Collections.Generic;
  19. using System.Runtime.InteropServices;
  20. using System.Text;
  21. using Grpc.Core.Api.Utils;
  22. using Grpc.Core.Utils;
  23. namespace Grpc.Core
  24. {
  25. /// <summary>
  26. /// A collection of metadata entries that can be exchanged during a call.
  27. /// gRPC supports these types of metadata:
  28. /// <list type="bullet">
  29. /// <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>
  30. /// <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>
  31. /// <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>
  32. /// </list>
  33. /// </summary>
  34. public sealed class Metadata : IList<Metadata.Entry>
  35. {
  36. /// <summary>
  37. /// All binary headers should have this suffix.
  38. /// </summary>
  39. public const string BinaryHeaderSuffix = "-bin";
  40. /// <summary>
  41. /// An read-only instance of metadata containing no entries.
  42. /// </summary>
  43. public static readonly Metadata Empty = new Metadata().Freeze();
  44. /// <summary>
  45. /// To be used in initial metadata to request specific compression algorithm
  46. /// for given call. Direct selection of compression algorithms is an internal
  47. /// feature and is not part of public API.
  48. /// </summary>
  49. internal const string CompressionRequestAlgorithmMetadataKey = "grpc-internal-encoding-request";
  50. static readonly Encoding EncodingASCII = System.Text.Encoding.ASCII;
  51. readonly List<Entry> entries;
  52. bool readOnly;
  53. /// <summary>
  54. /// Initializes a new instance of <c>Metadata</c>.
  55. /// </summary>
  56. public Metadata()
  57. {
  58. this.entries = new List<Entry>();
  59. }
  60. /// <summary>
  61. /// Makes this object read-only.
  62. /// </summary>
  63. /// <returns>this object</returns>
  64. internal Metadata Freeze()
  65. {
  66. this.readOnly = true;
  67. return this;
  68. }
  69. // TODO: add support for access by key
  70. #region IList members
  71. /// <summary>
  72. /// <see cref="T:IList`1"/>
  73. /// </summary>
  74. public int IndexOf(Metadata.Entry item)
  75. {
  76. return entries.IndexOf(item);
  77. }
  78. /// <summary>
  79. /// <see cref="T:IList`1"/>
  80. /// </summary>
  81. public void Insert(int index, Metadata.Entry item)
  82. {
  83. GrpcPreconditions.CheckNotNull(item);
  84. CheckWriteable();
  85. entries.Insert(index, item);
  86. }
  87. /// <summary>
  88. /// <see cref="T:IList`1"/>
  89. /// </summary>
  90. public void RemoveAt(int index)
  91. {
  92. CheckWriteable();
  93. entries.RemoveAt(index);
  94. }
  95. /// <summary>
  96. /// <see cref="T:IList`1"/>
  97. /// </summary>
  98. public Metadata.Entry this[int index]
  99. {
  100. get
  101. {
  102. return entries[index];
  103. }
  104. set
  105. {
  106. GrpcPreconditions.CheckNotNull(value);
  107. CheckWriteable();
  108. entries[index] = value;
  109. }
  110. }
  111. /// <summary>
  112. /// <see cref="T:IList`1"/>
  113. /// </summary>
  114. public void Add(Metadata.Entry item)
  115. {
  116. GrpcPreconditions.CheckNotNull(item);
  117. CheckWriteable();
  118. entries.Add(item);
  119. }
  120. /// <summary>
  121. /// Adds a new ASCII-valued metadata entry. See <c>Metadata.Entry</c> constructor for params.
  122. /// </summary>
  123. public void Add(string key, string value)
  124. {
  125. Add(new Entry(key, value));
  126. }
  127. /// <summary>
  128. /// Adds a new binary-valued metadata entry. See <c>Metadata.Entry</c> constructor for params.
  129. /// </summary>
  130. public void Add(string key, byte[] valueBytes)
  131. {
  132. Add(new Entry(key, valueBytes));
  133. }
  134. /// <summary>
  135. /// <see cref="T:IList`1"/>
  136. /// </summary>
  137. public void Clear()
  138. {
  139. CheckWriteable();
  140. entries.Clear();
  141. }
  142. /// <summary>
  143. /// <see cref="T:IList`1"/>
  144. /// </summary>
  145. public bool Contains(Metadata.Entry item)
  146. {
  147. return entries.Contains(item);
  148. }
  149. /// <summary>
  150. /// <see cref="T:IList`1"/>
  151. /// </summary>
  152. public void CopyTo(Metadata.Entry[] array, int arrayIndex)
  153. {
  154. entries.CopyTo(array, arrayIndex);
  155. }
  156. /// <summary>
  157. /// <see cref="T:IList`1"/>
  158. /// </summary>
  159. public int Count
  160. {
  161. get { return entries.Count; }
  162. }
  163. /// <summary>
  164. /// <see cref="T:IList`1"/>
  165. /// </summary>
  166. public bool IsReadOnly
  167. {
  168. get { return readOnly; }
  169. }
  170. /// <summary>
  171. /// <see cref="T:IList`1"/>
  172. /// </summary>
  173. public bool Remove(Metadata.Entry item)
  174. {
  175. CheckWriteable();
  176. return entries.Remove(item);
  177. }
  178. /// <summary>
  179. /// <see cref="T:IList`1"/>
  180. /// </summary>
  181. public IEnumerator<Metadata.Entry> GetEnumerator()
  182. {
  183. return entries.GetEnumerator();
  184. }
  185. IEnumerator System.Collections.IEnumerable.GetEnumerator()
  186. {
  187. return entries.GetEnumerator();
  188. }
  189. private void CheckWriteable()
  190. {
  191. GrpcPreconditions.CheckState(!readOnly, "Object is read only");
  192. }
  193. #endregion
  194. /// <summary>
  195. /// Metadata entry
  196. /// </summary>
  197. public class Entry
  198. {
  199. readonly string key;
  200. readonly string value;
  201. readonly byte[] valueBytes;
  202. private Entry(string key, string value, byte[] valueBytes)
  203. {
  204. this.key = key;
  205. this.value = value;
  206. this.valueBytes = valueBytes;
  207. }
  208. /// <summary>
  209. /// Initializes a new instance of the <see cref="Grpc.Core.Metadata.Entry"/> struct with a binary value.
  210. /// </summary>
  211. /// <param name="key">Metadata key. Gets converted to lowercase. Needs to have suffix indicating a binary valued metadata entry. Can only contain lowercase alphanumeric characters, underscores, hyphens and dots.</param>
  212. /// <param name="valueBytes">Value bytes.</param>
  213. public Entry(string key, byte[] valueBytes)
  214. {
  215. this.key = NormalizeKey(key);
  216. GrpcPreconditions.CheckArgument(HasBinaryHeaderSuffix(this.key),
  217. "Key for binary valued metadata entry needs to have suffix indicating binary value.");
  218. this.value = null;
  219. GrpcPreconditions.CheckNotNull(valueBytes, "valueBytes");
  220. this.valueBytes = new byte[valueBytes.Length];
  221. Buffer.BlockCopy(valueBytes, 0, this.valueBytes, 0, valueBytes.Length); // defensive copy to guarantee immutability
  222. }
  223. /// <summary>
  224. /// Initializes a new instance of the <see cref="Grpc.Core.Metadata.Entry"/> struct with an ASCII value.
  225. /// </summary>
  226. /// <param name="key">Metadata key. Gets converted to lowercase. Must not use suffix indicating a binary valued metadata entry. Can only contain lowercase alphanumeric characters, underscores, hyphens and dots.</param>
  227. /// <param name="value">Value string. Only ASCII characters are allowed.</param>
  228. public Entry(string key, string value)
  229. {
  230. this.key = NormalizeKey(key);
  231. GrpcPreconditions.CheckArgument(!HasBinaryHeaderSuffix(this.key),
  232. "Key for ASCII valued metadata entry cannot have suffix indicating binary value.");
  233. this.value = GrpcPreconditions.CheckNotNull(value, "value");
  234. this.valueBytes = null;
  235. }
  236. /// <summary>
  237. /// Gets the metadata entry key.
  238. /// </summary>
  239. public string Key
  240. {
  241. get
  242. {
  243. return this.key;
  244. }
  245. }
  246. /// <summary>
  247. /// Gets the binary value of this metadata entry.
  248. /// </summary>
  249. public byte[] ValueBytes
  250. {
  251. get
  252. {
  253. if (valueBytes == null)
  254. {
  255. return EncodingASCII.GetBytes(value);
  256. }
  257. // defensive copy to guarantee immutability
  258. var bytes = new byte[valueBytes.Length];
  259. Buffer.BlockCopy(valueBytes, 0, bytes, 0, valueBytes.Length);
  260. return bytes;
  261. }
  262. }
  263. /// <summary>
  264. /// Gets the string value of this metadata entry.
  265. /// </summary>
  266. public string Value
  267. {
  268. get
  269. {
  270. GrpcPreconditions.CheckState(!IsBinary, "Cannot access string value of a binary metadata entry");
  271. return value ?? EncodingASCII.GetString(valueBytes);
  272. }
  273. }
  274. /// <summary>
  275. /// Returns <c>true</c> if this entry is a binary-value entry.
  276. /// </summary>
  277. public bool IsBinary
  278. {
  279. get
  280. {
  281. return value == null;
  282. }
  283. }
  284. /// <summary>
  285. /// Returns a <see cref="System.String"/> that represents the current <see cref="Grpc.Core.Metadata.Entry"/>.
  286. /// </summary>
  287. public override string ToString()
  288. {
  289. if (IsBinary)
  290. {
  291. return string.Format("[Entry: key={0}, valueBytes={1}]", key, valueBytes);
  292. }
  293. return string.Format("[Entry: key={0}, value={1}]", key, value);
  294. }
  295. /// <summary>
  296. /// Gets the serialized value for this entry. For binary metadata entries, this leaks
  297. /// the internal <c>valueBytes</c> byte array and caller must not change contents of it.
  298. /// </summary>
  299. internal byte[] GetSerializedValueUnsafe()
  300. {
  301. return valueBytes ?? EncodingASCII.GetBytes(value);
  302. }
  303. /// <summary>
  304. /// Creates a binary value or ascii value metadata entry from data received from the native layer.
  305. /// We trust C core to give us well-formed data, so we don't perform any checks or defensive copying.
  306. /// </summary>
  307. internal static Entry CreateUnsafe(string key, IntPtr source, int length)
  308. {
  309. if (HasBinaryHeaderSuffix(key))
  310. {
  311. byte[] arr;
  312. if (length == 0)
  313. {
  314. arr = EmptyByteArray;
  315. }
  316. else
  317. { // create a local copy in a fresh array
  318. arr = new byte[length];
  319. Marshal.Copy(source, arr, 0, length);
  320. }
  321. return new Entry(key, null, arr);
  322. }
  323. else
  324. {
  325. string s = EncodingASCII.GetString(source, length);
  326. return new Entry(key, s, null);
  327. }
  328. }
  329. static readonly byte[] EmptyByteArray = new byte[0];
  330. private static string NormalizeKey(string key)
  331. {
  332. GrpcPreconditions.CheckNotNull(key, "key");
  333. GrpcPreconditions.CheckArgument(IsValidKey(key, out bool isLowercase),
  334. "Metadata entry key not valid. Keys can only contain lowercase alphanumeric characters, underscores, hyphens and dots.");
  335. if (isLowercase)
  336. {
  337. // save allocation of a new string if already lowercase
  338. return key;
  339. }
  340. return key.ToLowerInvariant();
  341. }
  342. private static bool IsValidKey(string input, out bool isLowercase)
  343. {
  344. isLowercase = true;
  345. for (int i = 0; i < input.Length; i++)
  346. {
  347. char c = input[i];
  348. if ('a' <= c && c <= 'z' ||
  349. '0' <= c && c <= '9' ||
  350. c == '.' ||
  351. c == '_' ||
  352. c == '-' )
  353. continue;
  354. if ('A' <= c && c <= 'Z')
  355. {
  356. isLowercase = false;
  357. continue;
  358. }
  359. return false;
  360. }
  361. return true;
  362. }
  363. /// <summary>
  364. /// Returns <c>true</c> if the key has "-bin" binary header suffix.
  365. /// </summary>
  366. private static bool HasBinaryHeaderSuffix(string key)
  367. {
  368. // We don't use just string.EndsWith because its implementation is extremely slow
  369. // on CoreCLR and we've seen significant differences in gRPC benchmarks caused by it.
  370. // See https://github.com/dotnet/coreclr/issues/5612
  371. int len = key.Length;
  372. if (len >= 4 &&
  373. key[len - 4] == '-' &&
  374. key[len - 3] == 'b' &&
  375. key[len - 2] == 'i' &&
  376. key[len - 1] == 'n')
  377. {
  378. return true;
  379. }
  380. return false;
  381. }
  382. }
  383. }
  384. }