Publish VCC Plus OSS source distribution for 3.6.2 build 60
This commit is contained in:
commit
c652a5276d
1192 files changed
+272368
No files matched your search
@@ -0,0 +1,186 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
/// Recovery copies only. This store never writes to the project or guest media.
|
||||
/// Each editor session owns one file per project, so two apps cannot overwrite
|
||||
/// one another's drafts. Restore into a new session before discarding an old copy.
|
||||
final class CMOCWorkspaceRecovery: @unchecked Sendable {
|
||||
struct Draft: Codable, Equatable, Sendable {
|
||||
let path: String
|
||||
let text: String
|
||||
let savedText: String
|
||||
let savedHash: String
|
||||
init(path: String, text: String, savedText: String, savedHash: String) {
|
||||
self.path = path; self.text = text; self.savedText = savedText; self.savedHash = savedHash
|
||||
}
|
||||
}
|
||||
struct Record: Identifiable, Sendable {
|
||||
let id: UUID
|
||||
let projectPath: String
|
||||
let modifiedAt: Date
|
||||
let drafts: [Draft]
|
||||
let isFromRunningSession: Bool
|
||||
fileprivate let file: URL
|
||||
fileprivate let digest: String
|
||||
fileprivate let processID: Int32
|
||||
}
|
||||
struct Scan: Sendable {
|
||||
let records: [Record]
|
||||
let issues: [String]
|
||||
}
|
||||
private struct Envelope: Codable {
|
||||
let version: Int
|
||||
let sessionID: UUID
|
||||
let processID: Int32
|
||||
let projectPath: String
|
||||
let modifiedAt: Date
|
||||
let drafts: [Draft]
|
||||
}
|
||||
static let maximumDrafts = 128
|
||||
static let maximumTextBytes = 16 * 1024 * 1024
|
||||
static let maximumRecordBytes = 64 * 1024 * 1024
|
||||
static let maximumScanRecords = 64
|
||||
static let maximumScanTextBytes = 64 * 1024 * 1024
|
||||
let root: URL
|
||||
let sessionID: UUID
|
||||
private let processID: Int32
|
||||
private let canonicalRoot: URL
|
||||
private let lock = NSLock()
|
||||
|
||||
init(root: URL, sessionID: UUID = UUID(), processID: Int32 = getpid()) {
|
||||
self.root = root.standardizedFileURL
|
||||
self.canonicalRoot = root.standardizedFileURL.resolvingSymlinksInPath()
|
||||
self.sessionID = sessionID; self.processID = processID
|
||||
}
|
||||
private func failure(_ message: String) -> CMOCBuildError {
|
||||
.message("Draft recovery: " + message)
|
||||
}
|
||||
private func projectPath(_ directory: URL) -> String {
|
||||
directory.standardizedFileURL.resolvingSymlinksInPath().path
|
||||
}
|
||||
private func kind(_ url: URL) throws -> FileAttributeType? {
|
||||
do { return try FileManager.default.attributesOfItem(atPath: url.path)[.type] as? FileAttributeType }
|
||||
catch let error as NSError where error.domain == NSCocoaErrorDomain && [NSFileReadNoSuchFileError, NSFileNoSuchFileError].contains(error.code) { return nil }
|
||||
}
|
||||
private func folder(for project: String, create: Bool) throws -> URL? {
|
||||
guard root.resolvingSymlinksInPath().path == canonicalRoot.path else { throw failure("The recovery folder location changed. Copies were left untouched.") }
|
||||
if let type = try kind(root) {
|
||||
guard type == .typeDirectory else { throw failure("The recovery folder must be a real directory, not a link.") }
|
||||
} else if create {
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
|
||||
} else { return nil }
|
||||
let directory = root.appendingPathComponent(CMOCProject.sha256(Data(project.utf8)), isDirectory: true)
|
||||
if let type = try kind(directory) {
|
||||
guard type == .typeDirectory else { throw failure("A project recovery folder is a link or is not a directory.") }
|
||||
} else if create {
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
|
||||
} else { return nil }
|
||||
return directory
|
||||
}
|
||||
private func validate(_ drafts: [Draft]) throws {
|
||||
guard drafts.count <= Self.maximumDrafts,
|
||||
Set(drafts.map { $0.path.lowercased() }).count == drafts.count else {
|
||||
throw failure("Too many drafts or duplicate draft paths. Existing copies were kept.")
|
||||
}
|
||||
var total = 0
|
||||
for draft in drafts {
|
||||
try CMOCProject.validateRelativePath(draft.path)
|
||||
let text = try CMOCProject.sourceBytes(draft.text), saved = try CMOCProject.sourceBytes(draft.savedText)
|
||||
guard CMOCProject.sha256(saved) == draft.savedHash else { throw failure("The saved-file identity for \(draft.path) is inconsistent.") }
|
||||
total += text.count + saved.count
|
||||
guard total <= Self.maximumTextBytes else { throw failure("Drafts exceed the 16 MB recovery limit. Save your edits to the project.") }
|
||||
}
|
||||
}
|
||||
private func read(_ url: URL) throws -> Data {
|
||||
let descriptor = open(url.path, O_RDONLY | O_NOFOLLOW)
|
||||
guard descriptor >= 0 else { throw failure("Cannot safely read \(url.lastPathComponent).") }
|
||||
let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
|
||||
defer { try? handle.close() }
|
||||
var info = stat()
|
||||
guard fstat(descriptor, &info) == 0, (info.st_mode & S_IFMT) == S_IFREG,
|
||||
info.st_size >= 0, info.st_size <= Int64(Self.maximumRecordBytes) else {
|
||||
throw failure("\(url.lastPathComponent) is not a bounded regular recovery file.")
|
||||
}
|
||||
let data = try handle.read(upToCount: Self.maximumRecordBytes + 1) ?? Data()
|
||||
guard data.count <= Self.maximumRecordBytes else { throw failure("The recovery file grew beyond its size limit.") }
|
||||
return data
|
||||
}
|
||||
private func alive(_ pid: Int32) -> Bool {
|
||||
guard pid > 0 else { return false }
|
||||
return kill(pid, 0) == 0 || errno == EPERM
|
||||
}
|
||||
private func record(_ file: URL, project: String) throws -> Record {
|
||||
let data = try read(file)
|
||||
let envelope: Envelope
|
||||
do { envelope = try JSONDecoder().decode(Envelope.self, from: data) }
|
||||
catch { throw failure("\(file.lastPathComponent) is damaged or has an unsupported structure. The file was kept.") }
|
||||
guard envelope.version == 1, envelope.processID > 0, envelope.projectPath == project,
|
||||
file.lastPathComponent == envelope.sessionID.uuidString + ".json",
|
||||
envelope.modifiedAt.timeIntervalSince1970.isFinite else {
|
||||
throw failure("\(file.lastPathComponent) has an invalid recovery identity. The file was kept.")
|
||||
}
|
||||
try validate(envelope.drafts)
|
||||
return Record(id: envelope.sessionID, projectPath: project, modifiedAt: envelope.modifiedAt,
|
||||
drafts: envelope.drafts, isFromRunningSession: envelope.sessionID != sessionID && alive(envelope.processID),
|
||||
file: file, digest: CMOCProject.sha256(data), processID: envelope.processID)
|
||||
}
|
||||
func save(projectDirectory: URL, drafts: [Draft]) throws {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
try validate(drafts)
|
||||
let project = projectPath(projectDirectory)
|
||||
guard let directory = try folder(for: project, create: !drafts.isEmpty) else { return }
|
||||
let file = directory.appendingPathComponent(sessionID.uuidString + ".json")
|
||||
if let type = try kind(file), type != .typeRegular { throw failure("The session recovery file is not a regular file. It was kept.") }
|
||||
if drafts.isEmpty {
|
||||
if try kind(file) != nil { try FileManager.default.removeItem(at: file) }
|
||||
return
|
||||
}
|
||||
let envelope = Envelope(version: 1, sessionID: sessionID, processID: processID, projectPath: project,
|
||||
modifiedAt: Date(), drafts: drafts)
|
||||
let data = try JSONEncoder().encode(envelope)
|
||||
guard data.count <= Self.maximumRecordBytes else { throw failure("The encoded recovery copy exceeds its size limit. Existing copies were kept.") }
|
||||
try data.write(to: file, options: .atomic)
|
||||
}
|
||||
func scan(projectDirectory: URL) throws -> Scan {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
let project = projectPath(projectDirectory)
|
||||
guard let directory = try folder(for: project, create: false) else { return Scan(records: [], issues: []) }
|
||||
let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)
|
||||
guard files.count <= 1024 else { throw failure("Too many recovery files to inspect safely. Copies were left untouched.") }
|
||||
var records: [Record] = [], issues: [String] = []
|
||||
var totalTextBytes = 0
|
||||
for file in files.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) where file.pathExtension == "json" {
|
||||
guard records.count < Self.maximumScanRecords else {
|
||||
issues.append("Draft recovery: More than 64 saved sessions are present. Export or discard reviewed copies, then refresh to inspect the remaining sessions. All copies were kept.")
|
||||
break
|
||||
}
|
||||
do {
|
||||
let recovered = try record(file, project: project)
|
||||
let bytes = recovered.drafts.reduce(0) { $0 + $1.text.utf8.count + $1.savedText.utf8.count }
|
||||
guard totalTextBytes + bytes <= Self.maximumScanTextBytes else {
|
||||
issues.append("Draft recovery: Saved sessions exceed the 64 MB review limit. Export or discard reviewed copies, then refresh to inspect the remaining sessions. All copies were kept.")
|
||||
break
|
||||
}
|
||||
totalTextBytes += bytes; records.append(recovered)
|
||||
} catch { issues.append(error.localizedDescription) }
|
||||
}
|
||||
return Scan(records: records.sorted { $0.modifiedAt > $1.modifiedAt }, issues: issues)
|
||||
}
|
||||
func records(projectDirectory: URL) throws -> [Record] {
|
||||
let result = try scan(projectDirectory: projectDirectory)
|
||||
guard result.issues.isEmpty else { throw failure(result.issues.joined(separator: "\n")) }
|
||||
return result.records
|
||||
}
|
||||
func discard(_ record: Record) throws {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
guard let directory = try folder(for: record.projectPath, create: false),
|
||||
directory.appendingPathComponent(record.id.uuidString + ".json").resolvingSymlinksInPath().path == record.file.resolvingSymlinksInPath().path else {
|
||||
throw failure("The recovery record no longer belongs to this store.")
|
||||
}
|
||||
let current = try self.record(record.file, project: record.projectPath)
|
||||
guard current.digest == record.digest else { throw failure("This recovery copy changed after it was shown. Review it again before discarding.") }
|
||||
guard !current.isFromRunningSession else { throw failure("Another running editor session owns this recovery copy.") }
|
||||
try FileManager.default.removeItem(at: record.file)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user