Skip to content

Commit

Permalink
Merge pull request #535 from DataDog/louiszawadzki/fix-ios-flaky-test
Browse files Browse the repository at this point in the history
Fix iOS tracer concurrency
  • Loading branch information
louiszawadzki authored and louiszawadzki committed Oct 30, 2023
1 parent f2333b8 commit a045dd7
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 4 deletions.
5 changes: 2 additions & 3 deletions packages/core/ios/Sources/DdTraceImplementation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,14 +44,13 @@ public class DdTraceImplementation: NSObject {
public func finishSpan(spanId: NSString, context: NSDictionary, timestampMs: Double, resolve:RCTPromiseResolveBlock, reject:RCTPromiseRejectBlock) -> Void {
objc_sync_enter(self)
let optionalSpan = spanDictionary.removeValue(forKey: spanId)
objc_sync_exit(self)

if let span = optionalSpan {
set(tags: castAttributesToSwift(context).mergeWithGlobalAttributes(), to: span)
let timeIntervalSince1970: TimeInterval = timestampMs / 1_000
span.finish(at: Date(timeIntervalSince1970: timeIntervalSince1970))
}

objc_sync_exit(self)

resolve(nil)
}

Expand Down
6 changes: 5 additions & 1 deletion packages/core/ios/Tests/DdTraceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,10 @@ internal class DdTraceTests: XCTestCase {
}

func testTracingConcurrently() {
// It is possible and acceptable that a concurrent finishSpan resolve is called on a different thread before we get the lastResolveValue.
// This would override lastResolveValue to be `nil`. To avoid this, we use a different resolve.
func mockFinishResolve(args: Any?) {}

let iterationCount = 30
DispatchQueue.concurrentPerform(iterations: iterationCount) { iteration in
tracer.startSpan(
Expand All @@ -149,7 +153,7 @@ internal class DdTraceTests: XCTestCase {
reject: mockReject
)
let spanID = lastResolveValue as! NSString
tracer.finishSpan(spanId: spanID, context: testTags, timestampMs: 100, resolve: mockResolve, reject: mockReject)
tracer.finishSpan(spanId: spanID, context: testTags, timestampMs: 100, resolve: mockFinishResolve, reject: mockReject)
}

XCTAssertEqual(mockNativeTracer.startedSpans.count, iterationCount, "\(mockNativeTracer.startedSpans)")
Expand Down

0 comments on commit a045dd7

Please sign in to comment.