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