diff --git a/.swiftformat b/.swiftformat index 1145ef0..04c2b62 100644 --- a/.swiftformat +++ b/.swiftformat @@ -1,6 +1,6 @@ # file options ---swiftversion 5.0 +--swiftversion 5.2 --exclude .build --exclude Tests/LinuxMain.swift --exclude **/*Tests+XCTest.swift @@ -12,6 +12,7 @@ --self insert --stripunusedargs closure-only --wraparguments before-first +--extensionacl on-declarations # rules diff --git a/IntegrationTests/allocation-counter-tests-framework/run-allocation-counter.sh b/IntegrationTests/allocation-counter-tests-framework/run-allocation-counter.sh index 52f16f8..d8ceb74 100755 --- a/IntegrationTests/allocation-counter-tests-framework/run-allocation-counter.sh +++ b/IntegrationTests/allocation-counter-tests-framework/run-allocation-counter.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/IntegrationTests/allocation-counter-tests-framework/template/AtomicCounter/Sources/AtomicCounter/include/atomic-counter.h b/IntegrationTests/allocation-counter-tests-framework/template/AtomicCounter/Sources/AtomicCounter/include/atomic-counter.h index 4ae6290..03098d1 100644 --- a/IntegrationTests/allocation-counter-tests-framework/template/AtomicCounter/Sources/AtomicCounter/include/atomic-counter.h +++ b/IntegrationTests/allocation-counter-tests-framework/template/AtomicCounter/Sources/AtomicCounter/include/atomic-counter.h @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/IntegrationTests/allocation-counter-tests-framework/template/AtomicCounter/Sources/AtomicCounter/src/atomic-counter.c b/IntegrationTests/allocation-counter-tests-framework/template/AtomicCounter/Sources/AtomicCounter/src/atomic-counter.c index a8c1b94..faca860 100644 --- a/IntegrationTests/allocation-counter-tests-framework/template/AtomicCounter/Sources/AtomicCounter/src/atomic-counter.c +++ b/IntegrationTests/allocation-counter-tests-framework/template/AtomicCounter/Sources/AtomicCounter/src/atomic-counter.c @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoHook/Sources/HookedFunctions/include/hooked-functions.h b/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoHook/Sources/HookedFunctions/include/hooked-functions.h index 226ebff..24b006a 100644 --- a/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoHook/Sources/HookedFunctions/include/hooked-functions.h +++ b/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoHook/Sources/HookedFunctions/include/hooked-functions.h @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoHook/Sources/HookedFunctions/src/hooked-functions.c b/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoHook/Sources/HookedFunctions/src/hooked-functions.c index 018c8ad..ca1257b 100644 --- a/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoHook/Sources/HookedFunctions/src/hooked-functions.c +++ b/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoHook/Sources/HookedFunctions/src/hooked-functions.c @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoNotHook/Sources/HookedFunctions/include/hooked-functions.h b/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoNotHook/Sources/HookedFunctions/include/hooked-functions.h index 5a87dd3..e97ebea 100644 --- a/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoNotHook/Sources/HookedFunctions/include/hooked-functions.h +++ b/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoNotHook/Sources/HookedFunctions/include/hooked-functions.h @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoNotHook/Sources/HookedFunctions/src/hooked-functions.c b/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoNotHook/Sources/HookedFunctions/src/hooked-functions.c index 8588925..38f49a3 100644 --- a/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoNotHook/Sources/HookedFunctions/src/hooked-functions.c +++ b/IntegrationTests/allocation-counter-tests-framework/template/HookedFunctionsDoNotHook/Sources/HookedFunctions/src/hooked-functions.c @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/IntegrationTests/allocation-counter-tests-framework/template/Sources/bootstrapDoHook/main.c b/IntegrationTests/allocation-counter-tests-framework/template/Sources/bootstrapDoHook/main.c index ecb880d..020014b 100644 --- a/IntegrationTests/allocation-counter-tests-framework/template/Sources/bootstrapDoHook/main.c +++ b/IntegrationTests/allocation-counter-tests-framework/template/Sources/bootstrapDoHook/main.c @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/IntegrationTests/allocation-counter-tests-framework/template/Sources/bootstrapDoNotHook/main.c b/IntegrationTests/allocation-counter-tests-framework/template/Sources/bootstrapDoNotHook/main.c index 8fb5657..c2fc0fa 100644 --- a/IntegrationTests/allocation-counter-tests-framework/template/Sources/bootstrapDoNotHook/main.c +++ b/IntegrationTests/allocation-counter-tests-framework/template/Sources/bootstrapDoNotHook/main.c @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/IntegrationTests/allocation-counter-tests-framework/template/scaffolding.swift b/IntegrationTests/allocation-counter-tests-framework/template/scaffolding.swift index 4244154..c956428 100644 --- a/IntegrationTests/allocation-counter-tests-framework/template/scaffolding.swift +++ b/IntegrationTests/allocation-counter-tests-framework/template/scaffolding.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/IntegrationTests/plugin_echo.sh b/IntegrationTests/plugin_echo.sh index 658026a..a11ed4e 100644 --- a/IntegrationTests/plugin_echo.sh +++ b/IntegrationTests/plugin_echo.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/IntegrationTests/plugin_junit_xml.sh b/IntegrationTests/plugin_junit_xml.sh index 0eebb6a..3a3f6db 100644 --- a/IntegrationTests/plugin_junit_xml.sh +++ b/IntegrationTests/plugin_junit_xml.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/IntegrationTests/run-single-test.sh b/IntegrationTests/run-single-test.sh index b49a867..3b97953 100755 --- a/IntegrationTests/run-single-test.sh +++ b/IntegrationTests/run-single-test.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/IntegrationTests/run-tests.sh b/IntegrationTests/run-tests.sh index 1a8f750..80848e6 100755 --- a/IntegrationTests/run-tests.sh +++ b/IntegrationTests/run-tests.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/IntegrationTests/test_functions.sh b/IntegrationTests/test_functions.sh index d691d3d..faddb0f 100644 --- a/IntegrationTests/test_functions.sh +++ b/IntegrationTests/test_functions.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/IntegrationTests/tests_01_performance/defines.sh b/IntegrationTests/tests_01_performance/defines.sh index 2dc8b63..91d9a56 100644 --- a/IntegrationTests/tests_01_performance/defines.sh +++ b/IntegrationTests/tests_01_performance/defines.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/IntegrationTests/tests_01_performance/test_01_allocation_counts.sh b/IntegrationTests/tests_01_performance/test_01_allocation_counts.sh index 3faeaee..c5067f8 100644 --- a/IntegrationTests/tests_01_performance/test_01_allocation_counts.sh +++ b/IntegrationTests/tests_01_performance/test_01_allocation_counts.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/IntegrationTests/tests_01_performance/test_01_resources/run-nio-alloc-counter-tests.sh b/IntegrationTests/tests_01_performance/test_01_resources/run-nio-alloc-counter-tests.sh index c2b4cb8..5e79cb1 100755 --- a/IntegrationTests/tests_01_performance/test_01_resources/run-nio-alloc-counter-tests.sh +++ b/IntegrationTests/tests_01_performance/test_01_resources/run-nio-alloc-counter-tests.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/IntegrationTests/tests_01_performance/test_01_resources/shared.swift b/IntegrationTests/tests_01_performance/test_01_resources/shared.swift index bb551d2..f17f884 100644 --- a/IntegrationTests/tests_01_performance/test_01_resources/shared.swift +++ b/IntegrationTests/tests_01_performance/test_01_resources/shared.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -25,8 +26,8 @@ // //===----------------------------------------------------------------------===// -import Baggage import Foundation +import InstrumentationBaggage @inline(never) func take1(context: BaggageContext) -> Int { diff --git a/IntegrationTests/tests_01_performance/test_01_resources/test_001_pass_around_static_strings_small.swift b/IntegrationTests/tests_01_performance/test_01_resources/test_001_pass_around_static_strings_small.swift index 2bd23b4..013bb4a 100644 --- a/IntegrationTests/tests_01_performance/test_01_resources/test_001_pass_around_static_strings_small.swift +++ b/IntegrationTests/tests_01_performance/test_01_resources/test_001_pass_around_static_strings_small.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -25,7 +26,7 @@ // //===----------------------------------------------------------------------===// -import Baggage +import InstrumentationBaggage func run(identifier: String) { measure(identifier: identifier) { diff --git a/IntegrationTests/tests_01_performance/test_01_resources/test_002_pass_around_static_strings_large.swift b/IntegrationTests/tests_01_performance/test_01_resources/test_002_pass_around_static_strings_large.swift index 5f4f01b..148dd8b 100644 --- a/IntegrationTests/tests_01_performance/test_01_resources/test_002_pass_around_static_strings_large.swift +++ b/IntegrationTests/tests_01_performance/test_01_resources/test_002_pass_around_static_strings_large.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -25,7 +26,7 @@ // //===----------------------------------------------------------------------===// -import Baggage +import InstrumentationBaggage func run(identifier: String) { measure(identifier: identifier) { diff --git a/Package.swift b/Package.swift index cea91ef..1307d58 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.0 +// swift-tools-version:5.2 import PackageDescription let package = Package( @@ -6,10 +6,9 @@ let package = Package( products: [ .library(name: "Instrumentation", targets: ["Instrumentation"]), .library(name: "Tracing", targets: ["Tracing"]), - .library(name: "TracingOpenTelemetrySupport", targets: ["TracingOpenTelemetrySupport"]), ], dependencies: [ - .package(url: "https://github.com/apple/swift-distributed-tracing-baggage.git", from: "0.1.1") + .package(url: "https://github.com/apple/swift-distributed-tracing-baggage.git", .upToNextMinor(from: "0.2.0")), ], targets: [ // ==== -------------------------------------------------------------------------------------------------------- @@ -18,13 +17,13 @@ let package = Package( .target( name: "Instrumentation", dependencies: [ - "Baggage", + .product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"), ] ), .testTarget( name: "InstrumentationTests", dependencies: [ - "Instrumentation", + .target(name: "Instrumentation"), ] ), @@ -34,29 +33,13 @@ let package = Package( .target( name: "Tracing", dependencies: [ - "Instrumentation", + .target(name: "Instrumentation"), ] ), .testTarget( name: "TracingTests", dependencies: [ - "Tracing", - ] - ), - - // ==== ---------------------------------------------------------------------------------------------------------------- - // MARK: Support libraries - - .target( - name: "TracingOpenTelemetrySupport", - dependencies: [ - "Tracing" - ] - ), - .testTarget( - name: "TracingOpenTelemetrySupportTests", - dependencies: [ - "TracingOpenTelemetrySupport", + .target(name: "Tracing"), ] ), @@ -66,10 +49,9 @@ let package = Package( .target( name: "_TracingBenchmarks", dependencies: [ - "Baggage", - "Tracing", - "TracingOpenTelemetrySupport", - "_TracingBenchmarkTools", + .product(name: "InstrumentationBaggage", package: "swift-distributed-tracing-baggage"), + .target(name: "Tracing"), + .target(name: "_TracingBenchmarkTools"), ] ), .target( diff --git a/README.md b/README.md index 4f68249..4ed15d4 100644 --- a/README.md +++ b/README.md @@ -9,24 +9,9 @@ While Swift Distributed Tracing allows building all kinds of _instruments_, whic --- -This project uses the context progagation types defined independently in: +This project uses the context progagation type defined independently in: -- 🧳 [swift-distributed-tracing-baggage](https://github.com/apple/swift-distributed-tracing-baggage) -- [`LoggingContext`](https://apple.github.io/swift-distributed-tracing-baggage/docs/current/Baggage/Protocols/LoggingContext.html) (Swift Log dependency) -- 🧳 [swift-distributed-tracing-baggage-core](https://github.com/apple/swift-distributed-tracing-baggage-core) -- defining [`Baggage`](https://apple.github.io/swift-distributed-tracing-baggage-core/docs/current/CoreBaggage/Structs/Baggage.html) (zero dependencies) - ---- - -### Important note on Adoption - -> ⚠️ ⚠️ ⚠️ -> -> We anticipate the upcoming [Swift Concurrency](https://forums.swift.org/t/swift-concurrency-roadmap/41611) features to have significant impact on the usage of these APIs, if task-local values **(proposal coming soon)** are accepted into the language. -> -> As such, we advice to adopt these APIs carefully, and offer them _optionally_, i.e. provide defaulted values for context parameters such that users do not necessarily have to use them – because the upcoming Swift Concurrency story should enable APIs to gain automatic context propagation using task locals (if the proposal were to be accepted). -> -> At this point in time we would like to focus on Tracer implementations, final API polish and adoption in "glue" libraries between services, such as AsyncHTTPClient, gRPC and similar APIs. -> -> ⚠️ ⚠️ ⚠️ +- 🧳 [swift-distributed-tracing-baggage](https://github.com/apple/swift-distributed-tracing-baggage) -- [`Baggage`](https://apple.github.io/swift-distributed-tracing-baggage/docs/current/InstrumentationBaggage/Structs/Baggage.html) (zero dependencies) --- @@ -579,7 +564,7 @@ When creating a tracer you need to create two types: ```swift import Tracing -private enum TraceIDKey: Baggage.Key { +private enum TraceIDKey: BaggageKey { typealias Value = String } diff --git a/Sources/Instrumentation/Instrument.swift b/Sources/Instrumentation/Instrument.swift index 128ad08..a7385be 100644 --- a/Sources/Instrumentation/Instrument.swift +++ b/Sources/Instrumentation/Instrument.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,7 +12,7 @@ // //===----------------------------------------------------------------------===// -import CoreBaggage +import InstrumentationBaggage /// Conforming types are used to extract values from a specific `Carrier`. public protocol Extractor { diff --git a/Sources/Instrumentation/InstrumentationSystem.swift b/Sources/Instrumentation/InstrumentationSystem.swift index 403c4a1..203936d 100644 --- a/Sources/Instrumentation/InstrumentationSystem.swift +++ b/Sources/Instrumentation/InstrumentationSystem.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,7 +12,7 @@ // //===----------------------------------------------------------------------===// -import Baggage +import InstrumentationBaggage /// `InstrumentationSystem` is a global facility where the default cross-cutting tool can be configured. /// It is set up just once in a given program to select the desired `Instrument` implementation. @@ -56,14 +57,14 @@ public enum InstrumentationSystem { /// /// Defaults to a no-op `Instrument` if `boostrap` wasn't called before. public static var instrument: Instrument { - return self.lock.withReaderLock { self._instrument } + self.lock.withReaderLock { self._instrument } } } extension InstrumentationSystem { /// :nodoc: INTERNAL API: Do Not Use public static func _findInstrument(where predicate: (Instrument) -> Bool) -> Instrument? { - return self.lock.withReaderLock { + self.lock.withReaderLock { if let multiplex = self._instrument as? MultiplexInstrument { return multiplex.firstInstrument(where: predicate) } else if predicate(self._instrument) { diff --git a/Sources/Instrumentation/Locks.swift b/Sources/Instrumentation/Locks.swift index 9e17107..ae50cb7 100644 --- a/Sources/Instrumentation/Locks.swift +++ b/Sources/Instrumentation/Locks.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -89,7 +90,7 @@ extension ReadWriteLock { /// - Parameter body: The block to execute while holding the lock. /// - Returns: The value returned by the block. @inlinable - internal func withReaderLock(_ body: () throws -> T) rethrows -> T { + func withReaderLock(_ body: () throws -> T) rethrows -> T { self.lockRead() defer { self.unlock() @@ -106,7 +107,7 @@ extension ReadWriteLock { /// - Parameter body: The block to execute while holding the lock. /// - Returns: The value returned by the block. @inlinable - internal func withWriterLock(_ body: () throws -> T) rethrows -> T { + func withWriterLock(_ body: () throws -> T) rethrows -> T { self.lockWrite() defer { self.unlock() diff --git a/Sources/Instrumentation/MultiplexInstrument.swift b/Sources/Instrumentation/MultiplexInstrument.swift index da55af3..ec2bbda 100644 --- a/Sources/Instrumentation/MultiplexInstrument.swift +++ b/Sources/Instrumentation/MultiplexInstrument.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,7 +12,7 @@ // //===----------------------------------------------------------------------===// -import Baggage +import InstrumentationBaggage /// A pseudo-`Instrument` that may be used to instrument using multiple other `Instrument`s across a /// common `BaggageContext`. @@ -29,18 +30,20 @@ public struct MultiplexInstrument { extension MultiplexInstrument { func firstInstrument(where predicate: (Instrument) -> Bool) -> Instrument? { - return self.instruments.first(where: predicate) + self.instruments.first(where: predicate) } } extension MultiplexInstrument: Instrument { public func inject(_ baggage: Baggage, into carrier: inout Carrier, using injector: Inject) - where Inject: Injector, Carrier == Inject.Carrier { + where Inject: Injector, Carrier == Inject.Carrier + { self.instruments.forEach { $0.inject(baggage, into: &carrier, using: injector) } } public func extract(_ carrier: Carrier, into baggage: inout Baggage, using extractor: Extract) - where Extract: Extractor, Carrier == Extract.Carrier { + where Extract: Extractor, Carrier == Extract.Carrier + { self.instruments.forEach { $0.extract(carrier, into: &baggage, using: extractor) } } } diff --git a/Sources/Instrumentation/NoOpInstrument.swift b/Sources/Instrumentation/NoOpInstrument.swift index d4901d4..849b439 100644 --- a/Sources/Instrumentation/NoOpInstrument.swift +++ b/Sources/Instrumentation/NoOpInstrument.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,19 +12,21 @@ // //===----------------------------------------------------------------------===// -import CoreBaggage +import InstrumentationBaggage /// A "no op" implementation of an `Instrument`. public struct NoOpInstrument: Instrument { public init() {} public func inject(_ baggage: Baggage, into carrier: inout Carrier, using injector: Inject) - where Inject: Injector, Carrier == Inject.Carrier { + where Inject: Injector, Carrier == Inject.Carrier + { // no-op } public func extract(_ carrier: Carrier, into baggage: inout Baggage, using extractor: Extract) - where Extract: Extractor, Carrier == Extract.Carrier { + where Extract: Extractor, Carrier == Extract.Carrier + { // no-op } } diff --git a/Sources/Tracing/InstrumentationSystem+Tracing.swift b/Sources/Tracing/InstrumentationSystem+Tracing.swift index fd49e93..1052c1d 100644 --- a/Sources/Tracing/InstrumentationSystem+Tracing.swift +++ b/Sources/Tracing/InstrumentationSystem+Tracing.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -21,6 +22,6 @@ extension InstrumentationSystem { /// /// - Returns: A `Tracer` if the system was bootstrapped with one, and `NoOpTracer` otherwise. public static var tracer: Tracer { - return (self._findInstrument(where: { $0 is Tracer }) as? Tracer) ?? NoOpTracer() + (self._findInstrument(where: { $0 is Tracer }) as? Tracer) ?? NoOpTracer() } } diff --git a/Sources/Tracing/NoOpTracer.swift b/Sources/Tracing/NoOpTracer.swift index d5b3cb3..f5bd716 100644 --- a/Sources/Tracing/NoOpTracer.swift +++ b/Sources/Tracing/NoOpTracer.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,9 +12,9 @@ // //===----------------------------------------------------------------------===// -@_exported import Baggage import Dispatch @_exported import Instrumentation +@_exported import InstrumentationBaggage /// No operation Tracer, used when no tracing is required. public struct NoOpTracer: Tracer { @@ -25,18 +26,20 @@ public struct NoOpTracer: Tracer { ofKind kind: SpanKind, at time: DispatchWallTime ) -> Span { - return NoOpSpan(baggage: baggage) + NoOpSpan(baggage: baggage) } public func forceFlush() {} public func inject(_ baggage: Baggage, into carrier: inout Carrier, using injector: Inject) - where Inject: Injector, Carrier == Inject.Carrier { + where Inject: Injector, Carrier == Inject.Carrier + { // no-op } public func extract(_ carrier: Carrier, into baggage: inout Baggage, using extractor: Extract) - where Extract: Extractor, Carrier == Extract.Carrier { + where Extract: Extractor, Carrier == Extract.Carrier + { // no-op } @@ -58,7 +61,7 @@ public struct NoOpTracer: Tracer { public var attributes: SpanAttributes { get { - return [:] + [:] } set { // ignore diff --git a/Sources/Tracing/Span.swift b/Sources/Tracing/Span.swift index 1ba7b77..d636fc4 100644 --- a/Sources/Tracing/Span.swift +++ b/Sources/Tracing/Span.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,8 +12,8 @@ // //===----------------------------------------------------------------------===// -@_exported import Baggage import Dispatch +@_exported import InstrumentationBaggage /// A `Span` represents an interval from the start of an operation to its end, along with additional metadata included /// with it. A `Span` can be created from a `Baggage` or `LoggingContext` which MAY contain existing span identifiers, @@ -175,7 +176,8 @@ extension NestedSpanAttributesProtocol { extension SpanAttributeNamespace { public subscript(dynamicMember dynamicMember: KeyPath>) -> T? - where T: SpanAttributeConvertible { + where T: SpanAttributeConvertible + { get { let key = NestedSpanAttributes.__namespace[keyPath: dynamicMember] let spanAttribute = self.attributes[key.name]?.toSpanAttribute() @@ -204,7 +206,8 @@ extension SpanAttributeNamespace { } public subscript(dynamicMember dynamicMember: KeyPath) -> Namespace - where Namespace: SpanAttributeNamespace { + where Namespace: SpanAttributeNamespace + { SpanAttribute.int(0)[keyPath: dynamicMember] } } @@ -254,7 +257,7 @@ public enum SpanAttribute: Equatable { /// This is a "magic value" that is used to enable the KeyPath based accessors to specific attributes. internal static var _namespace: SpanAttribute { - return .int(0) + .int(0) } internal var anyValue: Any { @@ -311,7 +314,7 @@ public enum SpanAttribute: Equatable { extension SpanAttribute: SpanAttributeConvertible { public func toSpanAttribute() -> SpanAttribute { - return self + self } } @@ -327,37 +330,37 @@ public protocol SpanAttributeConvertible { extension Array where Element == Int { public func toSpanAttribute() -> SpanAttribute { - return .intArray(self.map(Int64.init)) + .intArray(self.map(Int64.init)) } } extension Array where Element == Int8 { public func toSpanAttribute() -> SpanAttribute { - return .intArray(self.map(Int64.init)) + .intArray(self.map(Int64.init)) } } extension Array where Element == Int16 { public func toSpanAttribute() -> SpanAttribute { - return .intArray(self.map(Int64.init)) + .intArray(self.map(Int64.init)) } } extension Array where Element == Int32 { public func toSpanAttribute() -> SpanAttribute { - return .intArray(self.map(Int64.init)) + .intArray(self.map(Int64.init)) } } extension Array where Element == Int64 { public func toSpanAttribute() -> SpanAttribute { - return .intArray(self) + .intArray(self) } } extension Array where Element == Double { public func toSpanAttribute() -> SpanAttribute { - return .doubleArray(self) + .doubleArray(self) } } @@ -393,7 +396,7 @@ extension Array: SpanAttributeConvertible where Element: SpanAttributeConvertibl extension String: SpanAttributeConvertible { public func toSpanAttribute() -> SpanAttribute { - return .string(self) + .string(self) } } @@ -420,31 +423,31 @@ extension SpanAttribute: ExpressibleByIntegerLiteral { extension Int: SpanAttributeConvertible { public func toSpanAttribute() -> SpanAttribute { - return .int(Int64(self)) + .int(Int64(self)) } } extension Int8: SpanAttributeConvertible { public func toSpanAttribute() -> SpanAttribute { - return .int(Int64(self)) + .int(Int64(self)) } } extension Int16: SpanAttributeConvertible { public func toSpanAttribute() -> SpanAttribute { - return .int(Int64(self)) + .int(Int64(self)) } } extension Int32: SpanAttributeConvertible { public func toSpanAttribute() -> SpanAttribute { - return .int(Int64(self)) + .int(Int64(self)) } } extension Int64: SpanAttributeConvertible { public func toSpanAttribute() -> SpanAttribute { - return .int(self) + .int(self) } } @@ -453,13 +456,13 @@ extension Int64: SpanAttributeConvertible { extension Float: SpanAttributeConvertible { public func toSpanAttribute() -> SpanAttribute { - return .double(Double(self)) + .double(Double(self)) } } extension Double: SpanAttributeConvertible { public func toSpanAttribute() -> SpanAttribute { - return .double(self) + .double(self) } } @@ -474,7 +477,7 @@ extension SpanAttribute: ExpressibleByFloatLiteral { extension Bool: SpanAttributeConvertible { public func toSpanAttribute() -> SpanAttribute { - return .bool(self) + .bool(self) } } @@ -519,7 +522,7 @@ extension SpanAttributes { /// - Returns: The `SpanAttribute` identified by the given name, or `nil` if it's not present. public subscript(_ name: String) -> SpanAttributeConvertible? { get { - return self._attributes[name] + self._attributes[name] } set { self._attributes[name] = newValue?.toSpanAttribute() @@ -543,12 +546,12 @@ extension SpanAttributes { /// - Returns: Number of attributes stored. public var count: Int { - return self._attributes.count + self._attributes.count } /// Returns true if the collection contains no attributes. public var isEmpty: Bool { - return self._attributes.isEmpty + self._attributes.isEmpty } } @@ -568,7 +571,8 @@ extension SpanAttributes { /// Enables for type-safe nested namespaces for attribute accessors. public subscript(dynamicMember dynamicMember: KeyPath) -> Namespace - where Namespace: SpanAttributeNamespace { + where Namespace: SpanAttributeNamespace + { SpanAttribute._namespace[keyPath: dynamicMember] } } diff --git a/Sources/Tracing/Tracer.swift b/Sources/Tracing/Tracer.swift index af68022..4717ad6 100644 --- a/Sources/Tracing/Tracer.swift +++ b/Sources/Tracing/Tracer.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,15 +12,19 @@ // //===----------------------------------------------------------------------===// -@_exported import Baggage import Dispatch @_exported import Instrumentation +@_exported import InstrumentationBaggage /// An `Instrument` with added functionality for distributed tracing. Is uses the span-based tracing model and is /// based on the OpenTracing/OpenTelemetry spec. public protocol Tracer: Instrument { /// Start a new `Span` with the given `Baggage` at a given time. /// + /// - Note: Prefer to use `withSpan` to start a span as it automatically takes care of ending the span, + /// and recording errors when thrown. Use `startSpan` iff you need to pass the span manually to a different + /// location in your source code to end it. + /// /// - Parameters: /// - operationName: The name of the operation being traced. This may be a handler function, database call, ... /// - baggage: The `Baggage` providing information on where to start the new `Span`. @@ -53,77 +58,97 @@ extension Tracer { baggage: Baggage, ofKind kind: SpanKind = .internal ) -> Span { - return self.startSpan(operationName, baggage: baggage, ofKind: kind, at: .now()) + self.startSpan(operationName, baggage: baggage, ofKind: kind, at: .now()) } } // ==== ---------------------------------------------------------------------------------------------------------------- -// MARK: Span creation: with `LoggingContext` +// MARK: Starting spans: `withSpan` extension Tracer { - /// Start a new `Span` with the given `Baggage` starting at `DispatchWallTime.now()`. + /// Execute a specific task within a newly created `Span`. + /// + /// DO NOT `end()` the passed in span manually. It will be ended automatically when the `operation` returns. /// /// - Parameters: /// - operationName: The name of the operation being traced. This may be a handler function, database call, ... - /// - context: Logging context containing a `Baggage` which may contain trace identifiers of a parent `Span`. + /// - baggage: Baggage potentially containing trace identifiers of a parent `Span`. /// - kind: The `SpanKind` of the `Span` to be created. Defaults to `.internal`. - public func startSpan( + /// - operation: operation to wrap in a span start/end and execute immediately + /// - Returns: the value returned by `operation` + /// - Throws: the error the `operation` has thrown (if any) + public func withSpan( _ operationName: String, - context: LoggingContext, - ofKind kind: SpanKind = .internal - ) -> Span { - return self.startSpan(operationName, baggage: context.baggage, ofKind: kind, at: .now()) + baggage: Baggage, + ofKind kind: SpanKind = .internal, + _ operation: (Span) throws -> T + ) rethrows -> T { + let span = self.startSpan(operationName, baggage: baggage, ofKind: kind) + defer { span.end() } + do { + return try operation(span) + } catch { + span.recordError(error) + throw error // rethrow + } } } // ==== ---------------------------------------------------------------------------------------------------------------- -// MARK: Starting spans: `withSpan` +// MARK: Starting spans: Task-local Baggage propagation +#if swift(>=5.5) +@available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) extension Tracer { - /// Execute a specific task within a newly created `Span`. + /// Execute the given operation within a newly created `Span`, + /// started as a child of the currently stored task local `Baggage.current` or as a root span if `nil`. /// - /// DO NOT `end()` the passed in span manually. It will be ended automatically when the `function` returns. + /// DO NOT `end()` the passed in span manually. It will be ended automatically when the `operation` returns. /// /// - Parameters: /// - operationName: The name of the operation being traced. This may be a handler function, database call, ... - /// - context: Logging context containing a `Baggage` which may contain trace identifiers of a parent `Span`. /// - kind: The `SpanKind` of the `Span` to be created. Defaults to `.internal`. - /// - function: function to wrap in a span start/end and execute immediately - /// - Returns: the value returned by `function` - /// - Throws: the error the `function` has thrown (if any) + /// - operation: operation to wrap in a span start/end and execute immediately + /// - Returns: the value returned by `operation` + /// - Throws: the error the `operation` has thrown (if any) public func withSpan( _ operationName: String, - context: LoggingContext, ofKind kind: SpanKind = .internal, - _ function: (Span) throws -> T + _ operation: (Span) throws -> T ) rethrows -> T { - return try self.withSpan(operationName, baggage: context.baggage, function) + try self.withSpan(operationName, baggage: .current ?? .topLevel, ofKind: kind) { span in + try Baggage.$current.withValue(span.baggage) { + try operation(span) + } + } } - /// Execute a specific task within a newly created `Span`. + /// Execute the given async operation within a newly created `Span`, + /// started as a child of the currently stored task local `Baggage.current` or as a root span if `nil`. /// - /// DO NOT `end()` the passed in span manually. It will be ended automatically when the `function` returns. + /// DO NOT `end()` the passed in span manually. It will be ended automatically when the `operation` returns. /// /// - Parameters: /// - operationName: The name of the operation being traced. This may be a handler function, database call, ... - /// - baggage: Baggage potentially containing trace identifiers of a parent `Span`. /// - kind: The `SpanKind` of the `Span` to be created. Defaults to `.internal`. - /// - function: function to wrap in a span start/end and execute immediately - /// - Returns: the value returned by `function` - /// - Throws: the error the `function` has thrown (if any) + /// - operation: operation to wrap in a span start/end and execute immediately + /// - Returns: the value returned by `operation` + /// - Throws: the error the `operation` has thrown (if any) public func withSpan( _ operationName: String, - baggage: Baggage, ofKind kind: SpanKind = .internal, - _ function: (Span) throws -> T - ) rethrows -> T { - let span = self.startSpan(operationName, baggage: baggage, ofKind: kind) + _ operation: (Span) async throws -> T + ) async rethrows -> T { + let span = self.startSpan(operationName, baggage: .current ?? .topLevel, ofKind: kind) defer { span.end() } do { - return try function(span) + return try await Baggage.$current.withValue(span.baggage) { + try await operation(span) + } } catch { span.recordError(error) throw error // rethrow } } } +#endif diff --git a/Sources/TracingOpenTelemetrySupport/SpanAttribute+DatabaseSemantics.swift b/Sources/TracingOpenTelemetrySupport/SpanAttribute+DatabaseSemantics.swift deleted file mode 100644 index 17b7af9..0000000 --- a/Sources/TracingOpenTelemetrySupport/SpanAttribute+DatabaseSemantics.swift +++ /dev/null @@ -1,305 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Distributed Tracing open source project -// -// Copyright (c) 2021 Apple Inc. and the Swift Distributed Tracing project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import Tracing - -extension SpanAttributeName { - /// - SeeAlso: DatabaseAttributes - public enum Database { - /// - SeeAlso: DatabaseAttributes - public static let system = "db.system" - /// - SeeAlso: DatabaseAttributes - public static let connectionString = "db.connection_string" - /// - SeeAlso: DatabaseAttributes - public static let user = "db.user" - /// - SeeAlso: DatabaseAttributes - public static let name = "db.name" - /// - SeeAlso: DatabaseAttributes - public static let statement = "db.statement" - /// - SeeAlso: DatabaseAttributes - public static let operation = "db.operation" - - /// - SeeAlso: DatabaseAttributes.MSSQLAttributes - public enum MSSQL { - /// - SeeAlso: DatabaseAttributes.MSSQLAttributes - public static let instanceName = "db.mssql.instance_name" - } - - /// - SeeAlso: DatabaseAttributes.CassandraAttributes - public enum Cassandra { - /// - SeeAlso: DatabaseAttributes.CassandraAttributes - public static let keyspace = "db.cassandra.keyspace" - } - - /// - SeeAlso: DatabaseAttributes.HBaseAttributes - public enum HBase { - /// - SeeAlso: DatabaseAttributes.HBaseAttributes - public static let namespace = "db.hbase.namespace" - } - - /// - SeeAlso: DatabaseAttributes.RedisAttributes - public enum Redis { - /// - SeeAlso: DatabaseAttributes.RedisAttributes - public static let databaseIndex = "db.redis.database_index" - } - - /// - SeeAlso: DatabaseAttributes.MongoDBAttributes - public enum MongoDB { - /// - SeeAlso: DatabaseAttributes.MongoDBAttributes - public static let collection = "db.mongodb.collection" - } - - /// - SeeAlso: DatabaseAttributes.SQLAttributes - public enum SQL { - /// - SeeAlso: DatabaseAttributes.SQLAttributes - public static let table = "db.sql.table" - } - } -} - -#if swift(>=5.2) -extension SpanAttributes { - /// Semantic database client call attributes. - public var db: DatabaseAttributes { - get { - .init(attributes: self) - } - set { - self = newValue.attributes - } - } -} - -/// Semantic conventions for database client calls as defined in the OpenTelemetry spec. -/// -/// - SeeAlso: [OpenTelemetry: Database attributes](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/database.md) -@dynamicMemberLookup -public struct DatabaseAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - // MARK: - General - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// An identifier for the database management system (DBMS) product being used. See [OpenTelemetry: Database attributes](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/database.md) for a list of well-known identifiers. - public var system: Key { .init(name: SpanAttributeName.Database.system) } - - /// The connection string used to connect to the database. It is recommended to remove embedded credentials. - public var connectionString: Key { .init(name: SpanAttributeName.Database.connectionString) } - - /// Username for accessing the database. - public var user: Key { .init(name: SpanAttributeName.Database.user) } - - /// If no [tech-specific attribute](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/database.md#call-level-attributes-for-specific-technologies) - /// is defined, this attribute is used to report the name of the database being accessed. For commands that switch the database, this should be set to the target database (even if the command fails). - /// - /// - Note: In some SQL databases, the database name to be used is called "schema name". - public var name: Key { .init(name: SpanAttributeName.Database.name) } - - /// The database statement being executed. - /// - /// - Note: The value may be sanitized to exclude sensitive information. - public var statement: Key { .init(name: SpanAttributeName.Database.statement) } - - /// The name of the operation being executed, e.g. the [MongoDB command name](https://docs.mongodb.com/manual/reference/command/#database-operations) - /// such as `findAndModify`, or the SQL keyword. - /// - /// - Note: When setting this to an SQL keyword, it is not recommended to attempt any client-side parsing of `db.statement` just to get this - /// property, but it should be set if the operation name is provided by the library being instrumented. - /// If the SQL statement has an ambiguous operation, or performs more than one operation, this value may be omitted. - public var operation: Key { .init(name: SpanAttributeName.Database.operation) } - } - - // MARK: - MSSQL - - /// Semantic MSSQL client call attributes. - public var mssql: MSSQLAttributes { - get { - .init(attributes: self.attributes) - } - set { - self.attributes = newValue.attributes - } - } - - /// Semantic conventions for MSSQL client calls as defined in the OpenTelemetry spec. - public struct MSSQLAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// The Microsoft SQL Server [instance name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) - /// connecting to. This name is used to determine the port of a named instance. - /// - /// - Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no longer required (but still recommended if non-standard). - public var instanceName: Key { .init(name: SpanAttributeName.Database.MSSQL.instanceName) } - } - } - - // MARK: - Cassandra - - /// Semantic Cassandra client call attributes. - public var cassandra: CassandraAttributes { - get { - .init(attributes: self.attributes) - } - set { - self.attributes = newValue.attributes - } - } - - /// Semantic conventions for Cassandra client calls as defined in the OpenTelemetry spec. - public struct CassandraAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// The name of the keyspace being accessed. To be used instead of the generic `db.name` attribute. - public var keyspace: Key { .init(name: SpanAttributeName.Database.Cassandra.keyspace) } - } - } - - // MARK: - HBase - - /// Semantic HBase client call attributes. - public var hbase: HBaseAttributes { - get { - .init(attributes: self.attributes) - } - set { - self.attributes = newValue.attributes - } - } - - /// Semantic conventions for HBase client calls as defined in the OpenTelemetry spec. - public struct HBaseAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// The [HBase namespace](https://hbase.apache.org/book.html#_namespace) being accessed. - /// To be used instead of the generic `db.name` attribute. - public var namespace: Key { .init(name: SpanAttributeName.Database.HBase.namespace) } - } - } - - // MARK: - Redis - - /// Semantic Redis client call attributes. - public var redis: RedisAttributes { - get { - .init(attributes: self.attributes) - } - set { - self.attributes = newValue.attributes - } - } - - /// Semantic conventions for Redis client calls as defined in the OpenTelemetry spec. - public struct RedisAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// The index of the database being accessed as used in the [`SELECT` command](https://redis.io/commands/select), - /// provided as an integer. To be used instead of the generic `db.name` attribute. - public var databaseIndex: Key { .init(name: SpanAttributeName.Database.Redis.databaseIndex) } - } - } - - // MARK: - MongoDB - - /// Semantic MongoDB client call attributes. - public var mongodb: MongoDBAttributes { - get { - .init(attributes: self.attributes) - } - set { - self.attributes = newValue.attributes - } - } - - /// Semantic conventions for MongoDB client calls as defined in the OpenTelemetry spec. - public struct MongoDBAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// The collection being accessed within the database stated in `db.name`. - public var collection: Key { .init(name: SpanAttributeName.Database.MongoDB.collection) } - } - } - - // MARK: - SQL - - /// Semantic SQL client call attributes. - public var sql: SQLAttributes { - get { - .init(attributes: self.attributes) - } - set { - self.attributes = newValue.attributes - } - } - - /// Semantic conventions for SQL client calls as defined in the OpenTelemetry spec. - public struct SQLAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// The name of the primary table that the operation is acting upon, including the schema name (if applicable). - /// - /// - Note: It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, - /// but it should be set if it is provided by the library being instrumented. - /// If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. - public var table: Key { .init(name: SpanAttributeName.Database.SQL.table) } - } - } -} -#endif diff --git a/Sources/TracingOpenTelemetrySupport/SpanAttribute+EndUserSemantics.swift b/Sources/TracingOpenTelemetrySupport/SpanAttribute+EndUserSemantics.swift deleted file mode 100644 index c8e33e8..0000000 --- a/Sources/TracingOpenTelemetrySupport/SpanAttribute+EndUserSemantics.swift +++ /dev/null @@ -1,66 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Distributed Tracing open source project -// -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import Tracing - -extension SpanAttributeName { - /// - SeeAlso: EndUserAttributes - public enum EndUser { - /// - SeeAlso: EndUserAttributes - public static let id = "enduser.id" - /// - SeeAlso: EndUserAttributes - public static let role = "enduser.role" - /// - SeeAlso: EndUserAttributes - public static let scope = "enduser.scope" - } -} - -#if swift(>=5.2) -extension SpanAttributes { - /// Semantic end-user attributes. - public var endUser: EndUserAttributes { - get { - .init(attributes: self) - } - set { - self = newValue.attributes - } - } -} - -/// End-user-related semantic conventions as defined in the OpenTelemetry spec. -/// -/// - SeeAlso: [OpenTelemetry: General identity attributes](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/span-general.md#general-identity-attributes) -@dynamicMemberLookup -public struct EndUserAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// Username or client_id extracted from the access token or Authorization header in the inbound request from outside the system. - public var id: Key { .init(name: SpanAttributeName.EndUser.id) } - - /// Actual/assumed role the client is making the request under extracted from token or application security context. - public var role: Key { .init(name: SpanAttributeName.EndUser.role) } - - /// Scopes or granted authorities the client currently possesses extracted from token or application security context. - /// The value would come from the scope associated with an OAuth 2.0 Access Token or an attribute value in a SAML 2.0 Assertion. - public var scope: Key { .init(name: SpanAttributeName.EndUser.scope) } - } -} -#endif diff --git a/Sources/TracingOpenTelemetrySupport/SpanAttribute+ExceptionSemantics.swift b/Sources/TracingOpenTelemetrySupport/SpanAttribute+ExceptionSemantics.swift deleted file mode 100644 index fea71fa..0000000 --- a/Sources/TracingOpenTelemetrySupport/SpanAttribute+ExceptionSemantics.swift +++ /dev/null @@ -1,73 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Distributed Tracing open source project -// -// Copyright (c) 2021 Apple Inc. and the Swift Distributed Tracing project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import Tracing - -extension SpanAttributeName { - /// - SeeAlso: ExceptionAttributes - public enum Exception { - /// - SeeAlso: ExceptionAttributes - public static let type = "exception.type" - /// - SeeAlso: ExceptionAttributes - public static let message = "exception.message" - /// - SeeAlso: ExceptionAttributes - public static let stacktrace = "exception.stacktrace" - /// - SeeAlso: ExceptionAttributes - public static let escaped = "exception.escaped" - } -} - -#if swift(>=5.2) -extension SpanAttributes { - /// Semantic exception attributes. - public var exception: ExceptionAttributes { - get { - .init(attributes: self) - } - set { - self = newValue.attributes - } - } -} - -/// Semantic conventions for reporting a single exception associated with a span as defined in the OpenTelemetry spec. -/// -/// - SeeAlso: [OpenTelemetry: Exception attributes](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/exceptions.md) -@dynamicMemberLookup -public struct ExceptionAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should - /// be preferred over the static type in languages that support it. - public var type: Key { .init(name: SpanAttributeName.Exception.type) } - - /// The exception message. - public var message: Key { .init(name: SpanAttributeName.Exception.message) } - - /// A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined - /// and documented by each language SIG. - public var stacktrace: Key { .init(name: SpanAttributeName.Exception.stacktrace) } - - /// SHOULD be set to true if the exception event is recorded at a point where it is known that the exception - /// is escaping the scope of the span. - public var escaped: Key { .init(name: SpanAttributeName.Exception.escaped) } - } -} -#endif diff --git a/Sources/TracingOpenTelemetrySupport/SpanAttribute+FaaSSemantics.swift b/Sources/TracingOpenTelemetrySupport/SpanAttribute+FaaSSemantics.swift deleted file mode 100644 index 498e9c6..0000000 --- a/Sources/TracingOpenTelemetrySupport/SpanAttribute+FaaSSemantics.swift +++ /dev/null @@ -1,150 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Distributed Tracing open source project -// -// Copyright (c) 2021 Apple Inc. and the Swift Distributed Tracing project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import Tracing - -extension SpanAttributeName { - /// - SeeAlso: FaaSAttributes - public enum FaaS { - /// - SeeAlso: FaaSAttributes - public static let trigger = "faas.trigger" - /// - SeeAlso: FaaSAttributes - public static let execution = "faas.execution" - /// - SeeAlso: FaaSAttributes - public static let time = "faas.time" - /// - SeeAlso: FaaSAttributes - public static let cron = "faas.cron" - /// - SeeAlso: FaaSAttributes - public static let coldstart = "faas.coldstart" - /// - SeeAlso: FaaSAttributes - public static let invokedName = "faas.invoked_name" - /// - SeeAlso: FaaSAttributes - public static let invokedProvider = "faas.invoked_provider" - /// - SeeAlso: FaaSAttributes - public static let invokedRegion = "faas.invoked_region" - - /// - SeeAlso: FaaSAttributes.DocumentAttributes - public enum Document { - /// - SeeAlso: FaaSAttributes.DocumentAttributes - public static let collection = "faas.document.collection" - /// - SeeAlso: FaaSAttributes.DocumentAttributes - public static let operation = "faas.document.operation" - /// - SeeAlso: FaaSAttributes.DocumentAttributes - public static let time = "faas.document.time" - /// - SeeAlso: FaaSAttributes.DocumentAttributes - public static let name = "faas.document.name" - } - } -} - -#if swift(>=5.2) -extension SpanAttributes { - /// Semantic exception attributes. - public var faas: FaaSAttributes { - get { - .init(attributes: self) - } - set { - self = newValue.attributes - } - } -} - -/// Semantic conventions for reporting a single exception associated with a span as defined in the OpenTelemetry spec. -/// -/// - SeeAlso: [OpenTelemetry: FaaS attributes](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/faas.md) -@dynamicMemberLookup -public struct FaaSAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - // MARK: - General - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// Type of the trigger on which the function is executed. See [OpenTelemetry: Function Trigger Type](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/faas.md#function-trigger-type) for possible values. - public var trigger: Key { .init(name: SpanAttributeName.FaaS.trigger) } - - /// The execution ID of the current function execution. - public var execution: Key { .init(name: SpanAttributeName.FaaS.execution) } - - /// A string containing the function invocation time in the - /// [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format - /// expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - public var time: Key { .init(name: SpanAttributeName.FaaS.time) } - - /// A string containing the schedule period as [Cron Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). - public var cron: Key { .init(name: SpanAttributeName.FaaS.cron) } - - /// A boolean that is true if the serverless function is executed for the first time (aka cold-start). - public var coldstart: Key { .init(name: SpanAttributeName.FaaS.coldstart) } - - /// The name of the invoked function. - public var invokedName: Key { .init(name: SpanAttributeName.FaaS.invokedName) } - - /// The cloud provider of the invoked function. - /// See [OpenTelemetry: Outgoing Invocations](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/faas.md#outgoing-invocations) for possible values. - public var invokedProvider: Key { .init(name: SpanAttributeName.FaaS.invokedProvider) } - - /// The cloud region of the invoked function. - public var invokedRegion: Key { .init(name: SpanAttributeName.FaaS.invokedRegion) } - } - - // MARK: - Document - - /// Semantic conventions for HTTP server spans. - public var document: DocumentAttributes { - get { - .init(attributes: self.attributes) - } - set { - self.attributes = newValue.attributes - } - } - - /// Semantic Convention for FaaS triggered as a response to some data source operation such as a database or filesystem read/write. - /// - /// - SeeAlso: [OpenTelemetry: Datasource attributes](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/faas.md#datasource) - public struct DocumentAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// The name of the source on which the triggering operation was performed. - /// For example, in Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the database name. - public var collection: Key { .init(name: SpanAttributeName.FaaS.Document.collection) } - - /// Describes the type of the operation that was performed on the data. See [OpenTelemetry: Operation Type](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/faas.md#datasource) for possible values. - public var operation: Key { .init(name: SpanAttributeName.FaaS.Document.operation) } - - /// A string containing the time when the data was accessed in the - /// [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format - /// expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - public var time: Key { .init(name: SpanAttributeName.FaaS.Document.time) } - - /// The document name/table subjected to the operation. For example, in Cloud Storage or S3 is the name of the file, - /// and in Cosmos DB the table name. - public var name: Key { .init(name: SpanAttributeName.FaaS.Document.name) } - } - } -} -#endif diff --git a/Sources/TracingOpenTelemetrySupport/SpanAttribute+HTTPSemantics.swift b/Sources/TracingOpenTelemetrySupport/SpanAttribute+HTTPSemantics.swift deleted file mode 100644 index 08b589c..0000000 --- a/Sources/TracingOpenTelemetrySupport/SpanAttribute+HTTPSemantics.swift +++ /dev/null @@ -1,177 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Distributed Tracing open source project -// -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import Tracing - -extension SpanAttributeName { - /// - SeeAlso: HTTPAttributes - public enum HTTP { - /// - SeeAlso: HTTPAttributes - public static let method = "http.method" - /// - SeeAlso: HTTPAttributes - public static let url = "http.url" - /// - SeeAlso: HTTPAttributes - public static let target = "http.target" - /// - SeeAlso: HTTPAttributes - public static let host = "http.host" - /// - SeeAlso: HTTPAttributes - public static let scheme = "http.scheme" - /// - SeeAlso: HTTPAttributes - public static let statusCode = "http.status_code" - /// - SeeAlso: HTTPAttributes - public static let flavor = "http.flavor" - /// - SeeAlso: HTTPAttributes - public static let userAgent = "http.user_agent" - /// - SeeAlso: HTTPAttributes - public static let requestContentLength = "http.request_content_length" - /// - SeeAlso: HTTPAttributes - public static let requestContentLengthUncompressed = "http.request_content_length_uncompressed" - /// - SeeAlso: HTTPAttributes - public static let responseContentLength = "http.response_content_length" - /// - SeeAlso: HTTPAttributes - public static let responseContentLengthUncompressed = "http.response_content_length_uncompressed" - - /// - SeeAlso: HTTPAttributes.ServerAttributes - public enum Server { - /// - SeeAlso: HTTPAttributes.ServerAttributes - public static let name = "http.server_name" - /// - SeeAlso: HTTPAttributes.ServerAttributes - public static let route = "http.route" - /// - SeeAlso: HTTPAttributes.ServerAttributes - public static let clientIP = "http.client_ip" - } - } -} - -#if swift(>=5.2) -extension SpanAttributes { - /// Semantic conventions for HTTP spans. - public var http: HTTPAttributes { - get { - .init(attributes: self) - } - set { - self = newValue.attributes - } - } -} - -/// Semantic conventions for HTTP spans as defined in the OpenTelemetry spec. -/// -/// - SeeAlso: [OpenTelemetry: Semantic conventions for HTTP spans](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/http.md) -@dynamicMemberLookup -public struct HTTPAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - // MARK: - General - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// HTTP request method. E.g. "GET". - public var method: Key { .init(name: SpanAttributeName.HTTP.method) } - - /// Full HTTP request URL in the form scheme://host[:port]/path?query[#fragment]. - /// Usually the fragment is not transmitted over HTTP, but if it is known, it should be included nevertheless. - public var url: Key { .init(name: SpanAttributeName.HTTP.url) } - - /// The full request target as passed in a HTTP request line or equivalent, e.g. "/path/12314/?q=ddds#123". - public var target: Key { .init(name: SpanAttributeName.HTTP.target) } - - /// The value of the HTTP host header. When the header is empty or not present, this attribute should be the same. - public var host: Key { .init(name: SpanAttributeName.HTTP.host) } - - /// The URI scheme identifying the used protocol: "http" or "https" - public var scheme: Key { .init(name: SpanAttributeName.HTTP.scheme) } - - /// HTTP response status code. E.g. 200. - public var statusCode: Key { .init(name: SpanAttributeName.HTTP.statusCode) } - - /// Kind of HTTP protocol used: "1.0", "1.1", "2", "SPDY" or "QUIC". - /// - /// - Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` - /// is `QUIC`, in which case `IP.UDP` is assumed. - public var flavor: Key { .init(name: SpanAttributeName.HTTP.flavor) } - - /// Value of the HTTP User-Agent header sent by the client. - public var userAgent: Key { .init(name: SpanAttributeName.HTTP.userAgent) } - - /// The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, - /// but not always, present as the Content-Length header. For requests using transport encoding, this should be the - /// compressed size. - public var requestContentLength: Key { - .init(name: SpanAttributeName.HTTP.requestContentLength) - } - - /// The size of the uncompressed request payload body after transport decoding. Not set if transport encoding not used. - public var requestContentLengthUncompressed: Key { - .init(name: SpanAttributeName.HTTP.requestContentLengthUncompressed) - } - - /// The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and - /// is often, but not always, present as the Content-Length header. For requests using transport encoding, this - /// should be the compressed size. - public var responseContentLength: Key { - .init(name: SpanAttributeName.HTTP.responseContentLength) - } - - /// The size of the uncompressed response payload body after transport decoding. Not set if transport encoding not used. - public var responseContentLengthUncompressed: Key { - .init(name: SpanAttributeName.HTTP.responseContentLengthUncompressed) - } - } - - // MARK: - Server - - /// Semantic conventions for HTTP server spans. - public var server: ServerAttributes { - get { - .init(attributes: self.attributes) - } - set { - self.attributes = newValue.attributes - } - } - - /// Semantic conventions for HTTP Server spans as defined in the OpenTelemetry spec. - /// - /// - SeeAlso: [OpenTelemetry: Semantic conventions for HTTP Server spans](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/http.md#http-server) - public struct ServerAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// The primary server name of the matched virtual host. This should be obtained via configuration. - /// If no such configuration can be obtained, this attribute MUST NOT be set (`net.hostName` should be used instead). - public var name: Key { .init(name: SpanAttributeName.HTTP.Server.name) } - - /// The matched route (path template). E.g. "/users/:userID?". - public var route: Key { .init(name: SpanAttributeName.HTTP.Server.route) } - - /// The IP address of the original client behind all proxies, if known (e.g. from [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)). - /// - /// - Note: This is not necessarily the same as `net.peer.ip`, which would identify the network-level peer, which may be a proxy. - public var clientIP: Key { .init(name: SpanAttributeName.HTTP.Server.clientIP) } - } - } -} -#endif diff --git a/Sources/TracingOpenTelemetrySupport/SpanAttribute+MessagingSemantics.swift b/Sources/TracingOpenTelemetrySupport/SpanAttribute+MessagingSemantics.swift deleted file mode 100644 index 299e89a..0000000 --- a/Sources/TracingOpenTelemetrySupport/SpanAttribute+MessagingSemantics.swift +++ /dev/null @@ -1,179 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Distributed Tracing open source project -// -// Copyright (c) 2021 Apple Inc. and the Swift Distributed Tracing project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import Tracing - -extension SpanAttributeName { - /// - SeeAlso: MessagingAttributes - public enum Messaging { - /// - SeeAlso: MessagingAttributes - public static let system = "messaging.system" - /// - SeeAlso: MessagingAttributes - public static let destination = "messaging.destination" - /// - SeeAlso: MessagingAttributes - public static let destinationKind = "messaging.destination_kind" - /// - SeeAlso: MessagingAttributes - public static let tempDestination = "messaging.temp_destination" - /// - SeeAlso: MessagingAttributes - public static let `protocol` = "messaging.protocol" - /// - SeeAlso: MessagingAttributes - public static let protocolVersion = "messaging.protocol_version" - /// - SeeAlso: MessagingAttributes - public static let url = "messaging.url" - /// - SeeAlso: MessagingAttributes - public static let messageID = "messaging.message_id" - /// - SeeAlso: MessagingAttributes - public static let conversationID = "messaging.conversation_id" - /// - SeeAlso: MessagingAttributes - public static let messagePayloadSizeBytes = "messaging.message_payload_size_bytes" - /// - SeeAlso: MessagingAttributes - public static let messagePayloadCompressedSizeBytes = "messaging.message_payload_compressed_size_bytes" - /// - SeeAlso: MessagingAttributes - public static let operation = "messaging.operation" - - /// - SeeAlso: MessagingAttributes.KafkaAttributes - public enum Kafka { - /// - SeeAlso: MessagingAttributes.KafkaAttributes - public static let messageKey = "messaging.kafka.message_key" - /// - SeeAlso: MessagingAttributes.KafkaAttributes - public static let consumerGroup = "messaging.kafka.consumer_group" - /// - SeeAlso: MessagingAttributes.KafkaAttributes - public static let clientID = "messaging.kafka.client_id" - /// - SeeAlso: MessagingAttributes.KafkaAttributes - public static let partition = "messaging.kafka.partition" - /// - SeeAlso: MessagingAttributes.KafkaAttributes - public static let tombstone = "messaging.kafka.tombstone" - } - } -} - -#if swift(>=5.2) -extension SpanAttributes { - /// Semantic conventions for messaging system spans. - public var messaging: MessagingAttributes { - get { - .init(attributes: self) - } - set { - self = newValue.attributes - } - } -} - -/// Semantic conventions for messaging system spans as defined in the OpenTelemetry spec. -/// -/// - SeeAlso: [OpenTelemetry: Messaging Attributes](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/messaging.md#messaging-attributes) -@dynamicMemberLookup -public struct MessagingAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - // MARK: - General - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// A string identifying the messaging system. - public var system: Key { .init(name: SpanAttributeName.Messaging.system) } - - /// The message destination name. This might be equal to the span name but is required nevertheless. - public var destination: Key { .init(name: SpanAttributeName.Messaging.destination) } - - /// The kind of message destination. - public var destinationKind: Key { .init(name: SpanAttributeName.Messaging.destinationKind) } - - /// A boolean that is true if the message destination is temporary. - /// - /// - SeeAlso: [OpenTelemetry: Temporary Destinations](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/messaging.md#temporary-destinations) - public var tempDestination: Key { .init(name: SpanAttributeName.Messaging.tempDestination) } - - /// The name of the transport protocol. - public var `protocol`: Key { .init(name: SpanAttributeName.Messaging.protocol) } - - /// The version of the transport protocol. - public var protocolVersion: Key { .init(name: SpanAttributeName.Messaging.protocolVersion) } - - /// The connection string. - public var url: Key { .init(name: SpanAttributeName.Messaging.url) } - - /// A value used by the messaging system as an identifier for the message, represented as a string. - public var messageID: Key { .init(name: SpanAttributeName.Messaging.messageID) } - - /// The conversation ID identifying the conversation to which the message belongs, represented as a string. Sometimes called "Correlation ID". - /// - /// - SeeAlso: [OpenTelemetry: Conversations](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/messaging.md#conversations) - public var conversationID: Key { .init(name: SpanAttributeName.Messaging.conversationID) } - - /// The (uncompressed) size of the message payload in bytes. Also use this attribute if it is unknown whether the compressed or uncompressed - /// payload size is reported. - public var messagePayloadSizeBytes: Key { - .init(name: SpanAttributeName.Messaging.messagePayloadSizeBytes) - } - - /// The compressed size of the message payload in bytes. - public var messagePayloadCompressedSizeBytes: Key { - .init(name: SpanAttributeName.Messaging.messagePayloadCompressedSizeBytes) - } - - /// A string identifying the kind of message consumption as defined in the [Operation names](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/messaging.md#operation-names) section. - /// If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - public var operation: Key { .init(name: SpanAttributeName.Messaging.operation) } - } - - // MARK: - Kafka - - /// Semantic conventions for Kafka spans. - public var kafka: KafkaAttributes { - get { - .init(attributes: self.attributes) - } - set { - self.attributes = newValue.attributes - } - } - - /// Semantic conventions for Kafka spans as defined in the OpenTelemetry spec. - /// - /// - SeeAlso: [OpenTelemetry: Kafka Attributes](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/messaging.md#apache-kafka) - public struct KafkaAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// Message keys in Kafka are used for grouping alike messages to ensure they're processed on the same partition. - /// They differ from `messaging.message_id` in that they're not unique. If the key is `null`, the attribute MUST NOT be set. - public var messageKey: Key { .init(name: SpanAttributeName.Messaging.Kafka.messageKey) } - - /// Name of the Kafka Consumer Group that is handling the message. Only applies to consumers, not producers. - public var consumerGroup: Key { .init(name: SpanAttributeName.Messaging.Kafka.consumerGroup) } - - /// Client Id for the Consumer or Producer that is handling the message. - public var clientID: Key { .init(name: SpanAttributeName.Messaging.Kafka.clientID) } - - /// Partition the message is sent to. - public var partition: Key { .init(name: SpanAttributeName.Messaging.Kafka.partition) } - - /// A boolean that is true if the message is a tombstone. - public var tombstone: Key { .init(name: SpanAttributeName.Messaging.Kafka.tombstone) } - } - } -} -#endif diff --git a/Sources/TracingOpenTelemetrySupport/SpanAttribute+NetSemantics.swift b/Sources/TracingOpenTelemetrySupport/SpanAttribute+NetSemantics.swift deleted file mode 100644 index 902fc84..0000000 --- a/Sources/TracingOpenTelemetrySupport/SpanAttribute+NetSemantics.swift +++ /dev/null @@ -1,145 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Distributed Tracing open source project -// -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import Tracing - -extension SpanAttributeName { - /// - SeeAlso: NetAttributes - public enum Net { - /// - SeeAlso: NetAttributes - public static let transport = "net.transport" - - /// - SeeAlso: NetAttributes.PeerAttributes - public enum Peer { - /// - SeeAlso: NetAttributes.PeerAttributes - public static let ip = "net.peer.ip" - /// - SeeAlso: NetAttributes.PeerAttributes - public static let port = "net.peer.port" - /// - SeeAlso: NetAttributes.PeerAttributes - public static let name = "net.peer.name" - } - - /// - SeeAlso: NetAttributes.HostAttributes - public enum Host { - /// - SeeAlso: NetAttributes.HostAttributes - public static let ip = "net.host.ip" - /// - SeeAlso: NetAttributes.HostAttributes - public static let port = "net.host.port" - /// - SeeAlso: NetAttributes.HostAttributes - public static let name = "net.host.name" - } - } -} - -#if swift(>=5.2) -extension SpanAttributes { - /// Semantic network attributes. - public var net: NetAttributes { - get { - .init(attributes: self) - } - set { - self = newValue.attributes - } - } -} - -/// Network related semantic conventions as defined in the OpenTelemetry spec. -/// -/// - SeeAlso: [OpenTelemetry: General semantic attributes](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/span-general.md#general-network-connection-attributes) -@dynamicMemberLookup -public struct NetAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - // MARK: - General - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// Transport protocol used. - public var transport: Key { .init(name: SpanAttributeName.Net.transport) } - } - - // MARK: - Peer - - /// Semantic network peer attributes. - public var peer: PeerAttributes { - get { - .init(attributes: self.attributes) - } - set { - self.attributes = newValue.attributes - } - } - - /// Semantic network peer attributes. - public struct PeerAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// Remote address of the peer (dotted decimal for IPv4 or RFC5952 for IPv6). - public var ip: Key { .init(name: SpanAttributeName.Net.Peer.ip) } - - /// Remote port number as an integer. E.g., 80. - public var port: Key { .init(name: SpanAttributeName.Net.Peer.port) } - - /// Remote hostname or similar. - public var name: Key { .init(name: SpanAttributeName.Net.Peer.name) } - } - } - - // MARK: - Host - - /// Semantic network host attributes. - public var host: HostAttributes { - get { - .init(attributes: self.attributes) - } - set { - self.attributes = newValue.attributes - } - } - - /// Semantic network host attributes. - public struct HostAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// Like `peer.ip` but for the host IP. Useful in case of a multi-IP host. - public var ip: Key { .init(name: SpanAttributeName.Net.Host.ip) } - - /// Like `peer.port` but for the host port. - public var port: Key { .init(name: SpanAttributeName.Net.Host.port) } - - /// Local hostname or similar. - public var name: Key { .init(name: SpanAttributeName.Net.Host.name) } - } - } -} -#endif diff --git a/Sources/TracingOpenTelemetrySupport/SpanAttribute+PeerSemantics.swift b/Sources/TracingOpenTelemetrySupport/SpanAttribute+PeerSemantics.swift deleted file mode 100644 index 9f85808..0000000 --- a/Sources/TracingOpenTelemetrySupport/SpanAttribute+PeerSemantics.swift +++ /dev/null @@ -1,55 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Distributed Tracing open source project -// -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import Tracing - -extension SpanAttributeName { - /// - SeeAlso: PeerAttributes - public enum Peer { - /// - SeeAlso: PeerAttributes - public static let service = "peer.service" - } -} - -#if swift(>=5.2) -extension SpanAttributes { - /// General semantic attributes. - public var peer: PeerAttributes { - get { - .init(attributes: self) - } - set { - self = newValue.attributes - } - } -} - -/// Peer-related semantic conventions as defined in the OpenTelemetry spec. -/// -/// - SeeAlso: [OpenTelemetry: General remote service attributes](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/span-general.md#general-remote-service-attributes) -@dynamicMemberLookup -public struct PeerAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// The service.name of the remote service. SHOULD be equal to the actual service.name resource attribute of the remote service if any. - public var service: Key { .init(name: SpanAttributeName.Peer.service) } - } -} -#endif diff --git a/Sources/TracingOpenTelemetrySupport/SpanAttribute+RPCSemantics.swift b/Sources/TracingOpenTelemetrySupport/SpanAttribute+RPCSemantics.swift deleted file mode 100644 index 3cbc22a..0000000 --- a/Sources/TracingOpenTelemetrySupport/SpanAttribute+RPCSemantics.swift +++ /dev/null @@ -1,99 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Distributed Tracing open source project -// -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import Tracing - -extension SpanAttributeName { - /// - SeeAlso: RPCAttributes - public enum RPC { - /// - SeeAlso: RPCAttributes - public static let system = "rpc.system" - /// - SeeAlso: RPCAttributes - public static let service = "rpc.service" - /// - SeeAlso: RPCAttributes - public static let method = "rpc.method" - - /// - SeeAlso: RPCAttributes.GRPCAttributes - public enum GRPC { - /// - SeeAlso: RPCAttributes.GRPCAttributes - public static let statusCode = "rpc.grpc.status_code" - } - } -} - -#if swift(>=5.2) -extension SpanAttributes { - /// Semantic conventions for RPC spans. - public var rpc: RPCAttributes { - get { - .init(attributes: self) - } - set { - self = newValue.attributes - } - } -} - -/// Semantic conventions for RPC spans as defined in the OpenTelemetry spec. -/// -/// - SeeAlso: [OpenTelemetry: Semantic conventions for RPC spans](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/rpc.md) -@dynamicMemberLookup -public struct RPCAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// A string identifying the remoting system, e.g., "grpc", "java_rmi" or "wcf". - public var system: Key { .init(name: SpanAttributeName.RPC.system) } - - /// The full name of the service being called, including its package name, if applicable. - public var service: Key { .init(name: SpanAttributeName.RPC.service) } - - /// The name of the method being called, must be equal to the $method part in the span name. - public var method: Key { .init(name: SpanAttributeName.RPC.method) } - } - - /// Semantic conventions for gRPC spans. - public var gRPC: GRPCAttributes { - get { - .init(attributes: self.attributes) - } - set { - self.attributes = newValue.attributes - } - } - - /// Semantic concentions for gRPC spans as defined in the OpenTelemetry spec. - /// - /// - SeeAlso: [OpenTelemetry: Semantic conventions for gRPC spans](https://github.com/open-telemetry/opentelemetry-specification/blob/v0.7.0/specification/trace/semantic_conventions/rpc.md#grpc) - public struct GRPCAttributes: SpanAttributeNamespace { - public var attributes: SpanAttributes - - public init(attributes: SpanAttributes) { - self.attributes = attributes - } - - public struct NestedSpanAttributes: NestedSpanAttributesProtocol { - public init() {} - - /// The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - public var statusCode: Key { .init(name: SpanAttributeName.RPC.GRPC.statusCode) } - } - } -} -#endif diff --git a/Sources/TracingOpenTelemetrySupport/SpanAttributeName.swift b/Sources/TracingOpenTelemetrySupport/SpanAttributeName.swift deleted file mode 100644 index 6546096..0000000 --- a/Sources/TracingOpenTelemetrySupport/SpanAttributeName.swift +++ /dev/null @@ -1,17 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Distributed Tracing open source project -// -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import Tracing - -/// Namespace for attribute key constants used with `SpanAttributes`. -public enum SpanAttributeName {} diff --git a/Sources/_TracingBenchmarkTools/ArgParser.swift b/Sources/_TracingBenchmarkTools/ArgParser.swift index a1967a0..16ddb61 100644 --- a/Sources/_TracingBenchmarkTools/ArgParser.swift +++ b/Sources/_TracingBenchmarkTools/ArgParser.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -74,7 +75,7 @@ func checked( class ArgumentParser { private var result: U private var validOptions: [String] { - return self.arguments.compactMap { $0.name } + self.arguments.compactMap(\.name) } private var arguments: [Argument] = [] @@ -219,7 +220,7 @@ class ArgumentParser { ) { self.arguments.append( Argument(name: name, help: help) - { try self.parseArgument(name, property, defaultValue, parser) } + { try self.parseArgument(name, property, defaultValue, parser) } ) } diff --git a/Sources/_TracingBenchmarkTools/BenchmarkCategory.swift b/Sources/_TracingBenchmarkTools/BenchmarkCategory.swift index 54be1b5..126cc16 100644 --- a/Sources/_TracingBenchmarkTools/BenchmarkCategory.swift +++ b/Sources/_TracingBenchmarkTools/BenchmarkCategory.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/Sources/_TracingBenchmarkTools/BenchmarkTools.swift b/Sources/_TracingBenchmarkTools/BenchmarkTools.swift index 71826c9..283fe7b 100644 --- a/Sources/_TracingBenchmarkTools/BenchmarkTools.swift +++ b/Sources/_TracingBenchmarkTools/BenchmarkTools.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -25,13 +26,13 @@ import Darwin extension BenchmarkCategory: CustomStringConvertible { public var description: String { - return self.rawValue + self.rawValue } } extension BenchmarkCategory: Comparable { public static func < (lhs: BenchmarkCategory, rhs: BenchmarkCategory) -> Bool { - return lhs.rawValue < rhs.rawValue + lhs.rawValue < rhs.rawValue } } @@ -54,7 +55,7 @@ public struct BenchmarkPlatformSet: OptionSet { } public static var allPlatforms: BenchmarkPlatformSet { - return [.darwin, .linux] + [.darwin, .linux] } } @@ -124,17 +125,17 @@ public struct BenchmarkInfo { /// Returns true if this benchmark should be run on the current platform. var shouldRun: Bool { - return !self.unsupportedPlatforms.contains(.currentPlatform) + !self.unsupportedPlatforms.contains(.currentPlatform) } } extension BenchmarkInfo: Comparable { public static func < (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { - return lhs.name < rhs.name + lhs.name < rhs.name } public static func == (lhs: BenchmarkInfo, rhs: BenchmarkInfo) -> Bool { - return lhs.name == rhs.name + lhs.name == rhs.name } } @@ -175,7 +176,7 @@ public func SRand() { } public func Random() -> Int64 { - return lfsrRandomGenerator.randInt() + lfsrRandomGenerator.randInt() } @inlinable // FIXME(inline-always) @@ -192,16 +193,16 @@ public func CheckResults( } } -public func False() -> Bool { return false } +public func False() -> Bool { false } /// This is a dummy protocol to test the speed of our protocol dispatch. public protocol SomeProtocol { func getValue() -> Int } struct MyStruct: SomeProtocol { init() {} - func getValue() -> Int { return 1 } + func getValue() -> Int { 1 } } -public func someProtocolFactory() -> SomeProtocol { return MyStruct() } +public func someProtocolFactory() -> SomeProtocol { MyStruct() } // Just consume the argument. // It's important that this function is in another module than the tests @@ -212,19 +213,19 @@ public func blackHole(_: T) {} // Return the passed argument without letting the optimizer know that. @inline(never) public func identity(_ x: T) -> T { - return x + x } // Return the passed argument without letting the optimizer know that. // It's important that this function is in another module than the tests // which are using it. @inline(never) -public func getInt(_ x: Int) -> Int { return x } +public func getInt(_ x: Int) -> Int { x } // The same for String. @inline(never) -public func getString(_ s: String) -> String { return s } +public func getString(_ s: String) -> String { s } // The same for Substring. @inline(never) -public func getSubstring(_ s: Substring) -> Substring { return s } +public func getSubstring(_ s: Substring) -> Substring { s } diff --git a/Sources/_TracingBenchmarkTools/DriverUtils.swift b/Sources/_TracingBenchmarkTools/DriverUtils.swift index e8dc3a8..5968c0c 100644 --- a/Sources/_TracingBenchmarkTools/DriverUtils.swift +++ b/Sources/_TracingBenchmarkTools/DriverUtils.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -54,12 +55,12 @@ public struct BenchResults { return self.samples[index] } - var sampleCount: T { return self.samples.count } - var min: T { return self.samples.first! } - var max: T { return self.samples.last! } - var mean: T { return Int(self.stats.mean.rounded()) } - var sd: T { return Int(self.stats.standardDeviation.rounded()) } - var median: T { return self[0.5] } + var sampleCount: T { self.samples.count } + var min: T { self.samples.first! } + var max: T { self.samples.last! } + var mean: T { Int(self.stats.mean.rounded()) } + var sd: T { Int(self.stats.standardDeviation.rounded()) } + var median: T { self[0.5] } } public var registeredBenchmarks: [BenchmarkInfo] = [] @@ -135,14 +136,14 @@ struct TestConfig { // We support specifying multiple tags by splitting on comma, i.e.: // --tags=Array,Dictionary // --skip-tags=Array,Set,unstable,skip - return Set( + Set( try tags.split(separator: ",").map(String.init).map { try checked({ BenchmarkCategory(rawValue: $0) }, $0) } ) } func finiteDouble(value: String) -> Double? { - return Double(value).flatMap { $0.isFinite ? $0 : nil } + Double(value).flatMap { $0.isFinite ? $0 : nil } } // Configure the command line argument parser @@ -250,7 +251,7 @@ struct TestConfig { // We always prepare the configuration string and call the print to have // the same memory usage baseline between verbose and normal mode. - let testList = self.tests.map { $0.1.name }.joined(separator: ", ") + let testList = self.tests.map(\.1.name).joined(separator: ", ") let configuration = """ --- CONFIG --- NumSamples: \(numSamples ?? 0) @@ -288,17 +289,17 @@ struct TestConfig { let indices = Dictionary( uniqueKeysWithValues: zip( - allTests.map { $0.name }, + allTests.map(\.name), (1...).lazy.map { String($0) } ) ) func byTags(b: BenchmarkInfo) -> Bool { - return b.tags.isSuperset(of: tags) && + b.tags.isSuperset(of: tags) && b.tags.isDisjoint(with: skipTags) } func byNamesOrIndices(b: BenchmarkInfo) -> Bool { - return specifiedTests.contains(b.name) || + specifiedTests.contains(b.name) || specifiedTests.contains(indices[b.name]!) } // !! "`allTests` have been assigned an index" return allTests @@ -311,8 +312,8 @@ struct Stats { var n: Int = 0 var S: Double = 0.0 var mean: Double = 0.0 - var variance: Double { return self.n < 2 ? 0.0 : self.S / Double(self.n - 1) } - var standardDeviation: Double { return self.variance.squareRoot() } + var variance: Double { self.n < 2 ? 0.0 : self.S / Double(self.n - 1) } + var standardDeviation: Double { self.variance.squareRoot() } static func collect(_ s: inout Stats, _ x: Int) { Stats.runningMeanVariance(&s, Double(x)) @@ -353,7 +354,7 @@ public final class Timer { } public func getTimeAsInt() -> UInt64 { - return UInt64(getTime().tv_nsec) + UInt64(getTime().tv_nsec) } public func diffTimeInNanoSeconds(from start: TimeT, to end: TimeT) -> UInt64 { @@ -378,11 +379,11 @@ public final class Timer { } public func getTime() -> TimeT { - return mach_absolute_time() + mach_absolute_time() } public func getTimeAsInt() -> UInt64 { - return UInt64(getTime()) + UInt64(getTime()) } public func diffTimeInNanoSeconds(from start: TimeT, to end: TimeT) -> UInt64 { @@ -393,10 +394,10 @@ public final class Timer { } extension UInt64 { - public var nanoseconds: Int { return Int(self) } - public var microseconds: Int { return Int(self / 1000) } - public var milliseconds: Int { return Int(self / 1000 / 1000) } - public var seconds: Int { return Int(self / 1000 / 1000 / 1000) } + public var nanoseconds: Int { Int(self) } + public var microseconds: Int { Int(self / 1000) } + public var milliseconds: Int { Int(self / 1000 / 1000) } + public var seconds: Int { Int(self / 1000 / 1000 / 1000) } } enum TimeUnit: String { @@ -420,7 +421,7 @@ enum TimeUnit: String { extension TimeUnit: CustomStringConvertible { public var description: String { - return self.rawValue + self.rawValue } } @@ -447,7 +448,7 @@ final class TestRunner { private static func getExecutedInstructions() -> UInt64 { // FIXME: there is a Linux PMC API you can use to get this, but it's // not quite so straightforward. - return 0 + 0 } #else @@ -460,7 +461,7 @@ final class TestRunner { // } // return u.ri_instructions // } else { - return 0 + 0 // } } #endif @@ -533,7 +534,7 @@ final class TestRunner { /// Time in nanoseconds spent running the last function var lastSampleTime: UInt64 { - return timer.diffTimeInNanoSeconds(from: start, to: end) + timer.diffTimeInNanoSeconds(from: start, to: end) } /// Measure the `fn` and return the average sample time per iteration (in c.timeUnit). diff --git a/Sources/_TracingBenchmarks/SpanAttributesDSLBenchmark.swift b/Sources/_TracingBenchmarks/SpanAttributesDSLBenchmark.swift index 4847852..0a930de 100644 --- a/Sources/_TracingBenchmarks/SpanAttributesDSLBenchmark.swift +++ b/Sources/_TracingBenchmarks/SpanAttributesDSLBenchmark.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,11 +12,8 @@ // //===----------------------------------------------------------------------===// -#if swift(>=5.2) - import _TracingBenchmarkTools import Tracing -import TracingOpenTelemetrySupport public let SpanAttributesDSLBenchmarks: [BenchmarkInfo] = [ BenchmarkInfo( @@ -71,16 +69,13 @@ public let SpanAttributesDSLBenchmarks: [BenchmarkInfo] = [ ), ] -private var context: LoggingContext! private var span: Span! private func setUp() { - context = DefaultLoggingContext.topLevel(logger: .init(label: "")) - span = InstrumentationSystem.tracer.startSpan("something", context: context) + span = InstrumentationSystem.tracer.startSpan("something", baggage: .topLevel) } private func tearDown() { - context = nil span = nil } @@ -91,14 +86,14 @@ func bench_empty(times: Int) throws {} func bench_makeSpan(times: Int) throws { for _ in 0 ..< times { - let span = InstrumentationSystem.tracer.startSpan("something", context: context) + let span = InstrumentationSystem.tracer.startSpan("something", baggage: .topLevel) _ = span } } func bench_startSpan_end(times: Int) throws { for _ in 0 ..< times { - let span = InstrumentationSystem.tracer.startSpan("something", context: context) + let span = InstrumentationSystem.tracer.startSpan("something", baggage: .topLevel) span.end() } } @@ -133,4 +128,29 @@ func bench_set_Int_dsl(times: Int) throws { } } -#endif +extension SpanAttributes { + var http: HTTPAttributes { + get { + .init(attributes: self) + } + set { + self = newValue.attributes + } + } +} + +@dynamicMemberLookup +struct HTTPAttributes: SpanAttributeNamespace { + var attributes: SpanAttributes + + init(attributes: SpanAttributes) { + self.attributes = attributes + } + + struct NestedSpanAttributes: NestedSpanAttributesProtocol { + init() {} + + var method: Key { "http.method" } + var statusCode: Key { "http.status_code" } + } +} diff --git a/Sources/_TracingBenchmarks/main.swift b/Sources/_TracingBenchmarks/main.swift index 6b0e1a1..4ae4b3a 100644 --- a/Sources/_TracingBenchmarks/main.swift +++ b/Sources/_TracingBenchmarks/main.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -36,8 +37,6 @@ private func registerBenchmark(_ name: String, _ function: @escaping (Int) -> Vo registerBenchmark(BenchmarkInfo(name: name, runFunction: function, tags: tags)) } -#if swift(>=5.2) registerBenchmark(SpanAttributesDSLBenchmarks) -#endif main() diff --git a/Tests/InstrumentationTests/InstrumentTests+XCTest.swift b/Tests/InstrumentationTests/InstrumentTests+XCTest.swift index 7f7acdb..20c0028 100644 --- a/Tests/InstrumentationTests/InstrumentTests+XCTest.swift +++ b/Tests/InstrumentationTests/InstrumentTests+XCTest.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/Tests/InstrumentationTests/InstrumentTests.swift b/Tests/InstrumentationTests/InstrumentTests.swift index 1b161e6..aaea30a 100644 --- a/Tests/InstrumentationTests/InstrumentTests.swift +++ b/Tests/InstrumentationTests/InstrumentTests.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,8 +12,8 @@ // //===----------------------------------------------------------------------===// -import Baggage import Instrumentation +import InstrumentationBaggage import XCTest final class InstrumentTests: XCTestCase { @@ -47,12 +48,12 @@ private struct DictionaryInjector: Injector { private struct DictionaryExtractor: Extractor { func extract(key: String, from dictionary: [String: String]) -> String? { - return dictionary[key] + dictionary[key] } } private final class FirstFakeTracer: Instrument { - enum TraceIDKey: Baggage.Key { + enum TraceIDKey: BaggageKey { typealias Value = String static let name: String? = "FirstFakeTraceID" @@ -62,20 +63,22 @@ private final class FirstFakeTracer: Instrument { static let defaultTraceID = UUID().uuidString func inject(_ baggage: Baggage, into carrier: inout Carrier, using injector: Inject) - where Inject: Injector, Carrier == Inject.Carrier { + where Inject: Injector, Carrier == Inject.Carrier + { guard let traceID = baggage[TraceIDKey.self] else { return } injector.inject(traceID, forKey: FirstFakeTracer.headerName, into: &carrier) } func extract(_ carrier: Carrier, into baggage: inout Baggage, using extractor: Extract) - where Extract: Extractor, Carrier == Extract.Carrier { + where Extract: Extractor, Carrier == Extract.Carrier + { let traceID = extractor.extract(key: FirstFakeTracer.headerName, from: carrier) ?? FirstFakeTracer.defaultTraceID baggage[TraceIDKey.self] = traceID } } private final class SecondFakeTracer: Instrument { - enum TraceIDKey: Baggage.Key { + enum TraceIDKey: BaggageKey { typealias Value = String static let name: String? = "SecondFakeTraceID" @@ -89,7 +92,8 @@ private final class SecondFakeTracer: Instrument { ) where Inject: Injector, - Carrier == Inject.Carrier { + Carrier == Inject.Carrier + { guard let traceID = baggage[TraceIDKey.self] else { return } injector.inject(traceID, forKey: SecondFakeTracer.headerName, into: &carrier) } @@ -99,7 +103,8 @@ private final class SecondFakeTracer: Instrument { ) where Extract: Extractor, - Carrier == Extract.Carrier { + Carrier == Extract.Carrier + { let traceID = extractor.extract(key: SecondFakeTracer.headerName, from: carrier) ?? SecondFakeTracer.defaultTraceID baggage[TraceIDKey.self] = traceID } diff --git a/Tests/InstrumentationTests/InstrumentationSystemTests+XCTest.swift b/Tests/InstrumentationTests/InstrumentationSystemTests+XCTest.swift index 56aa167..74d5a19 100644 --- a/Tests/InstrumentationTests/InstrumentationSystemTests+XCTest.swift +++ b/Tests/InstrumentationTests/InstrumentationSystemTests+XCTest.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/Tests/InstrumentationTests/InstrumentationSystemTests.swift b/Tests/InstrumentationTests/InstrumentationSystemTests.swift index afe1dbd..87a7be5 100644 --- a/Tests/InstrumentationTests/InstrumentationSystemTests.swift +++ b/Tests/InstrumentationTests/InstrumentationSystemTests.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,13 +12,13 @@ // //===----------------------------------------------------------------------===// -import Baggage @testable import Instrumentation +import InstrumentationBaggage import XCTest extension InstrumentationSystem { public static func _instrument(of instrumentType: I.Type) -> I? where I: Instrument { - return self._findInstrument(where: { $0 is I }) as? I + self._findInstrument(where: { $0 is I }) as? I } } diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index 8e9ec21..88768ba 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -22,7 +23,6 @@ import XCTest #if os(Linux) || os(FreeBSD) @testable import InstrumentationTests - @testable import TracingOpenTelemetrySupportTests @testable import TracingTests // This protocol is necessary to we can call the 'run' method (on an existential of this protocol) @@ -36,7 +36,6 @@ class LinuxMainRunnerImpl: LinuxMainRunner { XCTMain([ testCase(InstrumentTests.allTests), testCase(InstrumentationSystemTests.allTests), - testCase(SpanAttributeSemanticsTests.allTests), testCase(SpanTests.allTests), testCase(TracedLockTests.allTests), testCase(TracerTests.allTests), diff --git a/Tests/TracingOpenTelemetrySupportTests/SpanAttributeSemanticsTests+XCTest.swift b/Tests/TracingOpenTelemetrySupportTests/SpanAttributeSemanticsTests+XCTest.swift deleted file mode 100644 index 83a3726..0000000 --- a/Tests/TracingOpenTelemetrySupportTests/SpanAttributeSemanticsTests+XCTest.swift +++ /dev/null @@ -1,32 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Distributed Tracing open source project -// -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// -// -// SpanAttributeSemanticsTests+XCTest.swift -// -import XCTest -/// -/// NOTE: This file was generated by generate_linux_tests.rb -/// -/// Do NOT edit this file directly as it will be regenerated automatically when needed. -/// - -extension SpanAttributeSemanticsTests { - - @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") - static var allTests : [(String, (SpanAttributeSemanticsTests) -> () throws -> Void)] { - return [ - ("testDynamicMemberLookupForEachNamespace", testDynamicMemberLookupForEachNamespace), - ] - } -} - diff --git a/Tests/TracingOpenTelemetrySupportTests/SpanAttributeSemanticsTests.swift b/Tests/TracingOpenTelemetrySupportTests/SpanAttributeSemanticsTests.swift deleted file mode 100644 index 80223eb..0000000 --- a/Tests/TracingOpenTelemetrySupportTests/SpanAttributeSemanticsTests.swift +++ /dev/null @@ -1,89 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Distributed Tracing open source project -// -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -import Baggage -import Instrumentation -import Tracing -import TracingOpenTelemetrySupport -import XCTest - -final class SpanAttributeSemanticsTests: XCTestCase { - func testDynamicMemberLookupForEachNamespace() { - #if swift(>=5.2) - var attributes: SpanAttributes = [:] - - attributes.db.system = "postgresql" - XCTAssertEqual(attributes.db.system, "postgresql") - - attributes.db.mssql.instanceName = "test" - XCTAssertEqual(attributes.db.mssql.instanceName, "test") - - attributes.db.cassandra.keyspace = "test" - XCTAssertEqual(attributes.db.cassandra.keyspace, "test") - - attributes.db.hbase.namespace = "test" - XCTAssertEqual(attributes.db.hbase.namespace, "test") - - attributes.db.redis.databaseIndex = 1 - XCTAssertEqual(attributes.db.redis.databaseIndex, 1) - - attributes.db.mongodb.collection = "test" - XCTAssertEqual(attributes.db.mongodb.collection, "test") - - attributes.db.sql.table = "test" - XCTAssertEqual(attributes.db.sql.table, "test") - - attributes.endUser.id = "steve" - XCTAssertEqual(attributes.endUser.id, "steve") - - attributes.exception.type = "SomeError" - XCTAssertEqual(attributes.exception.type, "SomeError") - - attributes.faas.trigger = "datasource" - XCTAssertEqual(attributes.faas.trigger, "datasource") - - attributes.faas.document.collection = "collection" - XCTAssertEqual(attributes.faas.document.collection, "collection") - - attributes.http.method = "GET" - XCTAssertEqual(attributes.http.method, "GET") - - attributes.http.server.route = "/users/:userID?" - XCTAssertEqual(attributes.http.server.route, "/users/:userID?") - - attributes.messaging.system = "kafka" - XCTAssertEqual(attributes.messaging.system, "kafka") - - attributes.messaging.kafka.partition = 2 - XCTAssertEqual(attributes.messaging.kafka.partition, 2) - - attributes.net.transport = "IP.TCP" - XCTAssertEqual(attributes.net.transport, "IP.TCP") - - attributes.net.peer.ip = "127.0.0.1" - XCTAssertEqual(attributes.net.peer.ip, "127.0.0.1") - - attributes.net.host.ip = "127.0.0.1" - XCTAssertEqual(attributes.net.host.ip, "127.0.0.1") - - attributes.peer.service = "hotrod" - XCTAssertEqual(attributes.peer.service, "hotrod") - - attributes.rpc.system = "grpc" - XCTAssertEqual(attributes.rpc.system, "grpc") - - attributes.rpc.gRPC.statusCode = 0 - XCTAssertEqual(attributes.rpc.gRPC.statusCode, 0) - #endif - } -} diff --git a/Tests/TracingTests/SpanTests+XCTest.swift b/Tests/TracingTests/SpanTests+XCTest.swift index 9370252..fbd5ec5 100644 --- a/Tests/TracingTests/SpanTests+XCTest.swift +++ b/Tests/TracingTests/SpanTests+XCTest.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/Tests/TracingTests/SpanTests.swift b/Tests/TracingTests/SpanTests.swift index b95bac4..3e79d8e 100644 --- a/Tests/TracingTests/SpanTests.swift +++ b/Tests/TracingTests/SpanTests.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,8 +12,8 @@ // //===----------------------------------------------------------------------===// -import Baggage import Instrumentation +import InstrumentationBaggage import Tracing import XCTest @@ -203,7 +204,7 @@ final class SpanTests: XCTestCase { extension SpanAttribute { var name: Key { - return "name" + "name" } } @@ -254,6 +255,6 @@ public struct CustomAttributeValue: Equatable, CustomStringConvertible, SpanAttr } #endif -private struct TestBaggageContextKey: Baggage.Key { +private struct TestBaggageContextKey: BaggageKey { typealias Value = String } diff --git a/Tests/TracingTests/TestTracer.swift b/Tests/TracingTests/TestTracer.swift index 3474929..ba7a8bb 100644 --- a/Tests/TracingTests/TestTracer.swift +++ b/Tests/TracingTests/TestTracer.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,10 +12,10 @@ // //===----------------------------------------------------------------------===// -import Baggage import Dispatch import Foundation import Instrumentation +import InstrumentationBaggage import Tracing final class TestTracer: Tracer { @@ -43,7 +44,8 @@ final class TestTracer: Tracer { func extract(_ carrier: Carrier, into baggage: inout Baggage, using extractor: Extract) where Extract: Extractor, - Carrier == Extract.Carrier { + Carrier == Extract.Carrier + { let traceID = extractor.extract(key: "trace-id", from: carrier) ?? UUID().uuidString baggage.traceID = traceID } @@ -51,14 +53,15 @@ final class TestTracer: Tracer { func inject(_ baggage: Baggage, into carrier: inout Carrier, using injector: Inject) where Inject: Injector, - Carrier == Inject.Carrier { + Carrier == Inject.Carrier + { guard let traceID = baggage.traceID else { return } injector.inject(traceID, forKey: "trace-id", into: &carrier) } } extension TestTracer { - enum TraceIDKey: Baggage.Key { + enum TraceIDKey: BaggageKey { typealias Value = String } } @@ -66,7 +69,7 @@ extension TestTracer { extension Baggage { var traceID: String? { get { - return self[TestTracer.TraceIDKey.self] + self[TestTracer.TraceIDKey.self] } set { self[TestTracer.TraceIDKey.self] = newValue diff --git a/Tests/TracingTests/TracedLock.swift b/Tests/TracingTests/TracedLock.swift index 86b3514..a17003a 100644 --- a/Tests/TracingTests/TracedLock.swift +++ b/Tests/TracingTests/TracedLock.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,9 +12,9 @@ // //===----------------------------------------------------------------------===// -import Baggage import Foundation import Instrumentation +import InstrumentationBaggage import Tracing final class TracedLock { diff --git a/Tests/TracingTests/TracedLockTests+XCTest.swift b/Tests/TracingTests/TracedLockTests+XCTest.swift index e96352b..84d1a42 100644 --- a/Tests/TracingTests/TracedLockTests+XCTest.swift +++ b/Tests/TracingTests/TracedLockTests+XCTest.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/Tests/TracingTests/TracedLockTests.swift b/Tests/TracingTests/TracedLockTests.swift index 21c5eca..07e1f07 100644 --- a/Tests/TracingTests/TracedLockTests.swift +++ b/Tests/TracingTests/TracedLockTests.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,8 +12,8 @@ // //===----------------------------------------------------------------------===// -import Baggage @testable import Instrumentation +import InstrumentationBaggage import Tracing import XCTest @@ -49,7 +50,7 @@ final class TracedLockTests: XCTestCase { // ==== ------------------------------------------------------------------------ // MARK: test keys -enum TaskIDKey: Baggage.Key { +enum TaskIDKey: BaggageKey { typealias Value = String static let name: String? = "LockedOperationNameKey" } @@ -64,7 +65,7 @@ private final class TracedLockPrintlnTracer: Tracer { ofKind kind: SpanKind, at time: DispatchWallTime ) -> Span { - return TracedLockPrintlnSpan( + TracedLockPrintlnSpan( operationName: operationName, startTime: time, kind: kind, diff --git a/Tests/TracingTests/TracerTests+XCTest.swift b/Tests/TracingTests/TracerTests+XCTest.swift index 55231cd..1737ae5 100644 --- a/Tests/TracingTests/TracerTests+XCTest.swift +++ b/Tests/TracingTests/TracerTests+XCTest.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -29,7 +30,10 @@ extension TracerTests { ("testContextPropagationWithNoOpSpan", testContextPropagationWithNoOpSpan), ("testWithSpan_success", testWithSpan_success), ("testWithSpan_throws", testWithSpan_throws), - ("testWithSpan_context", testWithSpan_context), + ("testWithSpan_automaticBaggagePropagation_sync", testWithSpan_automaticBaggagePropagation_sync), + ("testWithSpan_automaticBaggagePropagation_sync_throws", testWithSpan_automaticBaggagePropagation_sync_throws), + ("testWithSpan_automaticBaggagePropagation_async", testWithSpan_automaticBaggagePropagation_async), + ("testWithSpan_automaticBaggagePropagation_async_throws", testWithSpan_automaticBaggagePropagation_async_throws), ] } } diff --git a/Tests/TracingTests/TracerTests.swift b/Tests/TracingTests/TracerTests.swift index 82cf8cc..23ef0f8 100644 --- a/Tests/TracingTests/TracerTests.swift +++ b/Tests/TracingTests/TracerTests.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -11,8 +12,8 @@ // //===----------------------------------------------------------------------===// -import Baggage @testable import Instrumentation +import InstrumentationBaggage import Tracing import XCTest @@ -93,23 +94,149 @@ final class TracerTests: XCTestCase { XCTAssertEqual(error as? ExampleSpanError, ExampleSpanError()) return } - XCTFail("Should have throw") + XCTFail("Should have thrown") } - func testWithSpan_context() { + func testWithSpan_automaticBaggagePropagation_sync() throws { + #if swift(>=5.5) + guard #available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) else { + throw XCTSkip("Task locals are not supported on this platform.") + } + let tracer = TestTracer() InstrumentationSystem.bootstrapInternal(tracer) defer { - InstrumentationSystem.bootstrapInternal(NoOpTracer()) + InstrumentationSystem.bootstrapInternal(nil) } var spanEnded = false tracer.onEndSpan = { _ in spanEnded = true } - tracer.withSpan("", context: DefaultLoggingContext.topLevel(logger: Logger(label: "test"))) { _ in } + func operation(span: Span) -> String { + "world" + } + + let value = tracer.withSpan("hello") { (span: Span) -> String in + XCTAssertEqual(span.baggage.traceID, Baggage.current?.traceID) + return operation(span: span) + } + XCTAssertEqual(value, "world") XCTAssertTrue(spanEnded) + #endif + } + + func testWithSpan_automaticBaggagePropagation_sync_throws() throws { + #if swift(>=5.5) + guard #available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) else { + throw XCTSkip("Task locals are not supported on this platform.") + } + + let tracer = TestTracer() + InstrumentationSystem.bootstrapInternal(tracer) + defer { + InstrumentationSystem.bootstrapInternal(nil) + } + + var spanEnded = false + tracer.onEndSpan = { _ in spanEnded = true } + + func operation(span: Span) throws -> String { + throw ExampleSpanError() + } + + do { + _ = try tracer.withSpan("hello", operation) + } catch { + XCTAssertTrue(spanEnded) + XCTAssertEqual(error as? ExampleSpanError, ExampleSpanError()) + return + } + XCTFail("Should have thrown") + #endif + } + + func testWithSpan_automaticBaggagePropagation_async() throws { + #if swift(>=5.5) + guard #available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) else { + throw XCTSkip("Task locals are not supported on this platform.") + } + + let tracer = TestTracer() + InstrumentationSystem.bootstrapInternal(tracer) + defer { + InstrumentationSystem.bootstrapInternal(nil) + } + + var spanEnded = false + tracer.onEndSpan = { _ in spanEnded = true } + + func operation(span: Span) async throws -> String { + "world" + } + + try self.testAsync { + let value = try await tracer.withSpan("hello") { (span: Span) -> String in + XCTAssertEqual(span.baggage.traceID, Baggage.current?.traceID) + return try await operation(span: span) + } + + XCTAssertEqual(value, "world") + XCTAssertTrue(spanEnded) + } + #endif + } + + func testWithSpan_automaticBaggagePropagation_async_throws() throws { + #if swift(>=5.5) + guard #available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) else { + throw XCTSkip("Task locals are not supported on this platform.") + } + + let tracer = TestTracer() + InstrumentationSystem.bootstrapInternal(tracer) + defer { + InstrumentationSystem.bootstrapInternal(nil) + } + + var spanEnded = false + tracer.onEndSpan = { _ in spanEnded = true } + + func operation(span: Span) async throws -> String { + throw ExampleSpanError() + } + + self.testAsync { + do { + _ = try await tracer.withSpan("hello", operation) + } catch { + XCTAssertTrue(spanEnded) + XCTAssertEqual(error as? ExampleSpanError, ExampleSpanError()) + return + } + XCTFail("Should have thrown") + } + #endif + } + + #if swift(>=5.5) + @available(macOS 12, iOS 15, tvOS 15, watchOS 8, *) + /// Helper method to execute async operations until we can use async tests (currently incompatible with the generated LinuxMain file). + /// - Parameter operation: The operation to test. + func testAsync(_ operation: @escaping () async throws -> Void) rethrows { + let group = DispatchGroup() + group.enter() + Task.detached { + do { + try await operation() + } catch { + throw error + } + group.leave() + } + group.wait() } + #endif } struct ExampleSpanError: Error, Equatable {} @@ -120,7 +247,7 @@ typealias HTTPHeaders = [(String, String)] struct HTTPHeadersExtractor: Extractor { func extract(key: String, from headers: HTTPHeaders) -> String? { - return headers.first(where: { $0.0 == key })?.1 + headers.first(where: { $0.0 == key })?.1 } } diff --git a/Tests/TracingTests/TracingInstrumentationSystemTests+XCTest.swift b/Tests/TracingTests/TracingInstrumentationSystemTests+XCTest.swift index 604f8a5..ef03044 100644 --- a/Tests/TracingTests/TracingInstrumentationSystemTests+XCTest.swift +++ b/Tests/TracingTests/TracingInstrumentationSystemTests+XCTest.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/Tests/TracingTests/TracingInstrumentationSystemTests.swift b/Tests/TracingTests/TracingInstrumentationSystemTests.swift index 030439d..5e68ea5 100644 --- a/Tests/TracingTests/TracingInstrumentationSystemTests.swift +++ b/Tests/TracingTests/TracingInstrumentationSystemTests.swift @@ -2,7 +2,8 @@ // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -17,11 +18,11 @@ import XCTest extension InstrumentationSystem { public static func _tracer(of tracerType: T.Type) -> T? where T: Tracer { - return self._findInstrument(where: { $0 is T }) as? T + self._findInstrument(where: { $0 is T }) as? T } public static func _instrument(of instrumentType: I.Type) -> I? where I: Instrument { - return self._findInstrument(where: { $0 is I }) as? I + self._findInstrument(where: { $0 is I }) as? I } } diff --git a/docker/Dockerfile b/docker/Dockerfile index 3f2a2e7..68f0b80 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,4 +1,4 @@ -ARG swift_version=5.0 +ARG swift_version=5.2 ARG ubuntu_version=bionic ARG base_image=swift:$swift_version-$ubuntu_version FROM $base_image @@ -18,7 +18,7 @@ RUN apt-get update && apt-get install -y lsof dnsutils netcat-openbsd net-tools # ruby and jazzy for docs generation RUN apt-get update && apt-get install -y ruby ruby-dev libsqlite3-dev -RUN gem install jazzy --no-ri --no-rdoc +RUN gem install jazzy -v 0.13.7 --no-ri --no-rdoc # tools RUN mkdir -p $HOME/.tools @@ -26,7 +26,7 @@ RUN echo 'export PATH="$HOME/.tools:$PATH"' >> $HOME/.profile # swiftformat (until part of the toolchain) -ARG swiftformat_version=0.44.6 +ARG swiftformat_version=0.48.11 RUN git clone --branch $swiftformat_version --depth 1 https://github.com/nicklockwood/SwiftFormat $HOME/.tools/swift-format RUN cd $HOME/.tools/swift-format && swift build -c release RUN ln -s $HOME/.tools/swift-format/.build/release/swiftformat $HOME/.tools/swiftformat diff --git a/docker/docker-compose.1804.50.yaml b/docker/docker-compose.1804.50.yaml deleted file mode 100644 index a67fa14..0000000 --- a/docker/docker-compose.1804.50.yaml +++ /dev/null @@ -1,19 +0,0 @@ -version: "3" - -services: - - runtime-setup: - image: swift-distributed-tracing:18.04-5.0 - build: - args: - ubuntu_version: "bionic" - swift_version: "5.0" - - test: - image: swift-distributed-tracing:18.04-5.0 - - shell: - image: swift-distributed-tracing:18.04-5.0 - - docs: - image: swift-distributed-tracing:18.04-5.0 diff --git a/docker/docker-compose.1804.51.yaml b/docker/docker-compose.1804.51.yaml deleted file mode 100644 index a8bb604..0000000 --- a/docker/docker-compose.1804.51.yaml +++ /dev/null @@ -1,21 +0,0 @@ -version: "3" - -services: - - runtime-setup: - image: swift-distributed-tracing:18.04-5.1 - build: - args: - ubuntu_version: "bionic" - swift_version: "5.1" - - test: - image: swift-distributed-tracing:18.04-5.1 - environment: [] - #- SANITIZER_ARG=--sanitize=thread - - shell: - image: swift-distributed-tracing:18.04-5.1 - - docs: - image: swift-distributed-tracing:18.04-5.1 diff --git a/docker/docker-compose.1804.52.yaml b/docker/docker-compose.1804.52.yaml index 135f8a0..df31dfd 100644 --- a/docker/docker-compose.1804.52.yaml +++ b/docker/docker-compose.1804.52.yaml @@ -4,10 +4,6 @@ services: runtime-setup: image: swift-distributed-tracing:18.04-5.2 - build: - args: - ubuntu_version: "bionic" - swift_version: "5.2" test: image: swift-distributed-tracing:18.04-5.2 diff --git a/docker/docker-compose.1804.53.yaml b/docker/docker-compose.1804.53.yaml index d28ae2c..96c7160 100644 --- a/docker/docker-compose.1804.53.yaml +++ b/docker/docker-compose.1804.53.yaml @@ -6,7 +6,8 @@ services: image: swift-distributed-tracing:18.04-5.3 build: args: - base_image: "swiftlang/swift:nightly-5.3-bionic" + ubuntu_version: "bionic" + swift_version: "5.3" test: image: swift-distributed-tracing:18.04-5.3 diff --git a/docker/docker-compose.1804.54.yaml b/docker/docker-compose.1804.54.yaml new file mode 100644 index 0000000..e8e97b8 --- /dev/null +++ b/docker/docker-compose.1804.54.yaml @@ -0,0 +1,21 @@ +version: "3" + +services: + + runtime-setup: + image: swift-distributed-tracing:18.04-5.4 + build: + args: + ubuntu_version: "bionic" + swift_version: "5.4" + + test: + image: swift-distributed-tracing:18.04-5.4 + environment: [] + #- SANITIZER_ARG=--sanitize=thread + + shell: + image: swift-distributed-tracing:18.04-5.4 + + docs: + image: swift-distributed-tracing:18.04-5.4 diff --git a/docker/docker-compose.1804.55.yaml b/docker/docker-compose.1804.55.yaml new file mode 100644 index 0000000..c073a1e --- /dev/null +++ b/docker/docker-compose.1804.55.yaml @@ -0,0 +1,20 @@ +version: "3" + +services: + + runtime-setup: + image: swift-distributed-tracing:18.04-5.5 + build: + args: + base_image: "swiftlang/swift:nightly-5.5-bionic" + + test: + image: swift-distributed-tracing:18.04-5.5 + environment: [] + #- SANITIZER_ARG=--sanitize=thread + + shell: + image: swift-distributed-tracing:18.04-5.5 + + docs: + image: swift-distributed-tracing:18.04-5.5 diff --git a/docker/docker-compose.yaml b/docker/docker-compose.yaml index 757b547..bf1b661 100644 --- a/docker/docker-compose.yaml +++ b/docker/docker-compose.yaml @@ -34,15 +34,6 @@ services: test: <<: *common - security_opt: # FIXME: temp while private - - label=type:container_runtime_t - volumes: # FIXME: temp while private - - ..:/code:z - - ~/.ssh:/root/.ssh - - $SSH_AUTH_SOCK:/tmp/ssh-agent:z - environment: # FIXME: temp while private - - SSH_AUTH_SOCK=/tmp/ssh-agent - - GIT_SSH_COMMAND=ssh -vv -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no command: /bin/bash -xcl "swift test -Xswiftc -warnings-as-errors $${SANITIZER_ARG-}" # util diff --git a/scripts/generate_docs.sh b/scripts/generate_docs.sh index f5fb2bf..ee97f19 100755 --- a/scripts/generate_docs.sh +++ b/scripts/generate_docs.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/scripts/generate_linux_tests.rb b/scripts/generate_linux_tests.rb index 9c0b0c0..dc8bfa3 100755 --- a/scripts/generate_linux_tests.rb +++ b/scripts/generate_linux_tests.rb @@ -36,7 +36,8 @@ def header(fileName) // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information diff --git a/scripts/soundness.sh b/scripts/soundness.sh index 05256ad..f2fce6b 100755 --- a/scripts/soundness.sh +++ b/scripts/soundness.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information @@ -30,4 +31,3 @@ fi bash $here/validate_license_headers.sh bash $here/validate_language.sh bash $here/validate_format.sh -bash $here/validate_naming.sh diff --git a/scripts/validate_format.sh b/scripts/validate_format.sh index 7ec316d..3f62388 100755 --- a/scripts/validate_format.sh +++ b/scripts/validate_format.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/scripts/validate_language.sh b/scripts/validate_language.sh index 780e9b2..b925745 100755 --- a/scripts/validate_language.sh +++ b/scripts/validate_language.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2021 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/scripts/validate_license_headers.sh b/scripts/validate_license_headers.sh index 870e912..4d7f031 100755 --- a/scripts/validate_license_headers.sh +++ b/scripts/validate_license_headers.sh @@ -3,7 +3,8 @@ ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) 2020-2021 Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information @@ -31,7 +32,7 @@ here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" function replace_acceptable_years() { # this needs to replace all acceptable forms with 'YEARS' - sed -e 's/2019-2020/YEARS/' -e 's/2019-2021/YEARS/' -e 's/2020/YEARS/' -e 's/2021/YEARS/' + sed -e 's/2020-2021/YEARS/' -e 's/2020/YEARS/' -e 's/2021/YEARS/' } printf "=> Checking license headers\n" @@ -52,7 +53,8 @@ for language in swift-or-c bash dtrace; do // // This source file is part of the Swift Distributed Tracing open source project // -// Copyright (c) YEARS Apple Inc. and the Swift Distributed Tracing project authors +// Copyright (c) YEARS Apple Inc. and the Swift Distributed Tracing project +// authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -70,7 +72,8 @@ EOF ## ## This source file is part of the Swift Distributed Tracing open source project ## -## Copyright (c) YEARS Apple Inc. and the Swift Distributed Tracing project authors +## Copyright (c) YEARS Apple Inc. and the Swift Distributed Tracing project +## authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information @@ -88,7 +91,8 @@ EOF * * This source file is part of the Swift Distributed Tracing open source project * - * Copyright (c) YEARS Apple Inc. and the Swift Distributed Tracing project authors + * Copyright (c) YEARS Apple Inc. and the Swift Distributed Tracing project + * authors * Licensed under Apache License v2.0 * * See LICENSE.txt for license information diff --git a/scripts/validate_naming.sh b/scripts/validate_naming.sh deleted file mode 100755 index af45bf6..0000000 --- a/scripts/validate_naming.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/bin/bash -##===----------------------------------------------------------------------===## -## -## This source file is part of the Swift Distributed Tracing open source project -## -## Copyright (c) 2020 Apple Inc. and the Swift Distributed Tracing project authors -## Licensed under Apache License v2.0 -## -## See LICENSE.txt for license information -## -## SPDX-License-Identifier: Apache-2.0 -## -##===----------------------------------------------------------------------===## - -##===----------------------------------------------------------------------===## -## -## This source file is part of the SwiftNIO open source project -## -## Copyright (c) 2017-2019 Apple Inc. and the SwiftNIO project authors -## Licensed under Apache License v2.0 -## -## See LICENSE.txt for license information -## See CONTRIBUTORS.txt for the list of SwiftNIO project authors -## -## SPDX-License-Identifier: Apache-2.0 -## -##===----------------------------------------------------------------------===## - -printf "=> Checking for unacceptable language... " -# This greps for unacceptable terminology. The square bracket[s] are so that -# "git grep" doesn't find the lines that greps :). -unacceptable_terms=( - -e blacklis[t] - -e whitelis[t] - -e slav[e] -) -if git grep --color=never -i "${unacceptable_terms[@]}" > /dev/null; then - printf "\033[0;31mUnacceptable language found.\033[0m\n" - git grep -i "${unacceptable_terms[@]}" - exit 1 -fi -printf "\033[0;32mokay.\033[0m\n"