ClientTracingInterceptor.swift 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. /*
  2. * Copyright 2024, 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 GRPCCore
  17. import Tracing
  18. /// A client interceptor that injects tracing information into the request.
  19. ///
  20. /// The tracing information is taken from the current `ServiceContext`, and injected into the request's
  21. /// metadata. It will then be picked up by the server-side ``ServerTracingInterceptor``.
  22. ///
  23. /// For more information, refer to the documentation for `swift-distributed-tracing`.
  24. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  25. public struct ClientTracingInterceptor: ClientInterceptor {
  26. private let injector: ClientRequestInjector
  27. private let emitEventOnEachWrite: Bool
  28. /// Create a new instance of a ``ClientTracingInterceptor``.
  29. ///
  30. /// - Parameter emitEventOnEachWrite: If `true`, each request part sent and response part
  31. /// received will be recorded as a separate event in a tracing span. Otherwise, only the request/response
  32. /// start and end will be recorded as events.
  33. public init(emitEventOnEachWrite: Bool = false) {
  34. self.injector = ClientRequestInjector()
  35. self.emitEventOnEachWrite = emitEventOnEachWrite
  36. }
  37. /// This interceptor will inject as the request's metadata whatever `ServiceContext` key-value pairs
  38. /// have been made available by the tracing implementation bootstrapped in your application.
  39. ///
  40. /// Which key-value pairs are injected will depend on the specific tracing implementation
  41. /// that has been configured when bootstrapping `swift-distributed-tracing` in your application.
  42. public func intercept<Input, Output>(
  43. request: ClientRequest.Stream<Input>,
  44. context: ClientInterceptorContext,
  45. next: @Sendable (ClientRequest.Stream<Input>, ClientInterceptorContext) async throws ->
  46. ClientResponse.Stream<Output>
  47. ) async throws -> ClientResponse.Stream<Output> where Input: Sendable, Output: Sendable {
  48. var request = request
  49. let tracer = InstrumentationSystem.tracer
  50. let serviceContext = ServiceContext.current ?? .topLevel
  51. tracer.inject(
  52. serviceContext,
  53. into: &request.metadata,
  54. using: self.injector
  55. )
  56. return try await tracer.withSpan(
  57. context.descriptor.fullyQualifiedMethod,
  58. context: serviceContext,
  59. ofKind: .client
  60. ) { span in
  61. span.addEvent("Request started")
  62. if self.emitEventOnEachWrite {
  63. let wrappedProducer = request.producer
  64. request.producer = { writer in
  65. let eventEmittingWriter = HookedWriter(
  66. wrapping: writer,
  67. beforeEachWrite: {
  68. span.addEvent("Sending request part")
  69. },
  70. afterEachWrite: {
  71. span.addEvent("Sent request part")
  72. }
  73. )
  74. do {
  75. try await wrappedProducer(RPCWriter(wrapping: eventEmittingWriter))
  76. } catch {
  77. span.addEvent("Error encountered")
  78. throw error
  79. }
  80. span.addEvent("Request end")
  81. }
  82. }
  83. var response: ClientResponse.Stream<Output>
  84. do {
  85. response = try await next(request, context)
  86. } catch {
  87. span.addEvent("Error encountered")
  88. throw error
  89. }
  90. switch response.accepted {
  91. case .success(var success):
  92. if self.emitEventOnEachWrite {
  93. let onEachPartRecordingSequence = success.bodyParts.map { element in
  94. span.addEvent("Received response part")
  95. return element
  96. }
  97. let onFinishRecordingSequence = OnFinishAsyncSequence(
  98. wrapping: onEachPartRecordingSequence
  99. ) {
  100. span.addEvent("Received response end")
  101. }
  102. success.bodyParts = RPCAsyncSequence(wrapping: onFinishRecordingSequence)
  103. response.accepted = .success(success)
  104. } else {
  105. let onFinishRecordingSequence = OnFinishAsyncSequence(wrapping: success.bodyParts) {
  106. span.addEvent("Received response end")
  107. }
  108. success.bodyParts = RPCAsyncSequence(wrapping: onFinishRecordingSequence)
  109. response.accepted = .success(success)
  110. }
  111. case .failure:
  112. span.addEvent("Received error response")
  113. }
  114. return response
  115. }
  116. }
  117. }
  118. /// An injector responsible for injecting the required instrumentation keys from the `ServiceContext` into
  119. /// the request metadata.
  120. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  121. struct ClientRequestInjector: Instrumentation.Injector {
  122. typealias Carrier = Metadata
  123. func inject(_ value: String, forKey key: String, into carrier: inout Carrier) {
  124. carrier.addString(value, forKey: key)
  125. }
  126. }