mirror of
https://github.com/Novaloop-AG/element-x-ios.git
synced 2026-11-02 03:06:37 +00:00
a520d94760
* 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>
222 lines
11 KiB
Swift
222 lines
11 KiB
Swift
//
|
|
// Copyright 2026 Element Creations Ltd.
|
|
//
|
|
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
|
|
// Please see LICENSE files in the repository root for full details.
|
|
//
|
|
|
|
import Synchronization
|
|
import Testing
|
|
|
|
/// A class that provides a mechanism to confirm that a specific action or event
|
|
/// has occurred a given number of times within an async context.
|
|
///
|
|
/// `WaitingConfirmation` is used in conjunction with ``waitForConfirmation(_:expectedCount:isolation:sourceLocation:_:)``
|
|
/// to synchronize async test expectations. It bridges between your test code and
|
|
/// Swift Testing's `confirmation` mechanism using an `AsyncStream` under the hood.
|
|
///
|
|
/// You typically interact with this type via its `callAsFunction()` sugar:
|
|
/// ```swift
|
|
/// await waitForConfirmation { confirmation in
|
|
/// sut.onEvent = { confirmation() }
|
|
/// sut.triggerEvent()
|
|
/// }
|
|
/// ```
|
|
final class WaitingConfirmation: Sendable {
|
|
private let continuation: AsyncStream<Void>.Continuation
|
|
private let expectedCount: Int
|
|
private let confirmationsCount: Mutex<Int>
|
|
|
|
fileprivate init(continuation: AsyncStream<Void>.Continuation, expectedCount: Int) {
|
|
self.continuation = continuation
|
|
self.expectedCount = expectedCount
|
|
confirmationsCount = .init(0)
|
|
}
|
|
|
|
/// Confirms that the expected event has occurred once.
|
|
///
|
|
/// Each call yields a value into the underlying stream, incrementing the confirmation count.
|
|
/// When the count reaches `expectedCount`, the stream is finished, unblocking ``waitForConfirmation``.
|
|
///
|
|
/// This method is thread-safe — the count increment and the finish check are performed
|
|
/// atomically inside a `Mutex` lock.
|
|
func confirm() {
|
|
confirmationsCount.withLock { value in
|
|
continuation.yield()
|
|
value += 1
|
|
if value == expectedCount {
|
|
continuation.finish()
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Allows the instance to be called directly as a function, forwarding to ``confirm()``.
|
|
///
|
|
/// This enables the ergonomic shorthand `confirmation()` instead of `confirmation.confirm()`.
|
|
func callAsFunction() {
|
|
confirm()
|
|
}
|
|
}
|
|
|
|
/// Waits for a confirmation to be triggered an expected number of times within a synchronous body.
|
|
///
|
|
/// This is a wrapper around Swift Testing's `confirmation` that removes the need to manually
|
|
/// manage an `AsyncStream` at the call site. The body receives a ``WaitingConfirmation`` instance
|
|
/// which can be called directly to signal that the expected event occurred.
|
|
///
|
|
/// The body is synchronous by design — it is intended for setting up mocks and triggering
|
|
/// actions that schedule async work, rather than performing async work itself. The async
|
|
/// waiting happens internally once the body returns, by draining the stream until all
|
|
/// confirmations are received.
|
|
///
|
|
/// Unlike the timeout variant, this overload does not escape the body closure, which means
|
|
/// you can safely capture mutable structs — a common pattern in Swift Testing.
|
|
///
|
|
/// > **Warning**: This overload has no timeout. If ``WaitingConfirmation/confirm()`` is never called,
|
|
/// > the test will hang indefinitely. Prefer the timeout variant when the confirmation
|
|
/// > depends on asynchronous work that could silently fail.
|
|
///
|
|
/// Example:
|
|
/// ```swift
|
|
/// await waitForConfirmation(expectedCount: 2) { confirmation in
|
|
/// sut.onEvent = {
|
|
/// confirmation()
|
|
/// }
|
|
/// sut.triggerEvent()
|
|
/// sut.triggerEvent()
|
|
/// }
|
|
/// ```
|
|
///
|
|
/// - Parameters:
|
|
/// - comment: An optional comment to attach to the confirmation for test reporting.
|
|
/// - expectedCount: The number of times ``WaitingConfirmation/confirm()`` must be called.
|
|
/// Must be greater than 0, otherwise a test failure is recorded and execution stops.
|
|
/// Defaults to `1`.
|
|
/// - isolation: The actor isolation context. Defaults to the caller's isolation via `#isolation`.
|
|
/// - sourceLocation: The source location for failure reporting. Defaults to the call site via `#_sourceLocation`.
|
|
/// - body: A synchronous closure receiving a ``WaitingConfirmation`` instance used to signal
|
|
/// event occurrences. The closure may throw, and any thrown errors are rethrown to the caller.
|
|
/// Typically used to configure mocks and trigger the action under test.
|
|
/// - Returns: The value returned by `body`.
|
|
func waitForConfirmation<R>(_ comment: Comment? = nil,
|
|
expectedCount: Int = 1,
|
|
isolation: isolated (any Actor)? = #isolation,
|
|
sourceLocation: SourceLocation = #_sourceLocation,
|
|
_ body: (WaitingConfirmation) throws -> sending R) async rethrows -> R {
|
|
guard expectedCount > 0 else {
|
|
// Or may run indefinitely
|
|
Issue.record("Expected count must be greater than 0", sourceLocation: sourceLocation)
|
|
preconditionFailure()
|
|
}
|
|
|
|
let (stream, continuation) = AsyncStream.makeStream(of: Void.self)
|
|
return try await confirmation(comment,
|
|
expectedCount: expectedCount,
|
|
isolation: isolation,
|
|
sourceLocation: sourceLocation) { confirmation in
|
|
let result = try await runBody(on: isolation,
|
|
body,
|
|
with: .init(continuation: continuation,
|
|
expectedCount: expectedCount))
|
|
for await _ in stream {
|
|
confirmation()
|
|
}
|
|
return result
|
|
}
|
|
}
|
|
|
|
/// Runs the body on the given actor, so that it can safely touch the caller's isolated state.
|
|
///
|
|
/// Swift Testing's `confirmation` runs its closure on the concurrent executor regardless of the
|
|
/// isolation parameter, so without this hop a body that synchronously triggers main actor
|
|
/// work (e.g. sending a view action) would crash on the runtime's executor check.
|
|
private func runBody<R>(on isolation: isolated (any Actor)?,
|
|
_ body: (WaitingConfirmation) throws -> R,
|
|
with confirmation: WaitingConfirmation) rethrows -> R {
|
|
try body(confirmation)
|
|
}
|
|
|
|
/// Waits for a confirmation to be triggered an expected number of times within a synchronous body,
|
|
/// with a timeout.
|
|
///
|
|
/// This overload behaves like ``waitForConfirmation(_:expectedCount:isolation:sourceLocation:_:)``
|
|
/// but races the stream against a timeout. If the timeout expires before all confirmations
|
|
/// are received, the stream is forcefully finished and Swift Testing records whatever
|
|
/// confirmations were received up to that point — which will cause a test failure if
|
|
/// `expectedCount` was not reached.
|
|
///
|
|
/// The body is synchronous by design — it is intended for setting up mocks and triggering
|
|
/// actions that schedule async work, rather than performing async work itself. The async
|
|
/// waiting and timeout racing happen internally once the body returns.
|
|
///
|
|
/// > Note: Because this overload uses `withTaskGroup` internally to race the stream against
|
|
/// > the timeout, the `body` closure is implicitly `@escaping`. This is why this is a separate
|
|
/// > overload rather than a single function with an optional timeout — keeping them separate
|
|
/// > allows the non-timeout variant to avoid `@escaping`, which lets you capture mutable structs
|
|
/// > in `body` as is common in Swift Testing.
|
|
///
|
|
/// Example:
|
|
/// ```swift
|
|
/// await waitForConfirmation(expectedCount: 1, timeout: .seconds(2)) { confirmation in
|
|
/// sut.onNetworkResponse = { confirmation() }
|
|
/// sut.startRequest()
|
|
/// }
|
|
/// ```
|
|
///
|
|
/// - Parameters:
|
|
/// - comment: An optional comment to attach to the confirmation for test reporting.
|
|
/// - expectedCount: The number of times ``WaitingConfirmation/confirm()`` must be called.
|
|
/// Must be equal to or greater than 0, otherwise a test failure is recorded
|
|
/// and execution stops. Defaults to `1`.
|
|
/// Pass `0` to assert that the event never fires within the timeout window —
|
|
/// useful for verifying that a function does NOT trigger under specific conditions.
|
|
/// - timeout: The maximum duration to wait for all confirmations before finishing the stream.
|
|
/// - isolation: The actor isolation context. Defaults to the caller's isolation via `#isolation`.
|
|
/// - sourceLocation: The source location for failure reporting. Defaults to the call site via `#_sourceLocation`.
|
|
/// - body: A synchronous closure receiving a ``WaitingConfirmation`` instance used to signal
|
|
/// event occurrences. The closure may throw, and any thrown errors are rethrown to the caller.
|
|
/// Typically used to configure mocks and trigger the action under test.
|
|
/// - Returns: The value returned by `body`.
|
|
func waitForConfirmation<R>(_ comment: Comment? = nil,
|
|
expectedCount: Int = 1,
|
|
timeout: Duration,
|
|
isolation: isolated (any Actor)? = #isolation,
|
|
sourceLocation: SourceLocation = #_sourceLocation,
|
|
_ body: (WaitingConfirmation) throws -> sending R) async rethrows -> R {
|
|
guard expectedCount >= 0 else {
|
|
// Or may run indefinitely
|
|
Issue.record("Expected count must be equal or greater than 0", sourceLocation: sourceLocation)
|
|
preconditionFailure()
|
|
}
|
|
|
|
let (stream, continuation) = AsyncStream.makeStream(of: Void.self)
|
|
return try await confirmation(comment,
|
|
expectedCount: expectedCount,
|
|
isolation: isolation,
|
|
sourceLocation: sourceLocation) { confirmation in
|
|
let result = try await runBody(on: isolation,
|
|
body,
|
|
with: .init(continuation: continuation,
|
|
expectedCount: expectedCount))
|
|
|
|
// The reason why I don't add to the task group directly the non timeout implementation
|
|
// is that I do not want the body to be marked as @escaping and thus to be able to capture
|
|
// even mutable structs which is common in Swift Testing.
|
|
await withTaskGroup(of: Void.self) { group in
|
|
group.addTask {
|
|
for await _ in stream {
|
|
confirmation()
|
|
}
|
|
}
|
|
group.addTask {
|
|
try? await Task.sleep(for: timeout)
|
|
continuation.finish()
|
|
}
|
|
await group.next()
|
|
group.cancelAll()
|
|
}
|
|
|
|
return result
|
|
}
|
|
}
|