diff --git a/Modules/Account/Sources/Account/ErrorLog/ErrorLogDatabase.swift b/Modules/Account/Sources/Account/ErrorLog/ErrorLogDatabase.swift deleted file mode 100644 index 059cac005..000000000 --- a/Modules/Account/Sources/Account/ErrorLog/ErrorLogDatabase.swift +++ /dev/null @@ -1,55 +0,0 @@ -// -// ErrorLogDatabase.swift -// Account -// -// Created by Brent Simmons on 3/11/26. -// - -import Foundation -import RSDatabase -import RSDatabaseObjC - -public actor ErrorLogDatabase { - - private let database: FMDatabase - - private static let tableCreationStatements = "CREATE TABLE if not EXISTS errors (id INTEGER PRIMARY KEY AUTOINCREMENT, date REAL NOT NULL, accountName TEXT NOT NULL, accountType INTEGER NOT NULL, errorMessage TEXT NOT NULL);" - - private static let pruneLimit = 200 - - public init(databasePath: String) { - let database = FMDatabase.openAndSetUpDatabase(path: databasePath) - database.executeStatements("PRAGMA journal_mode = WAL;") - database.runCreateStatements(Self.tableCreationStatements) - ErrorLogTable.pruneEntries(limit: Self.pruneLimit, database: database) - - self.database = database - - NotificationCenter.default.addObserver(self, selector: #selector(handleAccountDidEncounterSyncError(_:)), name: .AccountDidEncounterSyncError, object: nil) - } - - public func addEntry(accountName: String, accountType: Int, errorMessage: String) { - ErrorLogTable.insertEntry(accountName: accountName, accountType: accountType, errorMessage: errorMessage, database: database) - } - - public func allEntries() -> [ErrorLogEntry] { - ErrorLogTable.allEntries(database: database) - } - - public func deleteAll() { - ErrorLogTable.deleteAll(database: database) - } - - // MARK: - Notifications - - @objc nonisolated func handleAccountDidEncounterSyncError(_ notification: Notification) { - guard let error = notification.userInfo?[Account.UserInfoKey.syncError] as? Error, - let accountName = notification.userInfo?[Account.UserInfoKey.accountName] as? String, - let accountType = notification.userInfo?[Account.UserInfoKey.accountType] as? Int else { - return - } - Task { - await addEntry(accountName: accountName, accountType: accountType, errorMessage: error.localizedDescription) - } - } -} diff --git a/Modules/ErrorLog/Package.swift b/Modules/ErrorLog/Package.swift new file mode 100644 index 000000000..892975bc2 --- /dev/null +++ b/Modules/ErrorLog/Package.swift @@ -0,0 +1,36 @@ +// swift-tools-version:6.2 +import PackageDescription + +let package = Package( + name: "ErrorLog", + platforms: [.macOS(.v15), .iOS(.v26)], + products: [ + .library( + name: "ErrorLog", + type: .dynamic, + targets: ["ErrorLog"]) + ], + dependencies: [ + .package(path: "../RSCore"), + .package(path: "../RSDatabase") + ], + targets: [ + .target( + name: "ErrorLog", + dependencies: [ + "RSCore", + "RSDatabase" + ], + swiftSettings: [ + .enableUpcomingFeature("NonisolatedNonsendingByDefault"), + .enableUpcomingFeature("InferIsolatedConformances"), + .unsafeFlags(["-warnings-as-errors"]) + ] + ), + .testTarget( + name: "ErrorLogTests", + dependencies: ["ErrorLog"], + swiftSettings: [.swiftLanguageMode(.v6)] + ) + ] +) diff --git a/Modules/ErrorLog/Sources/ErrorLog/ErrorLogDatabase.swift b/Modules/ErrorLog/Sources/ErrorLog/ErrorLogDatabase.swift new file mode 100644 index 000000000..070f52da4 --- /dev/null +++ b/Modules/ErrorLog/Sources/ErrorLog/ErrorLogDatabase.swift @@ -0,0 +1,54 @@ +// +// ErrorLogDatabase.swift +// ErrorLog +// +// Created by Brent Simmons on 3/11/26. +// + +import Foundation +import RSCore +import RSDatabase +import RSDatabaseObjC + +public actor ErrorLogDatabase { + + private let database: FMDatabase + + private static let tableCreationStatements = "CREATE TABLE if not EXISTS errors (id INTEGER PRIMARY KEY AUTOINCREMENT, date REAL NOT NULL, sourceName TEXT NOT NULL, sourceID INTEGER NOT NULL, errorMessage TEXT NOT NULL);" + + private static let pruneLimit = 200 + + public init(databasePath: String) { + let database = FMDatabase.openAndSetUpDatabase(path: databasePath) + database.executeStatements("PRAGMA journal_mode = WAL;") + database.runCreateStatements(Self.tableCreationStatements) + ErrorLogTable.pruneEntries(limit: Self.pruneLimit, database: database) + + self.database = database + + if !Platform.isRunningUnitTests { + NotificationCenter.default.addObserver(self, selector: #selector(handleAppDidEncounterError(_:)), name: .appDidEncounterError, object: nil) + } + } + + public func addEntry(sourceName: String, sourceID: Int, errorMessage: String) { + ErrorLogTable.insertEntry(sourceName: sourceName, sourceID: sourceID, errorMessage: errorMessage, database: database) + } + + public func allEntries() -> [ErrorLogEntry] { + ErrorLogTable.allEntries(database: database) + } + + // MARK: - Notifications + + @objc nonisolated func handleAppDidEncounterError(_ notification: Notification) { + guard let errorMessage = notification.userInfo?[ErrorLogUserInfoKey.errorMessage] as? String, + let sourceName = notification.userInfo?[ErrorLogUserInfoKey.sourceName] as? String, + let sourceID = notification.userInfo?[ErrorLogUserInfoKey.sourceID] as? Int else { + return + } + Task { + await addEntry(sourceName: sourceName, sourceID: sourceID, errorMessage: errorMessage) + } + } +} diff --git a/Modules/Account/Sources/Account/ErrorLog/ErrorLogEntry.swift b/Modules/ErrorLog/Sources/ErrorLog/ErrorLogEntry.swift similarity index 54% rename from Modules/Account/Sources/Account/ErrorLog/ErrorLogEntry.swift rename to Modules/ErrorLog/Sources/ErrorLog/ErrorLogEntry.swift index 6d2d08699..4bafbf0c7 100644 --- a/Modules/Account/Sources/Account/ErrorLog/ErrorLogEntry.swift +++ b/Modules/ErrorLog/Sources/ErrorLog/ErrorLogEntry.swift @@ -1,6 +1,6 @@ // // ErrorLogEntry.swift -// Account +// ErrorLog // // Created by Brent Simmons on 3/11/26. // @@ -10,33 +10,33 @@ import RSDatabase public struct ErrorLogEntry: Sendable { - public let id: Int64 + public let id: Int public let date: Date - public let accountName: String - public let accountType: Int + public let sourceName: String + public let sourceID: Int // 0-99 reserved for AccountType.rawValue. 100 and up for other components. public let errorMessage: String - public init(id: Int64, date: Date, accountName: String, accountType: Int, errorMessage: String) { + public init(id: Int, date: Date, sourceName: String, sourceID: Int, errorMessage: String) { self.id = id self.date = date - self.accountName = accountName - self.accountType = accountType + self.sourceName = sourceName + self.sourceID = sourceID self.errorMessage = errorMessage } struct DatabaseKey { static let id = "id" static let date = "date" - static let accountName = "accountName" - static let accountType = "accountType" + static let sourceName = "sourceName" + static let sourceID = "sourceID" static let errorMessage = "errorMessage" } func databaseDictionary() -> DatabaseDictionary { [ DatabaseKey.date: date.timeIntervalSince1970, - DatabaseKey.accountName: accountName, - DatabaseKey.accountType: accountType, + DatabaseKey.sourceName: sourceName, + DatabaseKey.sourceID: sourceID, DatabaseKey.errorMessage: errorMessage ] } diff --git a/Modules/ErrorLog/Sources/ErrorLog/ErrorLogNotification.swift b/Modules/ErrorLog/Sources/ErrorLog/ErrorLogNotification.swift new file mode 100644 index 000000000..296eb72b4 --- /dev/null +++ b/Modules/ErrorLog/Sources/ErrorLog/ErrorLogNotification.swift @@ -0,0 +1,22 @@ +// +// ErrorLogNotification.swift +// ErrorLog +// +// Created by Brent Simmons on 3/12/26. +// + +import Foundation + +public extension Notification.Name { + + /// Posted when any component encounters an error that should be logged. + /// UserInfo keys are defined in ErrorLogUserInfoKey. + static let appDidEncounterError = Notification.Name(rawValue: "AppDidEncounterErrorNotification") +} + +public struct ErrorLogUserInfoKey { + + public static let sourceName = "sourceName" + public static let sourceID = "sourceID" // 0-99 are AccountType raw values. 100 and greater are for other components. + public static let errorMessage = "errorMessage" +} diff --git a/Modules/Account/Sources/Account/ErrorLog/ErrorLogTable.swift b/Modules/ErrorLog/Sources/ErrorLog/ErrorLogTable.swift similarity index 64% rename from Modules/Account/Sources/Account/ErrorLog/ErrorLogTable.swift rename to Modules/ErrorLog/Sources/ErrorLog/ErrorLogTable.swift index c96f2a9fc..ca8325c10 100644 --- a/Modules/Account/Sources/Account/ErrorLog/ErrorLogTable.swift +++ b/Modules/ErrorLog/Sources/ErrorLog/ErrorLogTable.swift @@ -1,6 +1,6 @@ // // ErrorLogTable.swift -// Account +// ErrorLog // // Created by Brent Simmons on 3/11/26. // @@ -13,11 +13,11 @@ struct ErrorLogTable { static let name = "errors" - static func insertEntry(accountName: String, accountType: Int, errorMessage: String, database: FMDatabase) { + static func insertEntry(sourceName: String, sourceID: Int, errorMessage: String, database: FMDatabase) { let dictionary: DatabaseDictionary = [ ErrorLogEntry.DatabaseKey.date: Date().timeIntervalSince1970, - ErrorLogEntry.DatabaseKey.accountName: accountName, - ErrorLogEntry.DatabaseKey.accountType: accountType, + ErrorLogEntry.DatabaseKey.sourceName: sourceName, + ErrorLogEntry.DatabaseKey.sourceID: sourceID, ErrorLogEntry.DatabaseKey.errorMessage: errorMessage ] database.insertRow(dictionary, insertType: .normal, tableName: name) @@ -42,25 +42,20 @@ struct ErrorLogTable { let sql = "delete from \(name) where id not in (select id from \(name) order by id desc limit \(limit))" database.executeUpdateInTransaction(sql) } - - static func deleteAll(database: FMDatabase) { - let sql = "delete from \(name)" - database.executeUpdateInTransaction(sql) - } } private extension ErrorLogTable { static func entryWithRow(_ row: FMResultSet) -> ErrorLogEntry? { - guard let accountName = row.string(forColumn: ErrorLogEntry.DatabaseKey.accountName), + guard let sourceName = row.string(forColumn: ErrorLogEntry.DatabaseKey.sourceName), let errorMessage = row.string(forColumn: ErrorLogEntry.DatabaseKey.errorMessage) else { return nil } - let id = row.longLongInt(forColumn: ErrorLogEntry.DatabaseKey.id) + let id = Int(row.longLongInt(forColumn: ErrorLogEntry.DatabaseKey.id)) let date = Date(timeIntervalSince1970: row.double(forColumn: ErrorLogEntry.DatabaseKey.date)) - let accountType = Int(row.int(forColumn: ErrorLogEntry.DatabaseKey.accountType)) + let sourceID = Int(row.int(forColumn: ErrorLogEntry.DatabaseKey.sourceID)) - return ErrorLogEntry(id: id, date: date, accountName: accountName, accountType: accountType, errorMessage: errorMessage) + return ErrorLogEntry(id: id, date: date, sourceName: sourceName, sourceID: sourceID, errorMessage: errorMessage) } } diff --git a/Modules/ErrorLog/Tests/ErrorLogTests/ErrorLogDatabaseTests.swift b/Modules/ErrorLog/Tests/ErrorLogTests/ErrorLogDatabaseTests.swift new file mode 100644 index 000000000..59321b4b9 --- /dev/null +++ b/Modules/ErrorLog/Tests/ErrorLogTests/ErrorLogDatabaseTests.swift @@ -0,0 +1,82 @@ +// +// ErrorLogDatabaseTests.swift +// ErrorLog +// +// Created by Brent Simmons on 3/12/26. +// + +import Testing +import Foundation +@testable import ErrorLog + +@Suite(.serialized) struct ErrorLogDatabaseTests { + + private func temporaryDatabasePath() -> String { + let tempDir = NSTemporaryDirectory() + let filename = "ErrorLogTests-\(UUID().uuidString).db" + return (tempDir as NSString).appendingPathComponent(filename) + } + + private func deleteDatabaseFiles(at path: String) { + for suffix in ["", "-wal", "-shm"] { + try? FileManager.default.removeItem(atPath: path + suffix) + } + } + + @Test func addAndRetrieveEntry() async { + let path = temporaryDatabasePath() + defer { deleteDatabaseFiles(at: path) } + + let database = ErrorLogDatabase(databasePath: path) + await database.addEntry(sourceName: "TestAccount", sourceID: 1, errorMessage: "Something went wrong") + + let entries = await database.allEntries() + #expect(entries.count == 1) + + let entry = entries[0] + #expect(entry.sourceName == "TestAccount") + #expect(entry.sourceID == 1) + #expect(entry.errorMessage == "Something went wrong") + #expect(entry.id > 0) + } + + @Test func entriesReturnedInInsertionOrder() async { + let path = temporaryDatabasePath() + defer { deleteDatabaseFiles(at: path) } + + let database = ErrorLogDatabase(databasePath: path) + await database.addEntry(sourceName: "First", sourceID: 1, errorMessage: "Error 1") + await database.addEntry(sourceName: "Second", sourceID: 2, errorMessage: "Error 2") + await database.addEntry(sourceName: "Third", sourceID: 3, errorMessage: "Error 3") + + let entries = await database.allEntries() + #expect(entries.count == 3) + #expect(entries[0].sourceName == "First") + #expect(entries[1].sourceName == "Second") + #expect(entries[2].sourceName == "Third") + #expect(entries[0].id < entries[1].id) + #expect(entries[1].id < entries[2].id) + } + + @Test func pruneOnInit() async { + let path = temporaryDatabasePath() + defer { deleteDatabaseFiles(at: path) } + + let database = ErrorLogDatabase(databasePath: path) + for i in 1...210 { + await database.addEntry(sourceName: "Account", sourceID: 1, errorMessage: "Error \(i)") + } + + let entriesBeforePrune = await database.allEntries() + #expect(entriesBeforePrune.count == 210) + + // Creating a new database at the same path triggers pruning on init. + let database2 = ErrorLogDatabase(databasePath: path) + let entriesAfterPrune = await database2.allEntries() + #expect(entriesAfterPrune.count == 200) + + // Oldest entries should have been removed; newest should remain. + #expect(entriesAfterPrune[0].errorMessage == "Error 11") + #expect(entriesAfterPrune[199].errorMessage == "Error 210") + } +}