2
0

ServerCallContext.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. /*
  2. * Copyright 2019, 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. import Foundation
  17. import Logging
  18. import NIO
  19. import NIOHPACK
  20. import NIOHTTP1
  21. import SwiftProtobuf
  22. /// Protocol declaring a minimum set of properties exposed by *all* types of call contexts.
  23. public protocol ServerCallContext: AnyObject {
  24. /// The event loop this call is served on.
  25. var eventLoop: EventLoop { get }
  26. /// Request headers for this request.
  27. var headers: HPACKHeaders { get }
  28. /// A 'UserInfo' dictionary.
  29. var userInfo: UserInfo { get set }
  30. /// The logger used for this call.
  31. var logger: Logger { get }
  32. /// Whether compression should be enabled for responses, defaulting to `true`. Note that for
  33. /// this value to take effect compression must have been enabled on the server and a compression
  34. /// algorithm must have been negotiated with the client.
  35. var compressionEnabled: Bool { get set }
  36. }
  37. /// Base class providing data provided to the framework user for all server calls.
  38. open class ServerCallContextBase: ServerCallContext {
  39. public let eventLoop: EventLoop
  40. public let headers: HPACKHeaders
  41. public let logger: Logger
  42. public var compressionEnabled: Bool = true
  43. /// - Important: While `UserInfo` has value-semantics, this property retrieves from, and sets a
  44. /// reference wrapped `UserInfo`. The contexts passed to interceptors provide the same
  45. /// reference. As such this may be used as a mechanism to pass information between interceptors
  46. /// and service providers.
  47. public var userInfo: UserInfo {
  48. get {
  49. return self.userInfoRef.value
  50. }
  51. set {
  52. self.userInfoRef.value = newValue
  53. }
  54. }
  55. /// A reference to an underlying `UserInfo`. We share this with the interceptors.
  56. private let userInfoRef: Ref<UserInfo>
  57. /// Metadata to return at the end of the RPC. If this is required it should be updated before
  58. /// the `responsePromise` or `statusPromise` is fulfilled.
  59. public var trailers = HPACKHeaders()
  60. public convenience init(
  61. eventLoop: EventLoop,
  62. headers: HPACKHeaders,
  63. logger: Logger,
  64. userInfo: UserInfo = UserInfo()
  65. ) {
  66. self.init(eventLoop: eventLoop, headers: headers, logger: logger, userInfoRef: .init(userInfo))
  67. }
  68. internal init(
  69. eventLoop: EventLoop,
  70. headers: HPACKHeaders,
  71. logger: Logger,
  72. userInfoRef: Ref<UserInfo>
  73. ) {
  74. self.eventLoop = eventLoop
  75. self.headers = headers
  76. self.userInfoRef = userInfoRef
  77. self.logger = logger
  78. }
  79. @available(*, deprecated, renamed: "init(eventLoop:headers:logger:userInfo:)")
  80. public init(eventLoop: EventLoop, request: HTTPRequestHead, logger: Logger) {
  81. self.eventLoop = eventLoop
  82. self.headers = HPACKHeaders(httpHeaders: request.headers, normalizeHTTPHeaders: false)
  83. self.logger = logger
  84. self.userInfoRef = .init(UserInfo())
  85. }
  86. /// Processes an error, transforming it into a 'GRPCStatus' and any trailers to send to the peer.
  87. internal func processObserverError(
  88. _ error: Error,
  89. delegate: ServerErrorDelegate?
  90. ) -> (GRPCStatus, HPACKHeaders) {
  91. // Observe the error if we have a delegate.
  92. delegate?.observeRequestHandlerError(error, headers: self.headers)
  93. // What status are we terminating this RPC with?
  94. // - If we have a delegate, try transforming the error. If the delegate returns trailers, merge
  95. // them with any on the call context.
  96. // - If we don't have a delegate, then try to transform the error to a status.
  97. // - Fallback to a generic error.
  98. let status: GRPCStatus
  99. let trailers: HPACKHeaders
  100. if let transformed = delegate?.transformRequestHandlerError(error, headers: self.headers) {
  101. status = transformed.status
  102. if var transformedTrailers = transformed.trailers {
  103. // The delegate returned trailers: merge in those from the context as well.
  104. transformedTrailers.add(contentsOf: self.trailers)
  105. trailers = transformedTrailers
  106. } else {
  107. trailers = self.trailers
  108. }
  109. } else if let grpcStatusTransformable = error as? GRPCStatusTransformable {
  110. status = grpcStatusTransformable.makeGRPCStatus()
  111. trailers = self.trailers
  112. } else {
  113. // Eh... well, we don't what status to use. Use a generic one.
  114. status = .processingError
  115. trailers = self.trailers
  116. }
  117. return (status, trailers)
  118. }
  119. }