Files
element-x-ios/NSE/Sources/NSEUserSession.swift
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

157 lines
6.6 KiB
Swift

//
// Copyright 2025 Element Creations Ltd.
// Copyright 2023-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
// sourcery: AutoMockable
nonisolated protocol NSEUserSessionProtocol {
var inviteAvatarsVisibility: InviteAvatars { get async }
var mediaPreviewVisibility: MediaPreviews { get async }
var threadsEnabled: Bool { get }
func notificationItemProxy(roomID: String, eventID: String) async -> NotificationItemProxyProtocol?
func roomForIdentifier(_ roomID: String) -> Room?
}
final nonisolated class NSEUserSession: NSEUserSessionProtocol {
private let sessionDirectories: SessionDirectories
private let appSettings: CommonSettingsProtocol
private let baseClient: Client
private let notificationClient: NotificationClient
private let userID: String
private(set) lazy var mediaProvider: MediaProviderProtocol = MediaProvider(mediaLoader: MediaLoader(client: baseClient),
imageCache: .onlyOnDisk,
homeserverReachabilityPublisher: nil)
private let delegateHandle: TaskHandle?
var mediaPreviewVisibility: MediaPreviews {
get async {
do {
return try await baseClient.getMediaPreviewDisplayPolicy() ?? .on
} catch {
MXLog.error("Failed to get media preview visibility, defaulting to on. Error: \(error)")
return .on
}
}
}
var inviteAvatarsVisibility: InviteAvatars {
get async {
do {
return try await baseClient.getInviteAvatarsDisplayPolicy() ?? .on
} catch {
MXLog.error("Failed to get invite avatars visibility, defaulting to on. Error: \(error)")
return .on
}
}
}
var threadsEnabled: Bool {
appSettings.threadsEnabled
}
init(credentials: KeychainCredentials,
roomID: String,
clientSessionDelegate: ClientSessionDelegate,
appHooks: AppHooks,
appSettings: CommonSettingsProtocol) async throws {
sessionDirectories = credentials.restorationToken.sessionDirectories
userID = credentials.userID
self.appSettings = appSettings
let homeserverURL = credentials.restorationToken.session.homeserverUrl
let clientBuilder = ClientBuilder
.baseBuilder(setupEncryption: false,
httpProxy: URL(string: homeserverURL)?.globalProxy,
slidingSync: .restored,
sessionDelegate: clientSessionDelegate,
appHooks: appHooks,
enableOnlySignedDeviceIsolationMode: appSettings.enableOnlySignedDeviceIsolationMode,
requestTimeout: 15000,
maxRequestRetryTime: 5000,
threadsEnabled: appSettings.threadsEnabled)
.systemIsMemoryConstrained()
.sqliteStore(config: .init(dataPath: credentials.restorationToken.sessionDirectories.dataPath,
cachePath: credentials.restorationToken.sessionDirectories.cachePath)
.passphrase(passphrase: credentials.restorationToken.passphrase))
.username(username: credentials.userID)
.homeserverUrl(url: homeserverURL)
baseClient = try await clientBuilder.build()
delegateHandle = try baseClient.setDelegate(delegate: ClientDelegateWrapper())
try await baseClient.restoreSessionWith(session: credentials.restorationToken.session,
roomLoadSettings: .one(roomId: roomID))
notificationClient = try await baseClient.notificationClient(processSetup: .multipleProcesses)
}
func notificationItemProxy(roomID: String, eventID: String) async -> NotificationItemProxyProtocol? {
do {
let notificationStatus = try await notificationClient.getNotification(roomId: roomID, eventId: eventID)
switch notificationStatus {
case .event(let notification):
return NotificationItemProxy(notificationItem: notification,
eventID: eventID,
receiverID: userID,
roomID: roomID)
case .eventNotFound:
MXLog.error("Notification event not found - roomID: \(roomID) eventID: \(eventID)")
return nil
case .eventFilteredOut:
MXLog.warning("Notification event filtered out - roomID: \(roomID) eventID: \(eventID)")
return nil
case .eventRedacted:
MXLog.warning("Notification event redacted - roomID: \(roomID) eventID: \(eventID)")
return nil
}
} catch {
MXLog.error("Could not get notification's content creating an empty notification instead, error: \(error)")
return EmptyNotificationItemProxy(eventID: eventID, roomID: roomID, receiverID: userID)
}
}
func roomForIdentifier(_ roomID: String) -> Room? {
do {
return try notificationClient.getRoom(roomId: roomID)
} catch {
MXLog.error("Failed retrieving room with error: \(error)")
return nil
}
}
deinit {
delegateHandle?.cancel()
}
}
private final nonisolated class ClientDelegateWrapper: ClientDelegate {
// MARK: - ClientDelegate
func didReceiveAuthError(isSoftLogout: Bool) {
MXLog.error("Received authentication error, the NSE can't handle this.")
}
func didRefreshTokens() {
MXLog.info("Delegating session updates to the ClientSessionDelegate.")
}
func onBackgroundTaskErrorReport(taskName: String, error: MatrixRustSDK.BackgroundTaskFailureReason) {
switch error {
case .panic(let message, let backtrace):
MXLog.error("Received background task panic: \(message ?? "Missing message")\nBacktrace:\n\(backtrace ?? "Missing backtrace")")
case .error(let error):
MXLog.error("Received background task error: \(error)")
case .earlyTermination:
MXLog.error("Received background task early termination")
}
}
}