Skip to content
Closed
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
19 changes: 14 additions & 5 deletions Packages/PeerCore/Sources/PeerCore/SourceJobs.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ import Foundation
import PostgresNIO

public struct SourceJob: Sendable {
public enum TerminalStatus: String, Sendable {
case finished, failed, aborted
case timedOut = "timed_out"
}

public let id: Int
public let deadline: Date
}
Expand All @@ -22,9 +27,6 @@ public enum SourceJobs {
}

public static func pending(source: Int, on client: PostgresConnection) async throws -> [Int] {
try await client.query(
"UPDATE inkcre.jobs SET status='timed_out' WHERE type=\(type) AND status='running' AND parameters->'source'=to_jsonb(\(source)::bigint) AND started_at + timeout_seconds * interval '1 second' < now()",
logger: PeerDatabase.logger)
try await client.query(
"UPDATE inkcre.jobs SET status='aborted' WHERE type=\(type) AND status='pending' AND abort_requested AND parameters->'source'=to_jsonb(\(source)::bigint)",
logger: PeerDatabase.logger)
Expand Down Expand Up @@ -69,11 +71,18 @@ public enum SourceJobs {
public static func close(
_ job: SourceJob, status: String, state: String, on client: PostgresConnection
) async throws {
guard ["finished", "failed", "timed_out", "aborted"].contains(status) else {
guard let status = SourceJob.TerminalStatus(rawValue: status) else {
throw PeerError.invalid("无效的任务终态。")
}
try await close(job, status: status, state: state, on: client)
}

public static func close(
_ job: SourceJob, status: SourceJob.TerminalStatus, state: String,
on client: PostgresConnection
) async throws {
try await client.query(
"UPDATE inkcre.jobs SET status=\(status)::inkcre.jobstatus,state=\(state)::jsonb WHERE id=\(job.id) AND status='running'",
"UPDATE inkcre.jobs SET status=\(status.rawValue)::inkcre.jobstatus,state=\(state)::jsonb WHERE id=\(job.id) AND status='running'",
logger: PeerDatabase.logger)
}
}
134 changes: 134 additions & 0 deletions Tests/LocalFilesTests/SourceJobOwnershipTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import Foundation
import LocalFiles
import PeerCore
import Testing

@Suite(.enabled(if: ProcessInfo.processInfo.environment["INKCRE_FILES_TEST_DATABASE"] != nil))
struct SourceJobOwnershipTests {
enum Completion: CaseIterable {
case finished, cancelled, remoteAbort, expired

var status: String {
switch self {
case .finished: "finished"
case .cancelled, .remoteAbort: "aborted"
case .expired: "timed_out"
}
}
}

@Test(arguments: Completion.allCases)
func onlyTheExecutorClosesAfterTheScanExits(_ completion: Completion) async throws {
let env = ProcessInfo.processInfo.environment
let target = ConnectionTarget(
host: "127.0.0.1", port: Int(env["INKCRE_FILES_TEST_PORT"] ?? "55483")!,
database: try #require(env["INKCRE_FILES_TEST_DATABASE"]), username: "inkcre_core",
tls: .disable)
let observerTarget = ConnectionTarget(
host: target.host, port: target.port, database: target.database,
username: target.username, tls: target.tls)
let password = try #require(env["INKCRE_FILES_TEST_PASSWORD"])
let owner = PeerDatabase()
let observer = PeerDatabase()
let repository = LocalFilesRepository(target: target, password: password, database: owner)
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(
UUID().uuidString)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directory) }
try Data("Synthetic file".utf8).write(to: directory.appendingPathComponent("note.txt"))
try await repository.prepare()
let source = try await repository.createDirectory(path: directory.path)
let jobID = try await repository.submitScan(source)
let pool = try await observer.client(for: observerTarget, password: password)
if completion == .expired {
try await pool.query("UPDATE inkcre.jobs SET timeout_seconds=5 WHERE id=\(jobID)")
}

let (entered, enteredSignal) = AsyncStream<Void>.makeStream()
let (cancelled, cancelledSignal) = AsyncStream<Void>.makeStream()
let (released, releaseSignal) = AsyncStream<Void>.makeStream()
let pending = try await repository.pendingScans(source)
let execution = Task {
try await DirectoryScanner.run(
source: source, repository: repository, pendingJobs: pending
) {
_ in
await withTaskCancellationHandler {
enteredSignal.yield()
// Model a file operation that must finish even after cancellation is delivered.
await Task {
for await _ in released { break }
}.value
} onCancel: {
cancelledSignal.yield()
}
}
}
defer {
releaseSignal.finish()
execution.cancel()
}
try await waitForSignal(entered)
switch completion {
case .finished: break
case .cancelled:
execution.cancel()
try await waitForSignal(cancelled)
case .remoteAbort:
try await pool.query("UPDATE inkcre.jobs SET abort_requested=true WHERE id=\(jobID)")
case .expired:
try await waitForSignal(cancelled)
}

// Discovery uses a distinct database session while the owner is blocked in the scan.
let pendingAbort = try await repository.submitScan(source)
try await pool.query("UPDATE inkcre.jobs SET abort_requested=true WHERE id=\(pendingAbort)")
let found = try await observer.withConnection(for: observerTarget, password: password) {
connection in
try await SourceJobs.pending(source: source.id, on: connection)
}
#expect(found.isEmpty)
let active = try await pool.query(
"SELECT status::text,closed_at IS NULL FROM inkcre.jobs WHERE id=\(jobID)"
)
.decode((String, Bool).self).first { _ in true }
#expect(active?.0 == "running" && active?.1 == true)
let pendingStatus = try await pool.query(
"SELECT status::text FROM inkcre.jobs WHERE id=\(pendingAbort)"
)
.decode(String.self).first { _ in true }
#expect(pendingStatus == "aborted")

releaseSignal.finish()
switch completion {
case .finished:
#expect(try await execution.value.errors == 0)
case .cancelled, .remoteAbort:
await #expect(throws: CancellationError.self) { try await execution.value }
case .expired:
await #expect(throws: PeerError.self) { try await execution.value }
}
let terminal = try await pool.query(
"SELECT status::text,closed_at IS NOT NULL FROM inkcre.jobs WHERE id=\(jobID)"
)
.decode((String, Bool).self).first { _ in true }
#expect(terminal?.0 == completion.status && terminal?.1 == true)

await owner.shutdown()
await observer.shutdown()
}

private func waitForSignal(_ signal: AsyncStream<Void>) async throws {
try await withThrowingTaskGroup(of: Void.self) { group in
group.addTask {
for await _ in signal { return }
}
group.addTask {
try await Task.sleep(for: .seconds(10))
throw PeerError.needsAction("等待扫描的测试信号超时。")
}
defer { group.cancelAll() }
try await group.next()
}
}
}
67 changes: 67 additions & 0 deletions extensions/local-files/Sources/LocalFiles/DirectoryScanner.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,77 @@ public struct ScanProgress: Sendable {
}

