Skip to content
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

Improve Swift concurrency safety #1376

Merged
merged 8 commits into from
Mar 5, 2024
Merged
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
12 changes: 12 additions & 0 deletions iOS_SDK/OneSignalSDK/OneSignal.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
03E56DD328405F4A006AA1DA /* OneSignalAppDelegateOverrider.m in Sources */ = {isa = PBXBuildFile; fileRef = 03E56DD228405F4A006AA1DA /* OneSignalAppDelegateOverrider.m */; };
16664C4C25DDB195003B8A14 /* NSTimeZoneOverrider.m in Sources */ = {isa = PBXBuildFile; fileRef = 16664C4B25DDB195003B8A14 /* NSTimeZoneOverrider.m */; };
37E6B2BB19D9CAF300D0C601 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 37E6B2BA19D9CAF300D0C601 /* UIKit.framework */; settings = {ATTRIBUTES = (Weak, ); }; };
3C05904B2B86BC9E00450D48 /* UnfairLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C05904A2B86BC9E00450D48 /* UnfairLock.swift */; };
3C0EF49E28A1DBCB00E5434B /* OSUserInternalImpl.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C0EF49D28A1DBCB00E5434B /* OSUserInternalImpl.swift */; };
3C115165289A259500565C41 /* OneSignalOSCore.docc in Sources */ = {isa = PBXBuildFile; fileRef = 3C115164289A259500565C41 /* OneSignalOSCore.docc */; };
3C115171289A259500565C41 /* OneSignalOSCore.h in Headers */ = {isa = PBXBuildFile; fileRef = 3C115163289A259500565C41 /* OneSignalOSCore.h */; settings = {ATTRIBUTES = (Public, ); }; };
Expand Down Expand Up @@ -943,6 +944,7 @@
1AF75EAD1E8567FD0097B315 /* NSString+OneSignal.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+OneSignal.m"; sourceTree = "<group>"; };
37747F9319147D6500558FAD /* libOneSignal.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libOneSignal.a; sourceTree = BUILT_PRODUCTS_DIR; };
37E6B2BA19D9CAF300D0C601 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };
3C05904A2B86BC9E00450D48 /* UnfairLock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnfairLock.swift; sourceTree = "<group>"; };
3C0EF49D28A1DBCB00E5434B /* OSUserInternalImpl.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OSUserInternalImpl.swift; sourceTree = "<group>"; };
3C115161289A259500565C41 /* OneSignalOSCore.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = OneSignalOSCore.framework; sourceTree = BUILT_PRODUCTS_DIR; };
3C115163289A259500565C41 /* OneSignalOSCore.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = OneSignalOSCore.h; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1638,6 +1640,14 @@
name = Frameworks;
sourceTree = "<group>";
};
3C0590492B86BC5300450D48 /* Utils */ = {
isa = PBXGroup;
children = (
3C05904A2B86BC9E00450D48 /* UnfairLock.swift */,
);
path = Utils;
sourceTree = "<group>";
};
3C115162289A259500565C41 /* OneSignalOSCore */ = {
isa = PBXGroup;
children = (
Expand All @@ -1651,6 +1661,7 @@
isa = PBXGroup;
children = (
3C115163289A259500565C41 /* OneSignalOSCore.h */,
3C0590492B86BC5300450D48 /* Utils */,
3C115188289ADEA300565C41 /* OSModelStore.swift */,
3C115186289ADE7700565C41 /* OSModelStoreListener.swift */,
3C115184289ADE4F00565C41 /* OSModel.swift */,
Expand Down Expand Up @@ -3327,6 +3338,7 @@
3C115187289ADE7700565C41 /* OSModelStoreListener.swift in Sources */,
3CE5F9E3289D88DC004A156E /* OSModelStoreChangedHandler.swift in Sources */,
3C2D8A5928B4C4E300BE41F6 /* OSDelta.swift in Sources */,
3C05904B2B86BC9E00450D48 /* UnfairLock.swift in Sources */,
3C11518D289AF5E800565C41 /* OSModelChangedHandler.swift in Sources */,
3C8E6DF928A6D89E0031E48A /* OSOperationExecutor.swift in Sources */,
);
Expand Down
44 changes: 27 additions & 17 deletions iOS_SDK/OneSignalSDK/OneSignalOSCore/Source/OSOperationRepo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,13 @@ public class OSOperationRepo: NSObject {
public static let sharedInstance = OSOperationRepo()
private var hasCalledStart = false

// The Operation Repo dispatch queue, serial. This synchronizes access to `deltaQueue` and flushing behavior.
private let dispatchQueue = DispatchQueue(label: "OneSignal.OSOperationRepo", target: .global())

// Maps delta names to the interfaces for the operation executors
var deltasToExecutorMap: [String: OSOperationExecutor] = [:]
var executors: [OSOperationExecutor] = []
var deltaQueue: [OSDelta] = []
private var deltaQueue: [OSDelta] = []

// TODO: This could come from a config, plist, method, remote params
var pollIntervalMilliseconds = Int(POLL_INTERVAL_MS)
Expand All @@ -62,7 +65,7 @@ public class OSOperationRepo: NSObject {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSOperationRepo calling start()")
// register as user observer
NotificationCenter.default.addObserver(self,
selector: #selector(self.flushDeltaQueue),
selector: #selector(self.addFlushDeltaQueueToDispatchQueue),
name: Notification.Name(OS_ON_USER_WILL_CHANGE),
object: nil)
// Read the Deltas from cache, if any...
Expand All @@ -76,7 +79,7 @@ public class OSOperationRepo: NSObject {
}

private func pollFlushQueue() {
DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(pollIntervalMilliseconds)) { [weak self] in
self.dispatchQueue.asyncAfter(deadline: .now() + .milliseconds(pollIntervalMilliseconds)) { [weak self] in
self?.flushDeltaQueue()
self?.pollFlushQueue()
}
Expand All @@ -101,14 +104,21 @@ public class OSOperationRepo: NSObject {
return
}
start()
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSOperationRepo enqueueDelta: \(delta)")
deltaQueue.append(delta)
self.dispatchQueue.async {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSOperationRepo enqueueDelta: \(delta)")
self.deltaQueue.append(delta)
// Persist the deltas (including new delta) to storage
OneSignalUserDefaults.initShared().saveCodeableData(forKey: OS_OPERATION_REPO_DELTA_QUEUE_KEY, withValue: self.deltaQueue)
}
}

// Persist the deltas (including new delta) to storage
OneSignalUserDefaults.initShared().saveCodeableData(forKey: OS_OPERATION_REPO_DELTA_QUEUE_KEY, withValue: self.deltaQueue)
@objc public func addFlushDeltaQueueToDispatchQueue(inBackground: Bool = false) {
self.dispatchQueue.async {
self.flushDeltaQueue(inBackground: inBackground)
}
}

@objc public func flushDeltaQueue(inBackground: Bool = false) {
private func flushDeltaQueue(inBackground: Bool = false) {
guard !paused else {
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OSOperationRepo not flushing queue due to being paused")
return
Expand All @@ -122,16 +132,17 @@ public class OSOperationRepo: NSObject {
OSBackgroundTaskManager.beginBackgroundTask(OPERATION_REPO_BACKGROUND_TASK)
}

start()
if !deltaQueue.isEmpty {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSOperationRepo flushDeltaQueue in background: \(inBackground) with queue: \(deltaQueue)")
self.start()

if !self.deltaQueue.isEmpty {
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSOperationRepo flushDeltaQueue in background: \(inBackground) with queue: \(self.deltaQueue)")
}

var index = 0
for delta in deltaQueue {
if let executor = deltasToExecutorMap[delta.name] {
for delta in self.deltaQueue {
if let executor = self.deltasToExecutorMap[delta.name] {
executor.enqueueDelta(delta)
deltaQueue.remove(at: index)
self.deltaQueue.remove(at: index)
} else {
// keep in queue if no executor matches, we may not have the executor available yet
index += 1
Expand All @@ -141,17 +152,16 @@ public class OSOperationRepo: NSObject {
// Persist the deltas (including removed deltas) to storage after they are divvy'd up to executors.
OneSignalUserDefaults.initShared().saveCodeableData(forKey: OS_OPERATION_REPO_DELTA_QUEUE_KEY, withValue: self.deltaQueue)

for executor in executors {
for executor in self.executors {
executor.cacheDeltaQueue()
}

for executor in executors {
for executor in self.executors {
executor.processDeltaQueue(inBackground: inBackground)
}

if inBackground {
OSBackgroundTaskManager.endBackgroundTask(OPERATION_REPO_BACKGROUND_TASK)
}

}
}
47 changes: 47 additions & 0 deletions iOS_SDK/OneSignalSDK/OneSignalOSCore/Source/Utils/UnfairLock.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
Modified MIT License

Copyright 2024 OneSignal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

1. The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

2. All copies of substantial portions of the Software may only be used in connection
with services provided by OneSignal.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

// Taken from https://swiftrocks.com/thread-safety-in-swift
// Read http://www.russbishop.net/the-law for more information on why this is necessary
public final class UnfairLock {
private var _lock: UnsafeMutablePointer<os_unfair_lock>

public init() {
_lock = UnsafeMutablePointer<os_unfair_lock>.allocate(capacity: 1)
_lock.initialize(to: os_unfair_lock())
}

deinit {
_lock.deallocate()
}

public func locked<ReturnValue>(_ closure: () throws -> ReturnValue) rethrows -> ReturnValue {
os_unfair_lock_lock(_lock)
defer { os_unfair_lock_unlock(_lock) }
return try closure()
}
}
Loading
Loading