fix(file-provider): roll back cancelled parent lookup writes
Pass live cancellation state through the parent lookup. Check it before saving retrieved metadata and again before committing it. Use the async writer so a cancelled Swift task can also stop while waiting for the database. Cover cancellation before persistence and after insertion. Assisted-by: Codex:GPT-6 Signed-off-by: Claudio Cambra <[email protected]>
This commit is contained in:
8 files changed
+133
-42
No files matched your search
+34
-12
@@ -244,18 +244,22 @@ public final class FilesDatabaseManager: Sendable {
|
||||
///
|
||||
func write<T>(durability: WriteDurability, _ body: (Database) throws -> T) throws -> T {
|
||||
try writer.writeWithoutTransaction { db in
|
||||
try db.execute(sql: durability.pragma)
|
||||
|
||||
var result: T?
|
||||
try db.inTransaction {
|
||||
result = try body(db)
|
||||
return .commit
|
||||
}
|
||||
|
||||
return result!
|
||||
try writeTransaction(in: db, durability: durability, body)
|
||||
}
|
||||
}
|
||||
|
||||
private func writeTransaction<T>(in db: Database, durability: WriteDurability, _ body: (Database) throws -> T) throws -> T {
|
||||
try db.execute(sql: durability.pragma)
|
||||
|
||||
var result: T?
|
||||
try db.inTransaction {
|
||||
result = try body(db)
|
||||
return .commit
|
||||
}
|
||||
|
||||
return result!
|
||||
}
|
||||
|
||||
/// Checkpoint the write-ahead log so the file is complete on disk before the process goes away.
|
||||
public func checkpointForShutdown() {
|
||||
do {
|
||||
@@ -784,6 +788,22 @@ public final class FilesDatabaseManager: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Save the item metadata returned by the server. Roll back the write if cancellation is detected before commit.
|
||||
func addItemMetadataFromRemoteRead(
|
||||
_ metadata: SendableItemMetadata,
|
||||
isCancelled: @Sendable @escaping () -> Bool
|
||||
) async throws {
|
||||
// GRDB's async writer handles Swift task cancellation while waiting for the writer.
|
||||
try await writer.writeWithoutTransaction { db in
|
||||
try self.writeTransaction(in: db, durability: .full) { db in
|
||||
guard !isCancelled() else { throw CancellationError() }
|
||||
try self.insertItemMetadata(metadata, in: db)
|
||||
// Progress can be cancelled before its handler cancels the Swift task.
|
||||
guard !isCancelled() else { throw CancellationError() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the given `downloaded` and `visitedDirectory` values of several rows in one write transaction, leaving every other column and every missing row untouched; a failure discards the whole batch.
|
||||
///
|
||||
/// - Parameter durability: ``WriteDurability/full`` unless the flags only mirror the system's materialized set, which the next reconciliation pass rebuilds.
|
||||
@@ -1048,9 +1068,10 @@ public final class FilesDatabaseManager: Sendable {
|
||||
fromMetadata metadata: SendableItemMetadata,
|
||||
remoteInterface: RemoteInterface,
|
||||
account: Account,
|
||||
taskHandler: @Sendable @escaping (URLSessionTask) -> Void = { _ in }
|
||||
taskHandler: @Sendable @escaping (URLSessionTask) -> Void = { _ in },
|
||||
isCancelled: @Sendable @escaping () -> Bool = { false }
|
||||
) async -> NSFileProviderItemIdentifier? {
|
||||
guard !Task.isCancelled else { return nil }
|
||||
guard !Task.isCancelled, !isCancelled() else { return nil }
|
||||
if let parentItemIdentifier = parentItemIdentifierFromMetadata(metadata) {
|
||||
return parentItemIdentifier
|
||||
}
|
||||
@@ -1062,10 +1083,11 @@ public final class FilesDatabaseManager: Sendable {
|
||||
dbManager: self,
|
||||
depth: .target,
|
||||
taskHandler: taskHandler,
|
||||
isCancelled: isCancelled,
|
||||
log: logger.log
|
||||
)
|
||||
|
||||
guard !Task.isCancelled else { return nil }
|
||||
guard !Task.isCancelled, !isCancelled() else { return nil }
|
||||
|
||||
guard readResult.error == nil, let parentMetadata = readResult.metadatas?.first else {
|
||||
logger.error("Could not retrieve parent item identifier remotely.", [
|
||||
|
||||
+19
-18
@@ -206,9 +206,10 @@ extension Enumerator {
|
||||
expectedDirectoryOcId: String? = nil,
|
||||
depth: EnumerateDepth = .targetAndDirectChildren,
|
||||
taskHandler: @Sendable @escaping (URLSessionTask) -> Void = { _ in },
|
||||
isCancelled: @Sendable @escaping () -> Bool = { false },
|
||||
log: any FileProviderLogging
|
||||
) async -> RemoteReadResult {
|
||||
guard !Task.isCancelled else { return RemoteReadResult(error: .cancelled) }
|
||||
guard !Task.isCancelled, !isCancelled() else { return RemoteReadResult(error: .cancelled) }
|
||||
let logger = FileProviderLogger(category: "Enumerator", log: log)
|
||||
|
||||
logger.debug("Starting to read server URL.", [.url: serverUrl])
|
||||
@@ -275,7 +276,7 @@ extension Enumerator {
|
||||
return RemoteReadResult(error: error)
|
||||
}
|
||||
|
||||
guard !Task.isCancelled else { return RemoteReadResult(error: .cancelled) }
|
||||
guard !Task.isCancelled, !isCancelled() else { return RemoteReadResult(error: .cancelled) }
|
||||
if let expectedDirectoryOcId {
|
||||
// A path may now refer to a different item from the one this download owns.
|
||||
let target = files.first { files.isDirectoryToRead($0, directoryToRead: serverUrl) }?.toItemMetadata()
|
||||
@@ -296,6 +297,18 @@ extension Enumerator {
|
||||
return RemoteReadResult(metadatas: [], nextPage: nextPage)
|
||||
}
|
||||
|
||||
func finishTargetRead(_ metadata: SendableItemMetadata, changes: ChangeSet) async -> RemoteReadResult {
|
||||
do {
|
||||
try await dbManager.addItemMetadataFromRemoteRead(metadata, isCancelled: isCancelled)
|
||||
} catch is CancellationError {
|
||||
return RemoteReadResult(error: .cancelled)
|
||||
} catch {
|
||||
// A single-item lookup can still return the server result if caching fails.
|
||||
logger.error("Could not persist remote item metadata.", [.item: metadata.ocId, .error: error])
|
||||
}
|
||||
return RemoteReadResult(metadatas: [metadata], changes: changes, nextPage: nextPage)
|
||||
}
|
||||
|
||||
// Generally speaking a PROPFIND will provide the target of the PROPFIND as the first result
|
||||
// That is NOT the case for paginated results with offsets
|
||||
let isFollowUpPaginatedRequest = (pageSettings?.page != nil && pageSettings?.index ?? 0 > 0)
|
||||
@@ -308,7 +321,7 @@ extension Enumerator {
|
||||
logger.debug("Read item is a file, converting.", [.url: serverUrl])
|
||||
let received = receivedFile.toItemMetadata()
|
||||
|
||||
// Read, merge and write in one hop off the cooperative pool: see `FilesDatabaseManager.perform(_:)`.
|
||||
// Read and merge off the cooperative pool: see `FilesDatabaseManager.perform(_:)`.
|
||||
let (metadata, newItems, updatedItems) = await dbManager.perform {
|
||||
dbManager -> (SendableItemMetadata, [SendableItemMetadata], [SendableItemMetadata]) in
|
||||
var metadata = received
|
||||
@@ -330,23 +343,17 @@ extension Enumerator {
|
||||
metadata.keepDownloaded = dbManager.inheritedKeepDownloaded(for: metadata)
|
||||
}
|
||||
|
||||
dbManager.addItemMetadata(metadata)
|
||||
|
||||
return (metadata, newItems, updatedItems)
|
||||
}
|
||||
|
||||
return RemoteReadResult(
|
||||
metadatas: [metadata],
|
||||
changes: ChangeSet(created: newItems, updated: updatedItems),
|
||||
nextPage: nextPage
|
||||
)
|
||||
return await finishTargetRead(metadata, changes: ChangeSet(created: newItems, updated: updatedItems))
|
||||
}
|
||||
}
|
||||
|
||||
if depth == .target {
|
||||
let received = receivedFile.toItemMetadata()
|
||||
|
||||
// Read, merge and write in one hop off the cooperative pool: see
|
||||
// Read and merge off the cooperative pool: see
|
||||
// `FilesDatabaseManager.perform(_:)`.
|
||||
let (metadata, newMetadatas, updatedMetadatas) = await dbManager.perform {
|
||||
dbManager -> (SendableItemMetadata, [SendableItemMetadata], [SendableItemMetadata]) in
|
||||
@@ -368,16 +375,10 @@ extension Enumerator {
|
||||
metadata.keepDownloaded = dbManager.inheritedKeepDownloaded(for: metadata)
|
||||
}
|
||||
|
||||
dbManager.addItemMetadata(metadata)
|
||||
|
||||
return (metadata, newMetadatas, updatedMetadatas)
|
||||
}
|
||||
|
||||
return RemoteReadResult(
|
||||
metadatas: [metadata],
|
||||
changes: ChangeSet(created: newMetadatas, updated: updatedMetadatas),
|
||||
nextPage: nextPage
|
||||
)
|
||||
return await finishTargetRead(metadata, changes: ChangeSet(created: newMetadatas, updated: updatedMetadatas))
|
||||
} else if depth == .targetAndDirectChildren {
|
||||
let depth1Read = await handleDepth1ReadFileOrFolder(
|
||||
serverUrl: serverUrl,
|
||||
|
||||
+1
@@ -294,6 +294,7 @@ import OSLog
|
||||
remoteInterface: ncKit,
|
||||
dbManager: dbManager,
|
||||
taskHandler: { cancellation.register(task: $0) },
|
||||
isCancelled: { cancellation.isCancelled },
|
||||
log: log
|
||||
)
|
||||
guard !progress.isCancelled, !Task.isCancelled else {
|
||||
|
||||
+2
-1
@@ -350,7 +350,8 @@ public extension Item {
|
||||
fromMetadata: updatedMetadata,
|
||||
remoteInterface: remoteInterface,
|
||||
account: account,
|
||||
taskHandler: { cancellation.register(task: $0) }
|
||||
taskHandler: { cancellation.register(task: $0) },
|
||||
isCancelled: { cancellation.isCancelled }
|
||||
)
|
||||
guard !progress.isCancelled, !Task.isCancelled else {
|
||||
return (nil, nil, operation.error(for: CocoaError(.userCancelled)))
|
||||
|
||||
+7
-5
@@ -493,13 +493,14 @@ public final class Item: NSObject, NSFileProviderItem, Sendable {
|
||||
remoteInterface: RemoteInterface,
|
||||
dbManager: FilesDatabaseManager,
|
||||
taskHandler: @Sendable @escaping (URLSessionTask) -> Void = { _ in },
|
||||
isCancelled: @Sendable @escaping () -> Bool = { false },
|
||||
log: any FileProviderLogging
|
||||
) async -> Item? {
|
||||
// resolve the given identifier to a record in the model
|
||||
|
||||
guard !Task.isCancelled else { return nil }
|
||||
guard !Task.isCancelled, !isCancelled() else { return nil }
|
||||
let remoteSupportsTrash = await remoteInterface.supportsTrash(account: account)
|
||||
guard !Task.isCancelled else { return nil }
|
||||
guard !Task.isCancelled, !isCancelled() else { return nil }
|
||||
|
||||
guard identifier != .rootContainer else {
|
||||
return Item.rootContainer(
|
||||
@@ -531,11 +532,12 @@ public final class Item: NSObject, NSFileProviderItem, Sendable {
|
||||
fromMetadata: metadata,
|
||||
remoteInterface: remoteInterface,
|
||||
account: account,
|
||||
taskHandler: taskHandler
|
||||
taskHandler: taskHandler,
|
||||
isCancelled: isCancelled
|
||||
)
|
||||
}
|
||||
|
||||
guard !Task.isCancelled, let parentItemIdentifier else {
|
||||
guard !Task.isCancelled, !isCancelled(), let parentItemIdentifier else {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -543,7 +545,7 @@ public final class Item: NSObject, NSFileProviderItem, Sendable {
|
||||
|
||||
let displayFileActions = await Item.typeHasApplicableContextMenuItems(account: account, remoteInterface: remoteInterface, candidate: metadata.contentType)
|
||||
|
||||
guard !Task.isCancelled else { return nil }
|
||||
guard !Task.isCancelled, !isCancelled() else { return nil }
|
||||
|
||||
return Item(
|
||||
metadata: metadata,
|
||||
|
||||
+1
@@ -51,6 +51,7 @@ public func fetchThumbnails(
|
||||
remoteInterface: remoteInterface,
|
||||
dbManager: dbManager,
|
||||
taskHandler: { cancellation.register(task: $0) },
|
||||
isCancelled: { progress.isCancelled || cancellation.isCancelled },
|
||||
log: logger.log
|
||||
)
|
||||
guard !progress.isCancelled, !Task.isCancelled else {
|
||||
|
||||
+45
-6
@@ -2641,10 +2641,11 @@ final class ItemFetchTests: NextcloudFileProviderKitTestCase {
|
||||
let progress = Progress()
|
||||
let session = URLSession(configuration: .ephemeral)
|
||||
defer { session.invalidateAndCancel() }
|
||||
let (networkTask, networkCompletion) = try observedNetworkTask(
|
||||
in: session,
|
||||
url: XCTUnwrap(URL(string: "https://example.invalid/parent"))
|
||||
)
|
||||
let networkCancelled = DispatchSemaphore(value: 0)
|
||||
let networkTask = try session.dataTask(with: XCTUnwrap(URL(string: "https://example.invalid/parent"))) { _, _, error in
|
||||
XCTAssertEqual((error as? URLError)?.code, .cancelled)
|
||||
networkCancelled.signal()
|
||||
}
|
||||
defer { removeDownloadedContents(remoteInterface: remoteInterface) }
|
||||
remoteInterface.enumerateCallHandler = { path, depth, _, _, _, _, _, taskHandler in
|
||||
XCTAssertEqual(path, directory.remotePath)
|
||||
@@ -2652,6 +2653,8 @@ final class ItemFetchTests: NextcloudFileProviderKitTestCase {
|
||||
XCTAssertEqual(remoteInterface.downloadDestinationURL.map { FileManager.default.fileExists(atPath: $0.path) }, true)
|
||||
taskHandler(networkTask)
|
||||
progress.cancel()
|
||||
// Keep the lookup pending until the registered request observes cancellation.
|
||||
XCTAssertEqual(networkCancelled.wait(timeout: .now() + .seconds(Int(asyncTestTimeout.components.seconds))), .success)
|
||||
}
|
||||
|
||||
let (url, fetchedItem, error) = await item.fetchContents(progress: progress, dbManager: Self.dbManager)
|
||||
@@ -2659,8 +2662,6 @@ final class ItemFetchTests: NextcloudFileProviderKitTestCase {
|
||||
XCTAssertNil(url)
|
||||
XCTAssertNil(fetchedItem)
|
||||
XCTAssertEqual((error as? CocoaError)?.code, .userCancelled)
|
||||
let networkError = try await nextTestValue(from: networkCompletion)
|
||||
XCTAssertEqual(networkError, NSURLErrorCancelled)
|
||||
XCTAssertEqual(remoteInterface.readOperationCount, 1)
|
||||
XCTAssertNil(Self.dbManager.itemMetadata(ocId: directory.identifier))
|
||||
XCTAssertEqual(Self.dbManager.itemMetadata(ocId: item.itemIdentifier.rawValue)?.downloaded, false)
|
||||
@@ -2670,6 +2671,44 @@ final class ItemFetchTests: NextcloudFileProviderKitTestCase {
|
||||
XCTAssertEqual(remoteInterface.downloadDestinationURL.map { FileManager.default.fileExists(atPath: $0.path) }, false)
|
||||
}
|
||||
|
||||
func testCancelledParentLookupLeavesMetadataUnchanged() async throws {
|
||||
for cancelDuringWrite in [false, true] {
|
||||
let (item, remoteInterface, directory) = makeNestedFetchItem()
|
||||
let dbManager = Self.dbManager
|
||||
let progress = Progress()
|
||||
let parentId = directory.identifier
|
||||
remoteInterface.enumerateCallHandler = { path, depth, _, _, _, _, _, _ in
|
||||
XCTAssertEqual(path, directory.remotePath)
|
||||
XCTAssertEqual(depth, .target)
|
||||
// Model Progress cancellation before its handler reaches the Swift task.
|
||||
progress.cancellationHandler = nil
|
||||
if !cancelDuringWrite {
|
||||
progress.cancel()
|
||||
}
|
||||
}
|
||||
if cancelDuringWrite {
|
||||
try dbManager.setItemMetadataInsertionHandlerForTesting(ocId: parentId) { progress.cancel() }
|
||||
}
|
||||
defer {
|
||||
if cancelDuringWrite {
|
||||
try? dbManager.setItemMetadataInsertionHandlerForTesting(ocId: parentId, nil)
|
||||
}
|
||||
removeDownloadedContents(remoteInterface: remoteInterface)
|
||||
}
|
||||
|
||||
let (url, fetchedItem, error) = await item.fetchContents(progress: progress, dbManager: dbManager)
|
||||
|
||||
XCTAssertTrue(progress.isCancelled)
|
||||
XCTAssertEqual(remoteInterface.readOperationCount, 1)
|
||||
XCTAssertNil(url)
|
||||
XCTAssertNil(fetchedItem)
|
||||
XCTAssertEqual((error as? CocoaError)?.code, .userCancelled)
|
||||
XCTAssertNil(dbManager.itemMetadata(ocId: parentId))
|
||||
let temporaryFile = try XCTUnwrap(remoteInterface.downloadDestinationURL)
|
||||
XCTAssertFalse(FileManager.default.fileExists(atPath: temporaryFile.path))
|
||||
}
|
||||
}
|
||||
|
||||
func testCancellingThumbnailPreparationCancelsParentTask() async throws {
|
||||
let (item, remoteInterface, directory) = makeNestedFetchItem()
|
||||
let session = URLSession(configuration: .ephemeral)
|
||||
|
||||
+24
@@ -153,6 +153,30 @@ extension FilesDatabaseManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the handler after inserting a specific item, before the transaction commits.
|
||||
func setItemMetadataInsertionHandlerForTesting(ocId: String, _ handler: (@Sendable () -> Void)?) throws {
|
||||
let function = DatabaseFunction("on_item_metadata_insert", argumentCount: 0) { _ in
|
||||
handler?()
|
||||
return nil
|
||||
}
|
||||
try writer.write { db in
|
||||
if handler != nil {
|
||||
let identifier = ocId.replacingOccurrences(of: "'", with: "''")
|
||||
db.add(function: function)
|
||||
try db.execute(sql: """
|
||||
CREATE TEMP TRIGGER on_item_metadata_insert AFTER INSERT ON itemMetadata
|
||||
WHEN NEW.ocId = '\(identifier)'
|
||||
BEGIN
|
||||
SELECT on_item_metadata_insert();
|
||||
END
|
||||
""")
|
||||
} else {
|
||||
try db.execute(sql: "DROP TRIGGER IF EXISTS on_item_metadata_insert")
|
||||
db.remove(function: function)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reject publishing a completed download while allowing its start and cleanup writes.
|
||||
func setDownloadCompletionWriteFailureForTesting(_ enabled: Bool, ocId: String) throws {
|
||||
try writer.write { db in
|
||||
|
||||
Reference in new issue
Block a user