-
-
Notifications
You must be signed in to change notification settings - Fork 377
feat: Add pending task queue for SDK initialization #7377
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
itaybre
wants to merge
4
commits into
main
Choose a base branch
from
itaybrenner/cocoa-1010-setuser-not-work-after-upgade-to-8540
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
e438753
feat: Add pending task queue for SDK initialization
itaybre d0f3cb3
feat: Enhance SentryPendingTaskQueue to support task type deduplication
itaybre d4075dc
Merge branch 'main' of github.com:getsentry/sentry-cocoa into itaybre…
itaybre 6ba2d63
Update changelog
itaybre File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| @_implementationOnly import _SentryPrivate | ||
| import Foundation | ||
|
|
||
| @objc @_spi(Private) | ||
| // swiftlint:disable:next missing_docs | ||
| public enum SentryPendingTaskType: Int { | ||
| // swiftlint:disable:next missing_docs | ||
| case setUser | ||
| } | ||
|
|
||
| /// A thread-safe queue for pending SDK operations that are called before the SDK is fully initialized. | ||
| /// | ||
| /// When the SDK is started on a background thread, there's a window where the SDK is not fully | ||
| /// initialized but user code may call methods like `setUser`, `configureScope`, or `addBreadcrumb`. | ||
| /// This queue stores those operations and executes them once the SDK is ready. | ||
| /// | ||
| /// Tasks have a type that callers can use for deduplication via ``removeAll(type:)`` before | ||
| /// enqueueing, ensuring only the most recent value for a given type is applied during execution. | ||
| /// | ||
| /// See https://github.com/getsentry/sentry-cocoa/issues/6872 | ||
| @objc | ||
| @_spi(Private) | ||
| public final class SentryPendingTaskQueue: NSObject { | ||
|
|
||
| private struct PendingTask { | ||
| let type: SentryPendingTaskType | ||
| let task: () -> Void | ||
| } | ||
|
|
||
| private let lock = NSRecursiveLock() | ||
| private var pendingTasks: [PendingTask] = [] | ||
|
|
||
| override public init() { | ||
| super.init() | ||
| } | ||
|
|
||
| /// Adds a typed task to the pending queue. | ||
| /// - Parameters: | ||
| /// - task: A closure containing the operation to be executed. | ||
| /// - type: An enum identifying the task type. | ||
| @objc public func enqueue(_ task: @escaping () -> Void, type: SentryPendingTaskType) { | ||
| lock.synchronized { | ||
| pendingTasks.append(PendingTask(type: type, task: task)) | ||
| } | ||
| SentrySDKLog.debug("Typed task '\(type)' enqueued. SDK is not fully initialized yet.") | ||
| } | ||
|
|
||
| /// Removes all pending tasks of the given type without executing them. | ||
| @objc public func removeAll(type: SentryPendingTaskType) { | ||
| lock.synchronized { | ||
| pendingTasks.removeAll { $0.type == type } | ||
| } | ||
| } | ||
|
|
||
| /// Executes all pending tasks and clears the queue. | ||
| /// This should be called from the SDK initialization code after the hub is fully set up. | ||
| @objc public func executePendingTasks() { | ||
| let tasks = lock.synchronized { | ||
| let tasks = pendingTasks | ||
| pendingTasks = [] | ||
| return tasks | ||
| } | ||
|
|
||
| guard !tasks.isEmpty else { | ||
| return | ||
| } | ||
|
|
||
| SentrySDKLog.debug("Executing \(tasks.count) pending task(s) after SDK initialization.") | ||
|
|
||
| for entry in tasks { | ||
| entry.task() | ||
| } | ||
| } | ||
|
|
||
| /// Clears all pending tasks without executing them. | ||
| /// This is useful when the SDK is closed. | ||
| @objc public func clearPendingTasks() { | ||
| lock.synchronized { | ||
| pendingTasks.removeAll() | ||
| } | ||
| } | ||
|
|
||
| #if SENTRY_TEST || SENTRY_TEST_CI | ||
| /// Returns the number of pending tasks. | ||
| /// Used for testing. | ||
| @objc public var pendingTaskCount: Int { | ||
| lock.synchronized { | ||
| return pendingTasks.count | ||
| } | ||
| } | ||
| #endif | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
185 changes: 185 additions & 0 deletions
185
Tests/SentryTests/Helper/SentryPendingTaskQueueTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,185 @@ | ||
| @testable import Sentry | ||
| import XCTest | ||
|
|
||
| class SentryPendingTaskQueueTests: XCTestCase { | ||
|
|
||
| private var sut: SentryPendingTaskQueue! | ||
|
|
||
| override func setUp() { | ||
| super.setUp() | ||
| sut = SentryDependencyContainer.sharedInstance().pendingTaskQueue | ||
| sut.clearPendingTasks() | ||
| } | ||
|
|
||
| override func tearDown() { | ||
| sut.clearPendingTasks() | ||
| super.tearDown() | ||
| } | ||
|
|
||
| func testEnqueue_whenCalled_shouldIncreasePendingTaskCount() { | ||
| // -- Arrange -- | ||
| XCTAssertEqual(0, sut.pendingTaskCount) | ||
|
|
||
| // -- Act -- | ||
| sut.enqueue({ }, type: .setUser) | ||
|
|
||
| // -- Assert -- | ||
| XCTAssertEqual(1, sut.pendingTaskCount) | ||
| } | ||
|
|
||
| func testEnqueue_whenCalledMultipleTimes_shouldAccumulateTasks() { | ||
| // -- Arrange -- | ||
| XCTAssertEqual(0, sut.pendingTaskCount) | ||
|
|
||
| // -- Act -- | ||
| sut.enqueue({ }, type: .setUser) | ||
| sut.enqueue({ }, type: .setUser) | ||
| sut.enqueue({ }, type: .setUser) | ||
|
|
||
| // -- Assert -- | ||
| XCTAssertEqual(3, sut.pendingTaskCount) | ||
| } | ||
|
|
||
| func testExecutePendingTasks_whenTasksExist_shouldExecuteAllTasksInOrder() { | ||
| // -- Arrange -- | ||
| var executionOrder: [Int] = [] | ||
|
|
||
| sut.enqueue({ executionOrder.append(1) }, type: .setUser) | ||
| sut.enqueue({ executionOrder.append(2) }, type: .setUser) | ||
| sut.enqueue({ executionOrder.append(3) }, type: .setUser) | ||
|
|
||
| // -- Act -- | ||
| sut.executePendingTasks() | ||
|
|
||
| // -- Assert -- | ||
| XCTAssertEqual([1, 2, 3], executionOrder) | ||
| XCTAssertEqual(0, sut.pendingTaskCount) | ||
| } | ||
|
|
||
| func testExecutePendingTasks_whenNoTasks_shouldDoNothing() { | ||
| // -- Arrange -- | ||
| XCTAssertEqual(0, sut.pendingTaskCount) | ||
|
|
||
| // -- Act -- | ||
| sut.executePendingTasks() | ||
|
|
||
| // -- Assert -- | ||
| XCTAssertEqual(0, sut.pendingTaskCount) | ||
| } | ||
|
|
||
| func testClearPendingTasks_whenTasksExist_shouldRemoveAllWithoutExecuting() { | ||
| // -- Arrange -- | ||
| var wasExecuted = false | ||
| sut.enqueue({ wasExecuted = true }, type: .setUser) | ||
| XCTAssertEqual(1, sut.pendingTaskCount) | ||
|
|
||
| // -- Act -- | ||
| sut.clearPendingTasks() | ||
|
|
||
| // -- Assert -- | ||
| XCTAssertEqual(0, sut.pendingTaskCount) | ||
| XCTAssertFalse(wasExecuted) | ||
| } | ||
|
|
||
| func testExecutePendingTasks_whenCalledTwice_shouldOnlyExecuteOnce() { | ||
| // -- Arrange -- | ||
| var executionCount = 0 | ||
| sut.enqueue({ executionCount += 1 }, type: .setUser) | ||
|
|
||
| // -- Act -- | ||
| sut.executePendingTasks() | ||
| sut.executePendingTasks() | ||
|
|
||
| // -- Assert -- | ||
| XCTAssertEqual(1, executionCount) | ||
| } | ||
|
|
||
| // MARK: - removeAll(type:) | ||
|
|
||
| func testRemoveAllWithType_shouldRemoveMatchingTasks() { | ||
| // -- Arrange -- | ||
| var executedValue = "" | ||
| sut.enqueue({ executedValue = "old" }, type: .setUser) | ||
| XCTAssertEqual(1, sut.pendingTaskCount) | ||
|
|
||
| // -- Act -- | ||
| sut.removeAll(type: .setUser) | ||
|
|
||
| // -- Assert -- | ||
| XCTAssertEqual(0, sut.pendingTaskCount) | ||
| sut.executePendingTasks() | ||
| XCTAssertEqual("", executedValue) | ||
| } | ||
|
|
||
| func testRemoveAllWithType_shouldRemoveAllMatchingTasks() { | ||
| // -- Arrange -- | ||
| sut.enqueue({ }, type: .setUser) | ||
| sut.enqueue({ }, type: .setUser) | ||
| sut.enqueue({ }, type: .setUser) | ||
| XCTAssertEqual(3, sut.pendingTaskCount) | ||
|
|
||
| // -- Act -- | ||
| sut.removeAll(type: .setUser) | ||
|
|
||
| // -- Assert -- | ||
| XCTAssertEqual(0, sut.pendingTaskCount) | ||
| } | ||
|
|
||
| func testRemoveAllThenEnqueue_shouldKeepOnlyLatestTask() { | ||
| // -- Arrange -- | ||
| var executedValues: [String] = [] | ||
|
|
||
| sut.enqueue({ executedValues.append("old-user") }, type: .setUser) | ||
|
|
||
| // -- Act -- | ||
| // Simulates what setUser does: clear old, enqueue new | ||
| sut.removeAll(type: .setUser) | ||
| sut.enqueue({ executedValues.append("new-user") }, type: .setUser) | ||
|
|
||
| // -- Assert -- | ||
| XCTAssertEqual(1, sut.pendingTaskCount) | ||
| sut.executePendingTasks() | ||
| XCTAssertEqual(["new-user"], executedValues) | ||
| } | ||
|
|
||
| func testEnqueueAndExecute_whenConcurrent_shouldBeThreadSafe() { | ||
| // -- Arrange -- | ||
| let queue1 = DispatchQueue(label: "test.queue1", attributes: .concurrent) | ||
| let queue2 = DispatchQueue(label: "test.queue2", attributes: .concurrent) | ||
| let expectation = XCTestExpectation(description: "All tasks completed") | ||
| expectation.expectedFulfillmentCount = 100 | ||
|
|
||
| var executionCount = 0 | ||
| let lock = NSLock() | ||
|
|
||
| // -- Act -- | ||
| for _ in 0..<50 { | ||
| queue1.async { | ||
| self.sut.enqueue({ | ||
| lock.synchronized { | ||
| executionCount += 1 | ||
| } | ||
| }, type: .setUser) | ||
| expectation.fulfill() | ||
| } | ||
|
|
||
| queue2.async { | ||
| self.sut.enqueue({ | ||
| lock.synchronized { | ||
| executionCount += 1 | ||
| } | ||
| }, type: .setUser) | ||
| expectation.fulfill() | ||
| } | ||
| } | ||
|
|
||
| wait(for: [expectation], timeout: 5.0) | ||
|
|
||
| // Execute all pending tasks | ||
| sut.executePendingTasks() | ||
|
|
||
| // -- Assert -- | ||
| XCTAssertEqual(100, executionCount) | ||
| XCTAssertEqual(0, sut.pendingTaskCount) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Race condition causes incorrect ordering of setUser operations
Medium Severity
There's a race condition window between
setCurrentHub(line 230) andexecutePendingTasks(line 236) whereisEnabledreturns true but pending tasks haven't executed yet. IfsetUseris called from another thread during this window, it calls the hub directly while older queued tasks are still pending. WhenexecutePendingTaskssubsequently runs, it executes the older tasks, potentially overwriting the newer value with stale data. This can cause the wrong user to be set when multiplesetUsercalls happen around SDK initialization time.Additional Locations (1)
Sources/Sentry/SentrySDKInternal.m#L457-L467