public enum DirectoryScanner {
/// The caller must await the scan, including publication of any claimed Job's outcome.
public static func run(
source: DirectorySource, repository: LocalFilesRepository, pendingJobs: [Int],
progress: @escaping @Sendable (ScanProgress) async -> Void = { _ in }
) async throws -> DirectoryState {
for id in pendingJobs {
try Task.checkCancellation()
// Keep the claim receipt if cancellation races with the claim transaction's commit.
let claimed = try await Task { try await repository.claim(id, source: source) }.value
if let claimed {
return try await run(
claimed, source: source, repository: repository, progress: progress)
}
}
return try await scan(source: source, repository: repository, progress: progress)
}

private static func run(
_ job: SourceJob, source: DirectorySource, repository: LocalFilesRepository,
progress: @escaping @Sendable (ScanProgress) async -> Void
) async throws -> DirectoryState {
let timeout = PeerError.needsAction("扫描已超时。")
let (status, result): (SourceJob.TerminalStatus, Result<DirectoryState, any Error>) =
await withThrowingTaskGroup(of: DirectoryState.self) { group in
group.addTask {
let state = try await scan(
source: source, repository: repository, job: job, progress: progress)
try Task.checkCancellation()
if Date() >= job.deadline { throw timeout }
return state
}
group.addTask {
try await Task.sleep(for: .seconds(job.deadline.timeIntervalSinceNow))
throw timeout
}
defer { group.cancelAll() }
do {
let state = try await group.next()!
return (state.errors == 0 ? .finished : .failed, .success(state))
} catch {
// Decide when stop is observed. Unwinding may itself outlast the budget.
if Date() >= job.deadline { return (.timedOut, .failure(timeout)) }
if PeerDatabase.isCancellation(error) { return (.aborted, .failure(error)) }
return (.failed, .failure(error))
}
}

let state: DirectoryState
switch result {
case .success(let scanned):
state = scanned
case .failure(let error):
state = DirectoryState(
issue: status == .aborted
? "扫描已停止" : PeerDatabase.failure(error).localizedDescription)
}
// The task group has drained the scan. Publish from a fresh task and database lease.
do {
try await Task { try await repository.close(job, status: status, state: state) }.value
} catch {
let message = state.issue.map { "\($0);" } ?? ""
throw PeerError.connection("\(message)任务 \(job.id) 终态待信息库核对。")
}
return try result.get()
}

public static func scan(
source: DirectorySource, repository: LocalFilesRepository, job: SourceJob? = nil,
progress: @escaping @Sendable (ScanProgress) async -> Void = { _ in }
) async throws -> DirectoryState {
try Task.checkCancellation()
let root = URL(fileURLWithPath: source.config.path, isDirectory: true)
let identity: String
let files: [URL]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ extension LocalFilesRepository {
}

public func close(_ job: SourceJob, status: String, state: DirectoryState) async throws {
guard let status = SourceJob.TerminalStatus(rawValue: status) else {
throw PeerError.invalid("无效的任务终态。")
}
try await close(job, status: status, state: state)
}

func close(_ job: SourceJob, status: SourceJob.TerminalStatus, state: DirectoryState)
async throws
{
return try await database.withConnection(for: target, credentials: credentials) { client in
try await SourceJobs.close(
job, status: status, state: FileJSON.encode(state), on: client)
Expand Down
31 changes: 3 additions & 28 deletions extensions/local-files/Sources/LocalFilesMac/LocalFilesModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,6 @@ public final class LocalFilesModel: ObservableObject {
monitor.dirty = false
scanning.insert(id)
statuses[id] = "正在扫描…"
var job: SourceJob?
let repository: LocalFilesRepository
do { repository = try await self.repository(monitor.target) } catch {
statuses[id] = error.localizedDescription
Expand All @@ -314,23 +313,11 @@ public final class LocalFilesModel: ObservableObject {
}
do {
let pending = try await repository.pendingScans(monitor.source)
for candidate in pending {
if let claimed = try await repository.claim(
candidate, source: monitor.source)
{
job = claimed
break
}
}
let state = try await DirectoryScanner.scan(
source: monitor.source, repository: repository, job: job
let state = try await DirectoryScanner.run(
source: monitor.source, repository: repository, pendingJobs: pending
) { [weak self] progress in
await self?.report(progress, id: id)
}
if let job {
try await repository.close(
job, status: state.errors == 0 ? "finished" : "failed", state: state)
}
statuses[id] = state.errors == 0 ? "正在监视" : "\(state.errors) 个文件需要处理"
let updated = try await repository.sources()
if target?.peerID == monitor.source.config.peer, running, !Task.isCancelled {
Expand All @@ -345,25 +332,13 @@ public final class LocalFilesModel: ObservableObject {
PeerDatabase.isCancellation(error)
? "扫描已停止" : PeerDatabase.failure(error).localizedDescription
statuses[id] = message
if !PeerDatabase.isCancellation(error), running {
if !Task.isCancelled, !PeerDatabase.isCancellation(error), running {
do {
try await repository.reportIssue(message, source: monitor.source)
} catch {
statuses[id] = "\(message);状态暂未写回信息库"
}
}
if let job, !Task.isCancelled, running {
let status =
Date() >= job.deadline
? "timed_out"
: PeerDatabase.isCancellation(error) ? "aborted" : "failed"
do {
try await repository.close(
job, status: status, state: DirectoryState(issue: message))
} catch {
statuses[id] = "\(message);任务终态待信息库核对"
}
}
// Reconnection reconciles current files, without an outbox.
monitor.dirty = true
break
Expand Down
Loading