Metadata.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. /*
  2. * Copyright 2023, gRPC Authors All rights reserved.
  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. */
  16. /// A collection of metadata key-value pairs, found in RPC streams.
  17. ///
  18. /// Metadata is a side channel associated with an RPC, that allows you to send information between clients
  19. /// and servers. Metadata is stored as a list of key-value pairs where keys aren't required to be unique;
  20. /// a single key may have multiple values associated with it.
  21. ///
  22. /// Keys are case-insensitive ASCII strings. Values may be ASCII strings or binary data. The keys
  23. /// for binary data should end with "-bin": this will be asserted when adding a new binary value.
  24. /// Keys must not be prefixed with "grpc-" as these are reserved for gRPC.
  25. ///
  26. /// # Using Metadata
  27. ///
  28. /// You can add values to ``Metadata`` using the ``addString(_:forKey:)`` and
  29. /// ``addBinary(_:forKey:)`` methods:
  30. ///
  31. /// ```swift
  32. /// var metadata = Metadata()
  33. /// metadata.addString("value", forKey: "key")
  34. /// metadata.addBinary([118, 97, 108, 117, 101], forKey: "key-bin")
  35. /// ```
  36. ///
  37. /// As ``Metadata`` conforms to `RandomAccessCollection` you can iterate over its values.
  38. /// Because metadata can store strings and binary values, its `Element` type is an `enum` representing
  39. /// both possibilities:
  40. ///
  41. /// ```swift
  42. /// for (key, value) in metadata {
  43. /// switch value {
  44. /// case .string(let value):
  45. /// print("'\(key)' has a string value: '\(value)'")
  46. /// case .binary(let value):
  47. /// print("'\(key)' has a binary value: '\(value)'")
  48. /// }
  49. /// }
  50. /// ```
  51. ///
  52. /// You can also iterate over the values for a specific key:
  53. ///
  54. /// ```swift
  55. /// for value in metadata["key"] {
  56. /// switch value {
  57. /// case .string(let value):
  58. /// print("'key' has a string value: '\(value)'")
  59. /// case .binary(let value):
  60. /// print("'key' has a binary value: '\(value)'")
  61. /// }
  62. /// }
  63. /// ```
  64. ///
  65. /// You can get only string or binary values for a key using ``subscript(stringValues:)`` and
  66. /// ``subscript(binaryValues:)``:
  67. ///
  68. /// ```swift
  69. /// for value in metadata[stringValues: "key"] {
  70. /// print("'key' has a string value: '\(value)'")
  71. /// }
  72. ///
  73. /// for value in metadata[binaryValues: "key"] {
  74. /// print("'key' has a binary value: '\(value)'")
  75. /// }
  76. /// ```
  77. ///
  78. /// - Note: Binary values are encoded as base64 strings when they are sent over the wire, so keys with
  79. /// the "-bin" suffix may have string values (rather than binary). These are deserialized automatically when
  80. /// using ``subscript(binaryValues:)``.
  81. @available(gRPCSwift 2.0, *)
  82. @available(*, deprecated, message: "See https://forums.swift.org/t/80177")
  83. public struct Metadata: Sendable, Hashable {
  84. /// A metadata value. It can either be a simple string, or binary data.
  85. public enum Value: Sendable, Hashable {
  86. case string(String)
  87. case binary([UInt8])
  88. /// The value as a String. If it was originally stored as a binary, the base64-encoded String version
  89. /// of the binary data will be returned instead.
  90. public func encoded() -> String {
  91. switch self {
  92. case .string(let string):
  93. return string
  94. case .binary(let bytes):
  95. return Base64.encode(bytes: bytes)
  96. }
  97. }
  98. }
  99. /// A metadata key-value pair.
  100. internal struct KeyValuePair: Sendable, Hashable {
  101. internal let key: String
  102. internal let value: Value
  103. /// Constructor for a metadata key-value pair.
  104. ///
  105. /// - Parameters:
  106. /// - key: The key for the key-value pair.
  107. /// - value: The value to be associated to the given key. If it's a binary value, then the associated
  108. /// key must end in "-bin", otherwise, this method will produce an assertion failure.
  109. init(key: String, value: Value) {
  110. if case .binary = value {
  111. assert(key.hasSuffix("-bin"), "Keys for binary values must end in -bin")
  112. }
  113. self.key = key
  114. self.value = value
  115. }
  116. }
  117. private var elements: [KeyValuePair]
  118. /// The Metadata collection's capacity.
  119. public var capacity: Int {
  120. self.elements.capacity
  121. }
  122. /// Initialize an empty Metadata collection.
  123. public init() {
  124. self.elements = []
  125. }
  126. /// Initialize `Metadata` from a `Sequence` of `Element`s.
  127. public init(_ elements: some Sequence<Element>) {
  128. self.elements = elements.map { key, value in
  129. KeyValuePair(key: key, value: value)
  130. }
  131. }
  132. /// Reserve the specified minimum capacity in the collection.
  133. ///
  134. /// - Parameter minimumCapacity: The minimum capacity to reserve in the collection.
  135. public mutating func reserveCapacity(_ minimumCapacity: Int) {
  136. self.elements.reserveCapacity(minimumCapacity)
  137. }
  138. /// Add a new key-value pair, where the value is a string.
  139. ///
  140. /// - Parameters:
  141. /// - stringValue: The string value to be associated with the given key.
  142. /// - key: The key to be associated with the given value.
  143. public mutating func addString(_ stringValue: String, forKey key: String) {
  144. self.addValue(.string(stringValue), forKey: key)
  145. }
  146. /// Add a new key-value pair, where the value is binary data, in the form of `[UInt8]`.
  147. ///
  148. /// - Parameters:
  149. /// - binaryValue: The binary data (i.e., `[UInt8]`) to be associated with the given key.
  150. /// - key: The key to be associated with the given value. Must end in "-bin".
  151. public mutating func addBinary(_ binaryValue: [UInt8], forKey key: String) {
  152. self.addValue(.binary(binaryValue), forKey: key)
  153. }
  154. /// Add a new key-value pair.
  155. ///
  156. /// - Parameters:
  157. /// - value: The ``Value`` to be associated with the given key.
  158. /// - key: The key to be associated with the given value. If value is binary, it must end in "-bin".
  159. internal mutating func addValue(_ value: Value, forKey key: String) {
  160. self.elements.append(.init(key: key, value: value))
  161. }
  162. /// Add the contents of a `Sequence` of key-value pairs to this `Metadata` instance.
  163. ///
  164. /// - Parameter other: the `Sequence` whose key-value pairs should be added into this `Metadata` instance.
  165. public mutating func add(contentsOf other: some Sequence<Element>) {
  166. self.elements.append(contentsOf: other.map(KeyValuePair.init))
  167. }
  168. /// Add the contents of another `Metadata` to this instance.
  169. ///
  170. /// - Parameter other: the `Metadata` whose key-value pairs should be added into this one.
  171. public mutating func add(contentsOf other: Metadata) {
  172. self.elements.append(contentsOf: other.elements)
  173. }
  174. /// Removes all values associated with the given key.
  175. ///
  176. /// - Parameter key: The key for which all values should be removed.
  177. ///
  178. /// - Complexity: O(*n*), where *n* is the number of entries in the metadata instance.
  179. public mutating func removeAllValues(forKey key: String) {
  180. elements.removeAll { metadataKeyValue in
  181. metadataKeyValue.key.isEqualCaseInsensitiveASCIIBytes(to: key)
  182. }
  183. }
  184. /// Adds a key-value pair to the collection, where the value is a string.
  185. ///
  186. /// If there are pairs already associated to the given key, they will all be removed first, and the new pair
  187. /// will be added. If no pairs are present with the given key, a new one will be added.
  188. ///
  189. /// - Parameters:
  190. /// - stringValue: The string value to be associated with the given key.
  191. /// - key: The key to be associated with the given value.
  192. ///
  193. /// - Complexity: O(*n*), where *n* is the number of entries in the metadata instance.
  194. public mutating func replaceOrAddString(_ stringValue: String, forKey key: String) {
  195. self.replaceOrAddValue(.string(stringValue), forKey: key)
  196. }
  197. /// Adds a key-value pair to the collection, where the value is `[UInt8]`.
  198. ///
  199. /// If there are pairs already associated to the given key, they will all be removed first, and the new pair
  200. /// will be added. If no pairs are present with the given key, a new one will be added.
  201. ///
  202. /// - Parameters:
  203. /// - binaryValue: The `[UInt8]` to be associated with the given key.
  204. /// - key: The key to be associated with the given value. Must end in "-bin".
  205. ///
  206. /// - Complexity: O(*n*), where *n* is the number of entries in the metadata instance.
  207. public mutating func replaceOrAddBinary(_ binaryValue: [UInt8], forKey key: String) {
  208. self.replaceOrAddValue(.binary(binaryValue), forKey: key)
  209. }
  210. /// Adds a key-value pair to the collection.
  211. ///
  212. /// If there are pairs already associated to the given key, they will all be removed first, and the new pair
  213. /// will be added. If no pairs are present with the given key, a new one will be added.
  214. ///
  215. /// - Parameters:
  216. /// - value: The ``Value`` to be associated with the given key.
  217. /// - key: The key to be associated with the given value. If value is binary, it must end in "-bin".
  218. ///
  219. /// - Complexity: O(*n*), where *n* is the number of entries in the metadata instance.
  220. internal mutating func replaceOrAddValue(_ value: Value, forKey key: String) {
  221. self.removeAllValues(forKey: key)
  222. self.elements.append(.init(key: key, value: value))
  223. }
  224. /// Removes all key-value pairs from this metadata instance.
  225. ///
  226. /// - Parameter keepingCapacity: Whether the current capacity should be kept or reset.
  227. ///
  228. /// - Complexity: O(*n*), where *n* is the number of entries in the metadata instance.
  229. public mutating func removeAll(keepingCapacity: Bool) {
  230. self.elements.removeAll(keepingCapacity: keepingCapacity)
  231. }
  232. /// Removes all elements which match the given predicate.
  233. ///
  234. /// - Parameter predicate: Returns `true` if the element should be removed.
  235. ///
  236. /// - Complexity: O(*n*), where *n* is the number of entries in the metadata instance.
  237. public mutating func removeAll(
  238. where predicate: (_ key: String, _ value: Value) throws -> Bool
  239. ) rethrows {
  240. try self.elements.removeAll { pair in
  241. try predicate(pair.key, pair.value)
  242. }
  243. }
  244. }
  245. @available(gRPCSwift 2.0, *)
  246. extension Metadata: RandomAccessCollection {
  247. public typealias Element = (key: String, value: Value)
  248. public struct Index: Comparable, Sendable {
  249. @usableFromInline
  250. let _base: Array<Element>.Index
  251. @inlinable
  252. init(_base: Array<Element>.Index) {
  253. self._base = _base
  254. }
  255. @inlinable
  256. public static func < (lhs: Index, rhs: Index) -> Bool {
  257. return lhs._base < rhs._base
  258. }
  259. }
  260. public var startIndex: Index {
  261. return .init(_base: self.elements.startIndex)
  262. }
  263. public var endIndex: Index {
  264. return .init(_base: self.elements.endIndex)
  265. }
  266. public func index(before i: Index) -> Index {
  267. return .init(_base: self.elements.index(before: i._base))
  268. }
  269. public func index(after i: Index) -> Index {
  270. return .init(_base: self.elements.index(after: i._base))
  271. }
  272. public subscript(position: Index) -> Element {
  273. let keyValuePair = self.elements[position._base]
  274. return (key: keyValuePair.key, value: keyValuePair.value)
  275. }
  276. }
  277. @available(gRPCSwift 2.0, *)
  278. extension Metadata {
  279. /// A sequence of metadata values for a given key.
  280. public struct Values: Sequence, Sendable {
  281. /// An iterator for all metadata ``Value``s associated with a given key.
  282. public struct Iterator: IteratorProtocol, Sendable {
  283. private var metadataIterator: Metadata.Iterator
  284. private let key: String
  285. init(forKey key: String, metadata: Metadata) {
  286. self.metadataIterator = metadata.makeIterator()
  287. self.key = key
  288. }
  289. public mutating func next() -> Value? {
  290. while let nextKeyValue = self.metadataIterator.next() {
  291. if nextKeyValue.key.isEqualCaseInsensitiveASCIIBytes(to: self.key) {
  292. return nextKeyValue.value
  293. }
  294. }
  295. return nil
  296. }
  297. }
  298. private let key: String
  299. private let metadata: Metadata
  300. internal init(key: String, metadata: Metadata) {
  301. self.key = key
  302. self.metadata = metadata
  303. }
  304. public func makeIterator() -> Iterator {
  305. Iterator(forKey: self.key, metadata: self.metadata)
  306. }
  307. }
  308. /// Get a ``Values`` sequence for a given key.
  309. ///
  310. /// - Parameter key: The returned sequence will only return values for this key.
  311. ///
  312. /// - Returns: A sequence containing all values for the given key.
  313. public subscript(_ key: String) -> Values {
  314. Values(key: key, metadata: self)
  315. }
  316. }
  317. @available(gRPCSwift 2.0, *)
  318. extension Metadata {
  319. /// A sequence of metadata string values for a given key.
  320. public struct StringValues: Sequence, Sendable {
  321. /// An iterator for all string values associated with a given key.
  322. ///
  323. /// This iterator will only return values originally stored as strings for a given key.
  324. public struct Iterator: IteratorProtocol, Sendable {
  325. private var values: Values.Iterator
  326. init(values: Values) {
  327. self.values = values.makeIterator()
  328. }
  329. public mutating func next() -> String? {
  330. while let value = self.values.next() {
  331. switch value {
  332. case .string(let stringValue):
  333. return stringValue
  334. case .binary:
  335. continue
  336. }
  337. }
  338. return nil
  339. }
  340. }
  341. private let key: String
  342. private let metadata: Metadata
  343. internal init(key: String, metadata: Metadata) {
  344. self.key = key
  345. self.metadata = metadata
  346. }
  347. public func makeIterator() -> Iterator {
  348. Iterator(values: Values(key: self.key, metadata: self.metadata))
  349. }
  350. }
  351. /// Get a ``StringValues`` sequence for a given key.
  352. ///
  353. /// - Parameter key: The returned sequence will only return string values for this key.
  354. ///
  355. /// - Returns: A sequence containing string values for the given key.
  356. public subscript(stringValues key: String) -> StringValues {
  357. StringValues(key: key, metadata: self)
  358. }
  359. }
  360. @available(gRPCSwift 2.0, *)
  361. extension Metadata {
  362. /// A sequence of metadata binary values for a given key.
  363. public struct BinaryValues: Sequence, Sendable {
  364. /// An iterator for all binary data values associated with a given key.
  365. ///
  366. /// This iterator will return values originally stored as binary data for a given key, and will also try to
  367. /// decode values stored as strings as if they were base64-encoded strings.
  368. public struct Iterator: IteratorProtocol, Sendable {
  369. private var values: Values.Iterator
  370. init(values: Values) {
  371. self.values = values.makeIterator()
  372. }
  373. public mutating func next() -> [UInt8]? {
  374. while let value = self.values.next() {
  375. switch value {
  376. case .string(let stringValue):
  377. do {
  378. return try Base64.decode(string: stringValue, options: [.omitPaddingCharacter])
  379. } catch {
  380. continue
  381. }
  382. case .binary(let binaryValue):
  383. return binaryValue
  384. }
  385. }
  386. return nil
  387. }
  388. }
  389. private let key: String
  390. private let metadata: Metadata
  391. internal init(key: String, metadata: Metadata) {
  392. self.key = key
  393. self.metadata = metadata
  394. }
  395. public func makeIterator() -> Iterator {
  396. Iterator(values: Values(key: self.key, metadata: self.metadata))
  397. }
  398. }
  399. /// A subscript to get a ``BinaryValues`` sequence for a given key.
  400. ///
  401. /// As it's iterated, this sequence will return values originally stored as binary data for a given key, and will
  402. /// also try to decode values stored as strings as if they were base64-encoded strings; only strings that
  403. /// are successfully decoded will be returned.
  404. ///
  405. /// - Parameter key: The returned sequence will only return binary (i.e. `[UInt8]`) values for this key.
  406. ///
  407. /// - Returns: A sequence containing binary (i.e. `[UInt8]`) values for the given key.
  408. ///
  409. /// - SeeAlso: ``BinaryValues/Iterator``.
  410. public subscript(binaryValues key: String) -> BinaryValues {
  411. BinaryValues(key: key, metadata: self)
  412. }
  413. }
  414. @available(gRPCSwift 2.0, *)
  415. extension Metadata: ExpressibleByDictionaryLiteral {
  416. public init(dictionaryLiteral elements: (String, Value)...) {
  417. self.elements = elements.map { KeyValuePair(key: $0, value: $1) }
  418. }
  419. }
  420. @available(gRPCSwift 2.0, *)
  421. extension Metadata: ExpressibleByArrayLiteral {
  422. public init(arrayLiteral elements: (String, Value)...) {
  423. self.elements = elements.map { KeyValuePair(key: $0, value: $1) }
  424. }
  425. }
  426. @available(gRPCSwift 2.0, *)
  427. extension Metadata.Value: ExpressibleByStringLiteral {
  428. public init(stringLiteral value: StringLiteralType) {
  429. self = .string(value)
  430. }
  431. }
  432. @available(gRPCSwift 2.0, *)
  433. extension Metadata.Value: ExpressibleByStringInterpolation {
  434. public init(stringInterpolation: DefaultStringInterpolation) {
  435. self = .string(String(stringInterpolation: stringInterpolation))
  436. }
  437. }
  438. @available(gRPCSwift 2.0, *)
  439. extension Metadata.Value: ExpressibleByArrayLiteral {
  440. public typealias ArrayLiteralElement = UInt8
  441. public init(arrayLiteral elements: ArrayLiteralElement...) {
  442. self = .binary(elements)
  443. }
  444. }
  445. @available(gRPCSwift 2.0, *)
  446. extension Metadata: CustomStringConvertible {
  447. public var description: String {
  448. if self.isEmpty {
  449. return "[:]"
  450. } else {
  451. let elements = self.map { "\(String(reflecting: $0.key)): \(String(reflecting: $0.value))" }
  452. .joined(separator: ", ")
  453. return "[\(elements)]"
  454. }
  455. }
  456. }
  457. @available(gRPCSwift 2.0, *)
  458. extension Metadata.Value: CustomStringConvertible {
  459. public var description: String {
  460. switch self {
  461. case .string(let stringValue):
  462. return String(describing: stringValue)
  463. case .binary(let binaryValue):
  464. return String(describing: binaryValue)
  465. }
  466. }
  467. }
  468. @available(gRPCSwift 2.0, *)
  469. extension Metadata.Value: CustomDebugStringConvertible {
  470. public var debugDescription: String {
  471. switch self {
  472. case .string(let stringValue):
  473. return String(reflecting: stringValue)
  474. case .binary(let binaryValue):
  475. return String(reflecting: binaryValue)
  476. }
  477. }
  478. }