Skip to content
19 changes: 18 additions & 1 deletion Sources/Customization/DefaultEventDispatcher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ open class DefaultEventDispatcher: BackgroundingCallbacks, OPTEventDispatcher {
// for dispatching events
let queueLock = DispatchQueue(label: "DefaultEventDispatcherQueue")
// using a datastore queue with a backing file
let eventQueue: DataStoreQueueStackImpl<EventForDispatch>
private(set) var eventQueue: DataStoreQueueStackImpl<EventForDispatch>
// timer as a atomic property.
var timer = AtomicProperty<Timer>()

Expand Down Expand Up @@ -86,6 +86,23 @@ open class DefaultEventDispatcher: BackgroundingCallbacks, OPTEventDispatcher {

subscribe()
}

/// Creates a dispatcher whose event queue is a file stored in `dataStoreDirectory`
/// (e.g. `.applicationSupportDirectory` to keep it out of the Files app).
// convenience on purpose: any new designated init on an open class is an API break
public convenience init(batchSize: Int = DefaultValues.batchSize,
dataStoreName: String = "OPTEventQueue",
dataStoreDirectory: FileManager.SearchPathDirectory,
timerInterval: TimeInterval = DefaultValues.timeInterval,
maxQueueSize: Int = DefaultValues.maxQueueSize) {
self.init(batchSize: batchSize,
backingStore: .file,
dataStoreName: dataStoreName,
timerInterval: timerInterval,
maxQueueSize: maxQueueSize)
self.eventQueue = DataStoreQueueStackImpl<EventForDispatch>(queueStackName: "OPTEventQueue",
dataStore: DataStoreFile<[Data]>(storeName: dataStoreName, directory: dataStoreDirectory))
}

deinit {
stopTimer()
Expand Down
11 changes: 10 additions & 1 deletion Sources/Implementation/Datastore/DataStoreFile.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ open class DataStoreFile<T>: OPTDataStore where T: Codable {
let dataStoreName: String
let lock: DispatchQueue
let async: Bool
public let url: URL
public private(set) var url: URL

// thread-safe lazy logger load (after HandlerRegisterService ready)
private let threadSafeLogger = ThreadSafeLogger()
Expand All @@ -46,6 +46,15 @@ open class DataStoreFile<T>: OPTDataStore where T: Codable {
}

}

// convenience on purpose: any new designated init on an open class is an API break
public convenience init(storeName: String, directory: FileManager.SearchPathDirectory, async: Bool = true) {
self.init(storeName: storeName, async: async)
// create: true — unlike Documents, Application Support isn't guaranteed to exist on iOS
if let url = try? FileManager.default.url(for: directory, in: .userDomainMask, appropriateFor: nil, create: true) {
self.url = url.appendingPathComponent(storeName, isDirectory: false)
}
}
Comment on lines +51 to +57

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The target directory is never created, and .applicationSupportDirectory — the directory this feature exists to enable — does not exist by default on iOS. Writes there fail silently and events are dropped.

FileManager.urls(for:in:) returns the URL whether or not the folder exists on disk. iOS auto-creates Documents, tmp, and Library/Caches, but not Library/Application Support — the app must create it. The old code only used .documentDirectory (always present), so this never mattered before.

Downstream, writeData uses Data.write(to:options:.atomic), which does not create intermediate directories and throws if the parent is missing. saveItem swallows that into a log line, so the failure is silent:

} catch let e {
    self.logger.e(e.localizedDescription)   // event dropped, count stays 0
}

Failure scenario (the PR's own example):

let dispatcher = DefaultEventDispatcher(dataStoreDirectory: .applicationSupportDirectory)

On a real app where Library/Application Support hasn't been created, every eventQueue.save throws and is swallowed, count stays 0, flushEvents finds nothing — analytics events are silently lost. The datafile-cache path (createDataStore → DataStoreFile(directory: .applicationSupportDirectory)) fails the same way.

Why the tests miss it: both new tests pre-create the directory before using the store (DataStoreTests.testFileStoreCustomDirectory calls createDirectoryIfNeeded(...); EventDispatcherTests.testEventDispatcherFileCustomDirectory calls FileManager.default.createDirectory(at: dirUrl, withIntermediateDirectories: true)), so they only exercise a precondition the feature never establishes itself.

Proposed fix:

// convenience on purpose: any new designated init on an open class is an API break
public convenience init(storeName: String, directory: FileManager.SearchPathDirectory, async: Bool = true) {
    self.init(storeName: storeName, async: async)
    if let dirUrl = FileManager.default.urls(for: directory, in: .userDomainMask).first {
        // Application Support (unlike Documents) is not guaranteed to exist on iOS;
        // create it so writes don't silently fail and drop events.
        try? FileManager.default.createDirectory(at: dirUrl, withIntermediateDirectories: true)
        self.url = dirUrl.appendingPathComponent(storeName, isDirectory: false)
    }
}

And drop the createDirectory pre-steps from the new tests (or add a variant without them) so they actually prove the store is self-sufficient.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, thanks. Fixed in 6999d38.

  • The convenience init now resolves the directory with FileManager.default.url(for:in:appropriateFor:create: true). This is Foundation's built-in way to create a standard directory if it's missing.
  • One difference from your suggestion: if creating the directory fails, the store keeps its default location (Documents), so events are still saved and not dropped. With try? createDirectory followed by always setting url, events would still be dropped in that rare case.
  • Tests: removed the pre-create steps from testFileStoreCustomDirectory and testEventDispatcherFileCustomDirectory. I couldn't use Application Support to prove the directory gets created, because these tests have no host app. Application Support resolves to the simulator device's shared folder, which always exists and can't be deleted. So I added testFileStoreCreatesMissingDirectory, which uses .autosavedInformationDirectory (missing on a fresh simulator). It failed before the fix and passes with it.
  • DataStoreTests, EventDispatcherTests, DatafileHandlerTests: 41/41 passed. diagnose-api-breaking-changes origin/master: no breaking changes.

Could you re-review?


func isArray() -> Bool {
let t = "\(type(of: T.self))"
Expand Down
35 changes: 31 additions & 4 deletions Tests/OptimizelyTests-Common/DataStoreTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,9 @@
import XCTest

class DataStoreTests: XCTestCase {

override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
if let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

private func createDirectoryIfNeeded(directory: FileManager.SearchPathDirectory) {
if let url = FileManager.default.urls(for: directory, in: .userDomainMask).first {
if (!FileManager.default.fileExists(atPath: url.path)) {
do {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: false, attributes: nil)
Expand All @@ -30,7 +29,11 @@ class DataStoreTests: XCTestCase {

}
}
}

override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
createDirectoryIfNeeded(directory: .documentDirectory)
}

override func tearDown() {
Expand Down Expand Up @@ -168,6 +171,30 @@ class DataStoreTests: XCTestCase {
datastore.removeItem(forKey: key)
}

func testFileStoreCustomDirectory() throws {
let datastore = DataStoreFile<[String]>(storeName: "testFileStore", directory: .applicationSupportDirectory)

datastore.saveItem(forKey: "testString", value: ["value"])
let vj = datastore.getItem(forKey: "testString") as! [String]
XCTAssertEqual(vj.first, "value")

var url = try XCTUnwrap(FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first)
.appendingPathComponent("testFileStore", isDirectory: false)
XCTAssertTrue(FileManager.default.fileExists(atPath: url.path))
}

func testFileStoreCreatesMissingDirectory() throws {
// like Application Support on a fresh iOS install, this directory doesn't exist yet
let dirUrl = try XCTUnwrap(FileManager.default.urls(for: .autosavedInformationDirectory, in: .userDomainMask).first)
try XCTSkipIf(FileManager.default.fileExists(atPath: dirUrl.path), "directory already exists")
defer { try? FileManager.default.removeItem(at: dirUrl) }

let datastore = DataStoreFile<[String]>(storeName: "testFileStore", directory: .autosavedInformationDirectory)
datastore.saveItem(forKey: "testString", value: ["value"])
datastore.lock.sync {}

XCTAssertTrue(FileManager.default.fileExists(atPath: dirUrl.appendingPathComponent("testFileStore").path))
}


func testUserDefaults() {
Expand Down
21 changes: 21 additions & 0 deletions Tests/OptimizelyTests-Common/EventDispatcherTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,27 @@ class EventDispatcherTests: XCTestCase {
// Use XCTAssert and related functions to verify your tests produce the correct results.
}

func testEventDispatcherFileCustomDirectory() throws {
let dirUrl = try XCTUnwrap(FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first)
let storeName = "OPTEventQueueCustomDirectory"
let fileUrl = dirUrl.appendingPathComponent(storeName, isDirectory: false)
try? FileManager.default.removeItem(at: fileUrl)
defer { try? FileManager.default.removeItem(at: fileUrl) }

let dispatcher = DefaultEventDispatcher(dataStoreName: storeName,
dataStoreDirectory: .applicationSupportDirectory,
timerInterval: 0)
let dataStore = try XCTUnwrap(dispatcher.eventQueue.dataStore as? DataStoreFile<[Data]>)
XCTAssertEqual(dataStore.url, fileUrl)

dispatcher.eventQueue.save(item: EventForDispatch(body: Data()))
dispatcher.eventQueue.lock.sync {}
dataStore.lock.sync {}

XCTAssertEqual(dispatcher.eventQueue.count, 1)
XCTAssertTrue(FileManager.default.fileExists(atPath: fileUrl.path))
}

func testEventDispatcherUserDefaults() {
eventDispatcher = DefaultEventDispatcher( backingStore: .userDefaults)
let pEventD: OPTEventDispatcher = eventDispatcher!
Expand Down
Loading