Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions LaunchDarkly.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@
3D3AB9462A4F16FE003AECF1 /* ReportingConsts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D3AB9422A4F16FE003AECF1 /* ReportingConsts.swift */; };
3D3AB9482A570F3A003AECF1 /* ModifierSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D3AB9472A570F3A003AECF1 /* ModifierSpec.swift */; };
3D9A12582A73236800698B8D /* UtilSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D9A12572A73236800698B8D /* UtilSpec.swift */; };
50EE85C22EA0487F007CC662 /* TimeoutExecutor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50EE85C12EA0487F007CC662 /* TimeoutExecutor.swift */; };
50EE85C32EA0487F007CC662 /* TimeoutExecutor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50EE85C12EA0487F007CC662 /* TimeoutExecutor.swift */; };
50EE85C42EA0487F007CC662 /* TimeoutExecutor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50EE85C12EA0487F007CC662 /* TimeoutExecutor.swift */; };
50EE85C52EA0487F007CC662 /* TimeoutExecutor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50EE85C12EA0487F007CC662 /* TimeoutExecutor.swift */; };
50EE85C72EA0749C007CC662 /* TimeoutExecutorSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 50EE85C62EA0749C007CC662 /* TimeoutExecutorSpec.swift */; };
830BF933202D188E006DF9B1 /* HTTPURLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 830BF932202D188E006DF9B1 /* HTTPURLRequest.swift */; };
830DB3AC22380A3E00D65D25 /* HTTPHeadersSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = 830DB3AB22380A3E00D65D25 /* HTTPHeadersSpec.swift */; };
830DB3AE2239B54900D65D25 /* URLResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 830DB3AD2239B54900D65D25 /* URLResponse.swift */; };
Expand Down Expand Up @@ -429,6 +434,8 @@
3D3AB9422A4F16FE003AECF1 /* ReportingConsts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReportingConsts.swift; sourceTree = "<group>"; };
3D3AB9472A570F3A003AECF1 /* ModifierSpec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModifierSpec.swift; sourceTree = "<group>"; };
3D9A12572A73236800698B8D /* UtilSpec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilSpec.swift; sourceTree = "<group>"; };
50EE85C12EA0487F007CC662 /* TimeoutExecutor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TimeoutExecutor.swift; sourceTree = "<group>"; };
50EE85C62EA0749C007CC662 /* TimeoutExecutorSpec.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TimeoutExecutorSpec.swift; sourceTree = "<group>"; };
830BF932202D188E006DF9B1 /* HTTPURLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPURLRequest.swift; sourceTree = "<group>"; };
830DB3AB22380A3E00D65D25 /* HTTPHeadersSpec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HTTPHeadersSpec.swift; sourceTree = "<group>"; };
830DB3AD2239B54900D65D25 /* URLResponse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = URLResponse.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -629,6 +636,7 @@
831D8B751F72A48900ED65E8 /* ServiceObjects */ = {
isa = PBXGroup;
children = (
50EE85C62EA0749C007CC662 /* TimeoutExecutorSpec.swift */,
A3047D5B2A606A0000F568E0 /* EnvironmentReporting */,
B46F344025E6DB7D0078D45F /* DiagnosticReporterSpec.swift */,
83CFE7CD1F7AD81D0010544E /* EventReporterSpec.swift */,
Expand Down Expand Up @@ -887,6 +895,7 @@
83FEF8D91F2666BF001CF12C /* ServiceObjects */ = {
isa = PBXGroup;
children = (
50EE85C12EA0487F007CC662 /* TimeoutExecutor.swift */,
A3A8BCD12B7EAA89009A77E4 /* SheddingQueue.swift */,
A358D6CF2A4DD45000270C60 /* EnvironmentReporting */,
8354AC742243168800CDE602 /* Cache */,
Expand Down Expand Up @@ -1355,6 +1364,7 @@
3D3AB9462A4F16FE003AECF1 /* ReportingConsts.swift in Sources */,
831188522113ADF700D77CB5 /* KeyedValueCache.swift in Sources */,
831188582113AE0F00D77CB5 /* EventReporter.swift in Sources */,
50EE85C42EA0487F007CC662 /* TimeoutExecutor.swift in Sources */,
A358D6F52A4DEB4C00270C60 /* EnvironmentReporterBuilder.swift in Sources */,
8311885D2113AE2500D77CB5 /* DarklyService.swift in Sources */,
831188692113AE5900D77CB5 /* ObjcLDConfig.swift in Sources */,
Expand Down Expand Up @@ -1481,6 +1491,7 @@
A3A8BCD42B7EAA89009A77E4 /* SheddingQueue.swift in Sources */,
B4C9D43A2489E20A004A9B03 /* DiagnosticReporter.swift in Sources */,
831EF36A20655E730001C643 /* ObjcLDChangedFlag.swift in Sources */,
50EE85C22EA0487F007CC662 /* TimeoutExecutor.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down Expand Up @@ -1508,6 +1519,7 @@
3D3AB9432A4F16FE003AECF1 /* ReportingConsts.swift in Sources */,
A31088172837DC0400184942 /* Reference.swift in Sources */,
8354EFE21F26380700C05156 /* Event.swift in Sources */,
50EE85C52EA0487F007CC662 /* TimeoutExecutor.swift in Sources */,
A358D6F22A4DEB4C00270C60 /* EnvironmentReporterBuilder.swift in Sources */,
C408884923033B7500420721 /* ConnectionInformation.swift in Sources */,
831D8B721F71D3E700ED65E8 /* DarklyService.swift in Sources */,
Expand Down Expand Up @@ -1606,6 +1618,7 @@
838AB53F1F72A7D5006F03F5 /* FlagSynchronizerSpec.swift in Sources */,
A3FFE1132B7D4BA2009EF93F /* LDValueDecoderSpec.swift in Sources */,
A3570F5A28527B8200CF241A /* LDContextCodableSpec.swift in Sources */,
50EE85C72EA0749C007CC662 /* TimeoutExecutorSpec.swift in Sources */,
837406D421F760640087B22B /* LDTimerSpec.swift in Sources */,
832307A61F7D8D720029815A /* URLRequestSpec.swift in Sources */,
A3BA7D022BD192240000DB28 /* LDClientHookSpec.swift in Sources */,
Expand Down Expand Up @@ -1639,6 +1652,7 @@
3D3AB9442A4F16FE003AECF1 /* ReportingConsts.swift in Sources */,
83D9EC7E2062DEAB004D7FA6 /* FlagChangeObserver.swift in Sources */,
83D9EC7F2062DEAB004D7FA6 /* FlagsUnchangedObserver.swift in Sources */,
50EE85C32EA0487F007CC662 /* TimeoutExecutor.swift in Sources */,
A358D6F32A4DEB4C00270C60 /* EnvironmentReporterBuilder.swift in Sources */,
83D9EC802062DEAB004D7FA6 /* Event.swift in Sources */,
83D9EC822062DEAB004D7FA6 /* ClientServiceFactory.swift in Sources */,
Expand Down Expand Up @@ -2017,6 +2031,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = "$(inherited)";
DEVELOPMENT_TEAM = 53D32B66PT;
INFOPLIST_FILE = "$(PROJECT_DIR)/LaunchDarkly/LaunchDarklyTests/Info.plist";
PRODUCT_BUNDLE_IDENTIFIER = com.launchdarkly.DarklyTests;
PRODUCT_NAME = "$(TARGET_NAME)";
Expand All @@ -2027,6 +2042,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = "$(inherited)";
DEVELOPMENT_TEAM = 53D32B66PT;
INFOPLIST_FILE = "$(PROJECT_DIR)/LaunchDarkly/LaunchDarklyTests/Info.plist";
PRODUCT_BUNDLE_IDENTIFIER = com.launchdarkly.DarklyTests;
PRODUCT_NAME = "$(TARGET_NAME)";
Expand Down
54 changes: 23 additions & 31 deletions LaunchDarkly/LaunchDarkly/LDClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -384,22 +384,18 @@ public class LDClient {
if timeout > LDClient.longTimeoutInterval {
os_log("%s LDClient.identify was called with a timeout greater than %f seconds. We recommend a timeout of less than %f seconds.", log: config.logger, type: .info, self.typeName(and: #function), LDClient.longTimeoutInterval, LDClient.longTimeoutInterval)
}

var cancel = false

DispatchQueue.global().asyncAfter(deadline: .now() + timeout) {
guard !cancel else { return }

cancel = true
completion(.timeout)
}

identify(context: context, useCache: useCache) { result in
guard !cancel else { return }

cancel = true
completion(result)
}

TimeoutExecutor.run(
timeout: timeout,
queue: .global(),
operation: { done in
self.identify(context: context, useCache: useCache) { result in
done(result)
}
},
timeoutValue: .timeout,
completion: completion
)
}

func internalIdentify(newContext: LDContext, useCache: IdentifyCacheUsage, completion: (() -> Void)? = nil) {
Expand Down Expand Up @@ -854,27 +850,23 @@ public class LDClient {
}

static func start(serviceFactory: ClientServiceCreating?, config: LDConfig, context: LDContext? = nil, startWaitSeconds: TimeInterval, completion: ((_ timedOut: Bool) -> Void)? = nil) {
var completed = false
let internalCompletedQueue: DispatchQueue = DispatchQueue(label: "TimeOutQueue")
if !config.startOnline {
start(serviceFactory: serviceFactory, config: config, context: context)
// Consider to wrap this into internalCompletedQueue to make completion return always consistent
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Callback Context Inconsistency

The start method's completion callback has an inconsistent execution context. When config.startOnline is false, the callback runs on the current thread, but when true, it's dispatched to internalCompletedQueue. This difference in threading might lead to unexpected behavior for callers.

Fix in Cursor Fix in Web

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

true, but this is not part of this fix

completion?(true) // offline is considered a short circuited timed out case
} else {
let startTime = Date().timeIntervalSince1970
start(serviceFactory: serviceFactory, config: config, context: context) {
internalCompletedQueue.async {
if startTime + startWaitSeconds > Date().timeIntervalSince1970 && !completed {
completed = true
completion?(false) // false for not timedOut
TimeoutExecutor.run(
timeout: startWaitSeconds,
queue: internalCompletedQueue,
operation: { done in
start(serviceFactory: serviceFactory, config: config, context: context) {
done(false)
}
}
}
internalCompletedQueue.asyncAfter(deadline: .now() + startWaitSeconds) {
if !completed {
completed = true
completion?(true) // true for timedOut
}
}
},
timeoutValue: true,
completion: completion
)
}
}

Expand Down
76 changes: 76 additions & 0 deletions LaunchDarkly/LaunchDarkly/ServiceObjects/TimeoutExecutor.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import Foundation

/// A lightweight utility for executing asynchronous operations with a timeout fallback.
///
/// `TimeoutExecutor` guarantees that the provided `completion` closure is called **exactly once**,
/// either with the result of the asynchronous operation or with a timeout value if the operation
/// does not complete in time.
///
/// ### Typical Usage
/// ```swift
/// TimeoutExecutor.run(
/// timeout: 2.0,
/// queue: .main,
/// operation: { done in
/// service.action() {
/// done("Success")
/// }
/// },
/// timeoutValue: "Timeout",
/// completion: { result in
/// print("Result:", result)
/// }
/// )
/// ```
///
final class TimeoutExecutor {
private init() {}

static func run<T>(
timeout: TimeInterval,
queue: DispatchQueue = .global(),
operation: (@escaping (T) -> Void) -> Void,
timeoutValue: @autoclosure @escaping () -> T,
completion: ((T) -> Void)?
) {
guard let completion = completion else {
operation { _ in
/* ignore result */
}
return
}

let lockQueue = DispatchQueue(label: "launchdarkly.timeout.executor.lock")
var finished = false

// Start the user operation
operation { value in
var shouldCall = false
lockQueue.sync {
if !finished {
finished = true
shouldCall = true
}
}

if shouldCall {
queue.async { completion(value) }
}
}

// Timeout fallback
queue.asyncAfter(deadline: .now() + timeout) {
var shouldCall = false
lockQueue.sync {
if !finished {
finished = true
shouldCall = true
}
}

if shouldCall {
completion(timeoutValue())
}
}
}
}
Loading
Loading