Skip to content

Commit

Permalink
fix: storage instance issue
Browse files Browse the repository at this point in the history
  • Loading branch information
liuyang1520 committed Feb 13, 2024
1 parent d6c2768 commit 585259f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
9 changes: 8 additions & 1 deletion Sources/Amplitude/Utilities/OutputFileStream.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,21 @@ internal class OutputFileStream {
if fileHandle != nil { return }
do {
fileHandle = try FileHandle(forWritingTo: fileURL)
if #available(macOS 10.15.4, iOS 13.4, macCatalyst 13.4, tvOS 13.4, watchOS 6.2, *) {
_ = try? fileHandle?.seekToEnd()
} else if #available(tvOS 13.0, *) {
try? fileHandle?.seek(toOffset: .max)
} else {
fileHandle?.seekToEndOfFile()
}
} catch {
throw OutputStreamError.unableToOpen(fileURL.path)
}
}

func write(_ data: Data) throws {
guard data.isEmpty == false else { return }
if #available(macOS 10.15.4, iOS 13.4, macCatalyst 13.4, tvOS 13.4, watchOS 13.4, *) {
if #available(macOS 10.15.4, iOS 13.4, macCatalyst 13.4, tvOS 13.4, watchOS 6.2, *) {
do {
try fileHandle?.write(contentsOf: data)
} catch {
Expand Down
27 changes: 27 additions & 0 deletions Tests/AmplitudeTests/Storages/PersistentStorageTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,31 @@ final class PersistentStorageTests: XCTestCase {
XCTAssertNotEqual(eventFiles?[0].pathExtension, PersistentStorage.TEMP_FILE_EXTENSION)
persistentStorage.reset()
}

func testWriteWithTwoInstances() {
let persistentStorage1 = PersistentStorage(storagePrefix: "xxx-instance")
try? persistentStorage1.write(
key: StorageKey.EVENTS,
value: BaseEvent(eventType: "test1")
)
let persistentStorage2 = PersistentStorage(storagePrefix: "xxx-instance")
try? persistentStorage2.write(
key: StorageKey.EVENTS,
value: BaseEvent(eventType: "test2")
)
// Only read from second instance, reading from first instance insert the "]" at the wrong cursor.
let eventFiles2: [URL]? = persistentStorage2.read(key: StorageKey.EVENTS)
XCTAssertEqual(eventFiles2?[0].absoluteString.contains("xxx-instance.events.index"), true)
XCTAssertNotEqual(eventFiles2?[0].pathExtension, PersistentStorage.TEMP_FILE_EXTENSION)

XCTAssertEqual(eventFiles2?.count, 1)

let eventString2 = persistentStorage2.getEventsString(eventBlock: (eventFiles2?[0])!)
let decodedEvents = BaseEvent.fromArrayString(jsonString: eventString2!)
XCTAssertEqual(decodedEvents!.count, 2)
XCTAssertEqual(decodedEvents![0].eventType, "test1")
XCTAssertEqual(decodedEvents![1].eventType, "test2")
persistentStorage1.reset()
persistentStorage2.reset()
}
}

0 comments on commit 585259f

Please sign in to comment.