Files
element-x-ios/ElementX/Sources/Other/Logging/Tracing.swift
T
Mauro a520d94760 Swift 6 Migration (#5733)
* Enable Swift 6.2 with default main actor isolation for the app target

Turn on SWIFT_VERSION 6.2, SWIFT_APPROACHABLE_CONCURRENCY and SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor for the ElementX target, matching the NSE and Share Extension (which already use 6.2 without the main actor default).

# Conflicts:
#	ElementX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved

* Update the code generation templates for Swift 6

Emit nonisolated/@unchecked Sendable mocks and nonisolated string enums, and mark async mock methods @concurrent so they keep suspending like the real implementations (otherwise intermediate states are unobservable in tests). Includes the regenerated mocks and strings.

# Conflicts:
#	ElementX/Sources/Mocks/Generated/GeneratedMocks.swift

* Make the data layer and services nonisolated and Sendable

Annotate the value-type models, Rust SDK proxy wrappers, timeline item graph, settings, logging and NSE-shared types as nonisolated, and conform the service protocols to Sendable so their existentials can cross isolation boundaries. These types run off the main actor and no longer inherit the target's default main actor isolation.

* Adopt the new isolation across call sites, mocks and signatures

Update call sites, closure signatures and mock configuration helpers to match the nonisolated/Sendable data layer, including the main actor isolated mock inits and the @Sendable filter on recentlyVisitedRooms.

^ Conflicts:
^	ElementX/Sources/Services/SecureBackup/SecureBackupController.swift

* Remove redundant @MainActor annotations

With the app target defaulting to main actor isolation, the explicit @MainActor on view models, coordinators, views and their protocols is no longer required.

* Fix concurrency hotspots surfaced by the migration

Resolve the room summary main-thread deadlock by moving diff processing onto AsyncStreams, add the SDKListener.onMainActor FIFO bridge for SDK callbacks, hop KVO/timer/UIKit callbacks to the main actor via assumeIsolated, add isolated deinits, and apply the few justified nonisolated(unsafe) escapes for queue-confined Apple APIs.

* Fix the unit tests for Swift 6 concurrency

Hop the waitForConfirmation body onto the caller's actor (Swift Testing runs confirmation closures off-actor), and adjust the affected suites and async signatures.

* offload diffs on concurrent threads instead of main actor

* make room info protocols sendable

* use a task group for fetching data so that everything runs concurrently in the TextRoomTimelineView when getting the preview.

* use the generic onMainActor implementation, which already makes a stream and send the continuation on the main actor.

* small pr comments issues being addressed

* update enterprise

* Update StaticCode to 1.1.0 and specify the required Swift isolation.

* fix ElementCallServiceTests

* update enterprise

* re-generate mocks

* update enterprise

* enterprise new code conformed to swift 6

---------

Co-authored-by: Doug <douglase@element.io>
2026-06-18 17:55:31 +02:00

127 lines
5.6 KiB
Swift

//
// Copyright 2025 Element Creations Ltd.
// Copyright 2022-2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
import Foundation
import MatrixRustSDK
nonisolated enum Tracing {
/// The directory that stores all of the log files.
static var logsDirectory: URL {
if ProcessInfo.isRunningIntegrationTests {
"/Users/Shared"
} else {
logsDirectoryOverride ?? .appGroupLogsDirectory
}
}
/// Set this to temporarily override the directory from which logs will be collected.
/// This basically only affects ``logFiles``, and doesn't inform the SDK to write
/// the logs to a different directory, which should be done before setting this.
nonisolated(unsafe) static var logsDirectoryOverride: URL?
static var legacyLogsDirectory: URL {
.appGroupContainerDirectory
}
static let fileExtension = ".log"
static func buildConfiguration(logLevel: LogLevel,
traceLogPacks: Set<TraceLogPack>,
currentTarget: String,
filePrefix: String,
sentryURL: URL?) -> TracingConfiguration {
// Log everything on integration tests to check whether
// the logs contain any sensitive data. See `integration-tests.yml`
let level: LogLevel = ProcessInfo.isRunningIntegrationTests ? .trace : logLevel
let sentryConfig = sentryURL.map { url in
SentryConfig(dsn: url.absoluteString,
appVersion: InfoPlistReader.app.bundleShortVersionString,
appPlatform: ProcessInfo.processInfo.platform)
}
return .init(logLevel: level.rustLogLevel,
traceLogPacks: traceLogPacks.map(\.rustLogPack),
extraTargets: [currentTarget],
writeToStdoutOrSystem: true,
writeToFiles: .init(path: logsDirectory.path(percentEncoded: false),
filePrefix: filePrefix,
fileSuffix: fileExtension,
// Total compressed size needs to be under CloudFlare's max request size of 50Mb
maxTotalSizeBytes: 100 * 1024 * 1024, // 100Mb
maxAgeSeconds: 7 * 24 * 60 * 60), // One week
sentryConfig: sentryConfig)
}
/// A list of all log file URLs, sorted chronologically.
static var logFiles: [URL] {
logFiles(in: logsDirectory)
}
/// Collect all of the logs in the given directory, sorting them chronologically.
private static func logFiles(in directory: URL) -> [URL] {
var logFiles = [(url: URL, modificationDate: Date)]()
let fileManager = FileManager.default
let enumerator = fileManager.enumerator(at: directory,
includingPropertiesForKeys: [.contentModificationDateKey],
options: .skipsSubdirectoryDescendants)
// Find all *.log files and their modification dates.
while let logURL = enumerator?.nextObject() as? URL {
guard let resourceValues = try? logURL.resourceValues(forKeys: [.contentModificationDateKey]),
let modificationDate = resourceValues.contentModificationDate
else { continue }
if logURL.lastPathComponent.hasSuffix(fileExtension) {
logFiles.append((logURL, modificationDate))
}
}
let sortedFiles = logFiles.sorted { $0.modificationDate > $1.modificationDate }.map(\.url)
MXLog.info("logFiles: \(sortedFiles.map(\.lastPathComponent))")
return sortedFiles
}
static func migrateLogFiles() {
MXLog.info("Moving log files to \(logsDirectory)")
let fileManager = FileManager.default
let oldLogFiles = logFiles(in: legacyLogsDirectory)
for oldFileURL in oldLogFiles {
do {
let newFileURL = logsDirectory.appending(component: oldFileURL.lastPathComponent)
try fileManager.moveItem(at: oldFileURL, to: newFileURL)
MXLog.info("Moved \(newFileURL.lastPathComponent)")
} catch {
MXLog.error("Failed to move \(oldFileURL.lastPathComponent): \(error.localizedDescription)")
let nsError = error as NSError
if nsError.domain == NSCocoaErrorDomain, nsError.code == NSFileWriteFileExistsError {
// By now there will already be some logs in the new directory, so there is likely to be
// one log file that cannot be removed. As this is a one-off operation lets just delete it.
MXLog.error("Attempting to delete log file \(oldFileURL.lastPathComponent)")
try? fileManager.removeItem(at: oldFileURL)
}
}
}
}
/// Delete all log files.
static func deleteLogFiles(in directory: URL) {
let fileManager = FileManager.default
// We don't simply delete logsDirectory as once upon a time the logs
// we written to the very top-level of the app group container and
// there's a migration in place for old users of the app.
for logFileURL in logFiles(in: directory) {
try? fileManager.removeItem(at: logFileURL)
}
}
}