From 38fc47193929b8d2bb7e85d107d488a79294faf6 Mon Sep 17 00:00:00 2001 From: Prachi Gauriar Date: Tue, 24 Nov 2026 23:47:17 -0500 Subject: [PATCH] Add result updates to LiveQuery MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add LiveQueryResultUpdatesProducer, which returns an AsyncSequence of results for each query fragment, and LiveQuery.init(resultUpdatesProducer:). Each value the sequence produces replaces the live query’s results. - Make LiveQueryResultsProducer refine LiveQueryResultUpdatesProducer, with a default resultUpdates(forQueryFragment:) that produces results once. Existing conformances don’t need to change. - Cancel result production for a query fragment when a newer fragment arrives, and discard results that arrive for superseded fragments. This changes behavior for existing results producers. - Document what happens when a query fragment canonicalizes to nil. - Wait for live query state with Observations in tests instead of mock epilogues, which fire before the live query writes results. - Add MockLiveQueryResultUpdatesProducer and ClosureAsyncSequence for testing. - Add release notes to 1.12.0. --- CHANGELOG.md | 27 ++ .../Documentation.docc/Documentation.md | 1 + .../DevFoundation/Live Query/LiveQuery.swift | 178 +++++-- .../LiveQueryResultUpdatesProducer.swift | 80 +++ .../Live Query/LiveQueryResultsProducer.swift | 38 +- .../OneShotLiveQueryResultUpdates.swift | 58 +++ .../LiveQueryResultUpdatesProducerTests.swift | 51 ++ .../LiveQueryResultsProducerTests.swift | 76 ++- .../Live Query/LiveQueryTests.swift | 458 ++++++++++++++++-- .../ClosureAsyncSequence.swift | 46 ++ .../MockLiveQueryResultUpdatesProducer.swift | 33 ++ .../MockLiveQueryResultsProducer.swift | 3 + 12 files changed, 955 insertions(+), 94 deletions(-) create mode 100644 Sources/DevFoundation/Live Query/LiveQueryResultUpdatesProducer.swift create mode 100644 Sources/DevFoundation/Live Query/OneShotLiveQueryResultUpdates.swift create mode 100644 Tests/DevFoundationTests/Live Query/LiveQueryResultUpdatesProducerTests.swift create mode 100644 Tests/DevFoundationTests/Testing Helpers/ClosureAsyncSequence.swift create mode 100644 Tests/DevFoundationTests/Testing Helpers/MockLiveQueryResultUpdatesProducer.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 416e8d4..e04a9c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,33 @@ asynchronous code runs: explicitly `@concurrent`, so it still runs off its caller’s actor, and existing interceptors don’t need to change. +This release also adds support for live queries whose results change after they’re produced, like +a search over a local database that should update when the database does: + + - The new `LiveQueryResultUpdatesProducer` protocol returns an `AsyncSequence` of results for each + query fragment. Create a live query that uses one with `LiveQuery.init(resultUpdatesProducer:)`. + Each value the sequence produces replaces the live query’s results, and when the query fragment + changes, the live query cancels its iteration of the previous fragment’s sequence. + - `LiveQueryResultsProducer` now refines `LiveQueryResultUpdatesProducer`, with a default + implementation of `resultUpdates(forQueryFragment:)` that produces results once. Existing + conformances don’t need to change. + - `LiveQuery` now cancels result production for a query fragment when a newer fragment arrives, + and discards any results it produces later. Previously, a live query waited for each + fragment’s results before producing the next fragment’s. That delayed results for the latest + fragment by however long the previous call had left, and it showed results for a fragment the + user had already moved past. Now, result production for the latest fragment starts right away, + and results that arrive for a fragment the user has moved past are discarded. This change is + required to support result updates sequences, because otherwise a live query would wait for + the first fragment’s sequence to finish; if it never did, the live query would never produce + results for later fragments. + + You may notice the change if your results producer is slow relative to its debounce duration. + While someone types in short bursts, each burst cancels the previous call, so intermediate + results appear less often. Choosing a debounce duration close to your producer’s typical + latency avoids this. If your producer ignores cancellation, it still runs to completion, but + its results are no longer shown. If its work must finish, for example to cache results, run + that work in a separate task that cancellation doesn’t reach. + ## 1.11.0: August 4, 2026 diff --git a/Sources/DevFoundation/Documentation.docc/Documentation.md b/Sources/DevFoundation/Documentation.docc/Documentation.md index 97583af..a6d622f 100644 --- a/Sources/DevFoundation/Documentation.docc/Documentation.md +++ b/Sources/DevFoundation/Documentation.docc/Documentation.md @@ -28,6 +28,7 @@ for paging through data, and essential utility types for building robust applica - ``LiveQuery`` - ``LiveQueryResultsProducer`` + - ``LiveQueryResultUpdatesProducer`` - ``LiveQuerySchedulingStrategy`` ### Localizing with Remote Content diff --git a/Sources/DevFoundation/Live Query/LiveQuery.swift b/Sources/DevFoundation/Live Query/LiveQuery.swift index c6589b8..ca6c26d 100644 --- a/Sources/DevFoundation/Live Query/LiveQuery.swift +++ b/Sources/DevFoundation/Live Query/LiveQuery.swift @@ -19,7 +19,15 @@ import Synchronization /// ## Overview /// /// `LiveQuery` provides a reactive interface for search-as-you-type functionality. It coordinates between user input -/// and result production, handling common concerns like debouncing, duplicate removal, and error management. +/// and result production, handling common concerns like debouncing, duplicate removal, cancellation, and error +/// management. +/// +/// Live queries get results from a producer. A ``LiveQueryResultsProducer`` produces results once for each query +/// fragment, which works well for searches whose results don’t change, like network requests. A +/// ``LiveQueryResultUpdatesProducer`` produces a sequence of results for each query fragment, which works well for +/// searches over local data that should update when the data changes. In both cases, results for a query fragment are +/// only used until the query fragment changes. When it does, the live query cancels result production for the previous +/// fragment and discards any results it produces later. /// /// /// ## Usage @@ -38,6 +46,10 @@ import Synchronization /// /// let liveQuery = LiveQuery(resultsProducer: SearchProducer()) /// +/// If results can change after they’re produced, provide a ``LiveQueryResultUpdatesProducer`` instead: +/// +/// let liveQuery = LiveQuery(resultUpdatesProducer: NoteSearchProducer(noteStore: noteStore)) +/// /// Update the query fragment to trigger result production: /// /// liveQuery.queryFragment = "search term" @@ -56,7 +68,7 @@ import Synchronization /// /// ## Scheduling Strategies /// -/// The results producer’s ``LiveQueryResultsProducer/schedulingStrategy`` determines when results are generated: +/// The producer’s scheduling strategy determines when results are generated: /// /// - ``LiveQuerySchedulingStrategy/passthrough``: Produces results immediately for every change. Best for cheap /// operations like filtering local data. @@ -69,6 +81,10 @@ import Synchronization /// Errors from result production are captured in ``lastError``. The query continues operating after errors, /// preserving the last successful results until new ones are produced. /// +/// When a result updates sequence throws an error, the live query sets ``lastError`` and stops iterating that +/// sequence, keeping its last results. Changing the query fragment starts a new sequence, and its first value clears +/// ``lastError``. Errors from a sequence that was cancelled because the query fragment changed are ignored. +/// /// /// ## Thread Safety /// @@ -78,8 +94,8 @@ import Synchronization /// /// ## Performance /// -/// The query automatically deduplicates identical fragments and canonicalizes input through the results producer. -/// This prevents unnecessary work when users make redundant changes. +/// The query automatically deduplicates identical fragments and canonicalizes input through the producer. This +/// prevents unnecessary work when users make redundant changes. @Observable public final class LiveQuery: Sendable where Results: Sendable { /// The query’s mutable state. @@ -95,50 +111,48 @@ public final class LiveQuery: Sendable where Results: Sendable { /// The task that handles inputs. var inputHandlingTask: Task? + + /// The task that iterates the current query fragment’s result updates. + var resultUpdatesTask: Task? + + /// The generation of the current query fragment’s result updates. + /// + /// This is incremented each time result updates start for a new query fragment. Result updates only change the + /// query’s state if their generation matches this one. + var resultUpdatesGeneration: UInt64 = 0 } + /// A mutex that synchronizes access to the query’s mutable state. private let stateMutex = Mutex(State()) /// A continuation used to yield query fragment changes to the input handling task. private let queryFragmentContinuation: AsyncStream.Continuation - /// The results producer used to generate results. - private let resultsProducer: any LiveQueryResultsProducer + /// The producer used to generate result updates. + private let resultUpdatesProducer: any LiveQueryResultUpdatesProducer - /// Creates a live query with the specified results producer. + /// Creates a live query with the specified result updates producer. /// - /// - Parameter resultsProducer: The producer used to generate results. - public init(resultsProducer: some LiveQueryResultsProducer) { - self.resultsProducer = resultsProducer + /// Each time the query fragment changes, the live query iterates the result updates for the new query fragment, + /// updating ``results`` with each value. It cancels its iteration of the previous query fragment’s result updates. + /// + /// - Parameter resultUpdatesProducer: The producer used to generate result updates. + public init(resultUpdatesProducer: some LiveQueryResultUpdatesProducer) { + self.resultUpdatesProducer = resultUpdatesProducer let (queryFragmentStream, queryFragmentContinuation) = AsyncStream.makeStream() self.queryFragmentContinuation = queryFragmentContinuation - let queryFragmentValues = queryFragmentStream.schedule(with: resultsProducer.schedulingStrategy) + let queryFragmentValues = queryFragmentStream.schedule(with: resultUpdatesProducer.schedulingStrategy) let task = Task { [weak self] in for await queryFragment in queryFragmentValues { guard let self else { return } - do { - let results = try await resultsProducer.results(forQueryFragment: queryFragment) - - _$observationRegistrar.willSet(self, keyPath: \.lastError) - _$observationRegistrar.willSet(self, keyPath: \.results) - stateMutex.withLock { state in - state.results = results - state.lastError = nil - } - _$observationRegistrar.didSet(self, keyPath: \.results) - _$observationRegistrar.didSet(self, keyPath: \.lastError) - } catch { - withMutation(keyPath: \.lastError) { - stateMutex.withLock { $0.lastError = error } - } - } + startResultUpdates(forQueryFragment: queryFragment) } } @@ -146,15 +160,33 @@ public final class LiveQuery: Sendable where Results: Sendable { } + /// Creates a live query with the specified results producer. + /// + /// Each time the query fragment changes, the live query produces results for the new query fragment. If results for + /// the previous query fragment are still being produced, the live query cancels their production and discards them. + /// + /// - Parameter resultsProducer: The producer used to generate results. + public convenience init(resultsProducer: some LiveQueryResultsProducer) { + self.init(resultUpdatesProducer: resultsProducer) + } + + deinit { - stateMutex.withLock { $0.inputHandlingTask?.cancel() } + stateMutex.withLock { state in + state.inputHandlingTask?.cancel() + state.resultUpdatesTask?.cancel() + } queryFragmentContinuation.finish() } /// The current query fragment. /// - /// Updates trigger result production based on the scheduling strategy. + /// Updates trigger result production based on the scheduling strategy. If the producer’s + /// ``LiveQueryResultUpdatesProducer/canonicalQueryFragment(from:)`` returns `nil` for the new value, the update + /// doesn’t trigger result production. The query keeps its results, and if the previous query fragment’s result + /// updates haven’t finished, the query keeps iterating them. With the default canonicalization, this happens + /// when the query fragment is empty or contains only whitespace. public var queryFragment: String { get { access(keyPath: \.queryFragment) @@ -166,7 +198,7 @@ public final class LiveQuery: Sendable where Results: Sendable { stateMutex.withLock { $0.queryFragment = newValue } } - if let canonicalQueryFragment = resultsProducer.canonicalQueryFragment(from: newValue) { + if let canonicalQueryFragment = resultUpdatesProducer.canonicalQueryFragment(from: newValue) { queryFragmentContinuation.yield(canonicalQueryFragment) } } @@ -185,6 +217,92 @@ public final class LiveQuery: Sendable where Results: Sendable { access(keyPath: \.lastError) return stateMutex.withLock(\.lastError) } + + + /// Starts iterating the result updates for a query fragment, cancelling the previous fragment’s result updates. + /// + /// - Parameter queryFragment: The canonical query fragment whose result updates are iterated. + private func startResultUpdates(forQueryFragment queryFragment: String) { + let resultUpdates = resultUpdatesProducer.resultUpdates(forQueryFragment: queryFragment) + + stateMutex.withLock { state in + state.resultUpdatesTask?.cancel() + state.resultUpdatesGeneration += 1 + + let generation = state.resultUpdatesGeneration + state.resultUpdatesTask = Task { [weak self] in + do { + for try await results in resultUpdates { + // Stop iterating once we’re deallocated, even if the sequence ignores cancellation + guard let self else { + return + } + + update(results: results, generation: generation) + } + } catch { + self?.update(error: error, generation: generation) + } + } + } + } + + + /// Sets the query’s results and clears its last error if the generation is current. + /// + /// - Parameters: + /// - results: The new results. + /// - generation: The generation of the result updates that produced the results. + private func update(results: Results, generation: UInt64) { + // Check the generation before notifying observers so that rejected writes don’t cause spurious notifications. + // We check again when writing, because the generation can change in between. + guard isCurrent(generation) else { + return + } + + _$observationRegistrar.willSet(self, keyPath: \.lastError) + _$observationRegistrar.willSet(self, keyPath: \.results) + stateMutex.withLock { state in + guard state.resultUpdatesGeneration == generation else { + return + } + + state.results = results + state.lastError = nil + } + _$observationRegistrar.didSet(self, keyPath: \.results) + _$observationRegistrar.didSet(self, keyPath: \.lastError) + } + + + /// Sets the query’s last error if the generation is current. + /// + /// - Parameters: + /// - error: The error that occurred. + /// - generation: The generation of the result updates that produced the error. + private func update(error: any Error, generation: UInt64) { + guard isCurrent(generation) else { + return + } + + withMutation(keyPath: \.lastError) { + stateMutex.withLock { state in + guard state.resultUpdatesGeneration == generation else { + return + } + + state.lastError = error + } + } + } + + + /// Returns whether the specified generation is the generation of the current query fragment’s result updates. + /// + /// - Parameter generation: The generation to check. + private func isCurrent(_ generation: UInt64) -> Bool { + return stateMutex.withLock { $0.resultUpdatesGeneration == generation } + } } diff --git a/Sources/DevFoundation/Live Query/LiveQueryResultUpdatesProducer.swift b/Sources/DevFoundation/Live Query/LiveQueryResultUpdatesProducer.swift new file mode 100644 index 0000000..ef94f5c --- /dev/null +++ b/Sources/DevFoundation/Live Query/LiveQueryResultUpdatesProducer.swift @@ -0,0 +1,80 @@ +// +// LiveQueryResultUpdatesProducer.swift +// DevFoundation +// +// Created by Prachi Gauriar on 11/24/2026. +// + +import Foundation + +/// A type that produces a sequence of result updates for query fragments. +/// +/// Conform to this protocol when a query fragment’s results can change after they’re first produced, like a search +/// over local data that should update when the data does. ``LiveQuery`` iterates the sequence for the latest query +/// fragment and updates its results each time the sequence produces a value. When the query fragment changes, the live +/// query cancels its iteration of the previous fragment’s sequence. +/// +/// For example, a producer can return a database observation that produces the current search results, then new +/// results each time the database changes: +/// +/// struct NoteSearchProducer: LiveQueryResultUpdatesProducer { +/// let noteStore: NoteStore +/// +/// var schedulingStrategy: LiveQuerySchedulingStrategy { +/// .passthrough +/// } +/// +/// func resultUpdates( +/// forQueryFragment queryFragment: String +/// ) -> some AsyncSequence<[Note], any Error> & Sendable { +/// noteStore.observeNotes(matching: queryFragment) +/// } +/// } +/// +/// let liveQuery = LiveQuery(resultUpdatesProducer: NoteSearchProducer(noteStore: noteStore)) +/// +/// If results don’t change after they’re produced, conform to ``LiveQueryResultsProducer`` instead. It refines this +/// protocol, providing a default implementation of ``resultUpdates(forQueryFragment:)`` that produces results once. +public protocol LiveQueryResultUpdatesProducer: Sendable { + /// The type of results that instances produce. + associatedtype Results: Sendable + + /// The type of sequence that instances return for each query fragment. + associatedtype ResultUpdates: AsyncSequence & Sendable + + /// The strategy used to schedule result production. + var schedulingStrategy: LiveQuerySchedulingStrategy { get } + + /// Returns a canonical form of the query fragment, or `nil` if it’s invalid. + /// + /// Conforming types can use this function to sanitize or validate query fragments before producing results. The + /// default implementation trims whitespace, collapses multiple spaces into one, and returns `nil` for empty + /// strings. + /// + /// When this function returns `nil`, live queries don’t produce results for the query fragment. They keep their + /// results, and keep iterating the previous query fragment’s result updates if they haven’t finished. + /// + /// - Parameter queryFragment: The query fragment to canonicalize. + func canonicalQueryFragment(from queryFragment: String) -> String? + + /// Returns a sequence of results for the specified query fragment. + /// + /// The sequence should produce the query fragment’s current results first, followed by new results each time they + /// change. Live queries cancel their iteration of the sequence when the query fragment changes, so the sequence + /// should stop producing values when it’s cancelled. + /// + /// - Parameter queryFragment: A canonical query fragment. Live queries ensure this is already canonicalized before + /// calling this function. + func resultUpdates(forQueryFragment queryFragment: String) -> ResultUpdates +} + + +extension LiveQueryResultUpdatesProducer { + public func canonicalQueryFragment(from queryFragment: String) -> String? { + let canonicalFragment = queryFragment.components(separatedBy: .whitespacesAndNewlines) + .filter { !$0.isEmpty } + .joined(separator: " ") + + return canonicalFragment.isEmpty ? nil : canonicalFragment + } +} diff --git a/Sources/DevFoundation/Live Query/LiveQueryResultsProducer.swift b/Sources/DevFoundation/Live Query/LiveQueryResultsProducer.swift index 3a32f69..e432c4c 100644 --- a/Sources/DevFoundation/Live Query/LiveQueryResultsProducer.swift +++ b/Sources/DevFoundation/Live Query/LiveQueryResultsProducer.swift @@ -11,21 +11,13 @@ import Foundation /// /// Conform to this protocol to define how results are generated or fetched for a given query fragment. ``LiveQuery`` /// uses result producers to fetch results and determine how to schedule result production. -public protocol LiveQueryResultsProducer: Sendable { +/// +/// Results producers are result updates producers whose result updates contain a single value: the results returned by +/// ``results(forQueryFragment:)``. If a query fragment’s results can change after they’re produced, conform to +/// ``LiveQueryResultUpdatesProducer`` instead. +public protocol LiveQueryResultsProducer: LiveQueryResultUpdatesProducer { /// The type of results that instances produce. - associatedtype Results: Sendable - - /// The strategy used to schedule result production. - var schedulingStrategy: LiveQuerySchedulingStrategy { get } - - /// Returns a canonical form of the query fragment, or `nil` if it’s invalid. - /// - /// Conforming types can use this function to sanitize or validate query fragments before producing results. The - /// default implementation trims whitespace, collapses multiple spaces into one, and returns `nil` for empty - /// strings. - /// - /// - Parameter queryFragment: The query fragment to canonicalize. - func canonicalQueryFragment(from queryFragment: String) -> String? + associatedtype Results /// Produces results for the specified query fragment. /// @@ -36,11 +28,17 @@ public protocol LiveQueryResultsProducer: Sendable { extension LiveQueryResultsProducer { - public func canonicalQueryFragment(from queryFragment: String) -> String? { - let canonicalFragment = queryFragment.components(separatedBy: .whitespacesAndNewlines) - .filter { !$0.isEmpty } - .joined(separator: " ") - - return canonicalFragment.isEmpty ? nil : canonicalFragment + /// Returns a sequence that produces the query fragment’s results once. + /// + /// The sequence calls ``results(forQueryFragment:)`` when it’s first iterated, produces its results, and then + /// finishes. If the iterating task is cancelled before the sequence calls ``results(forQueryFragment:)``, the + /// sequence throws a `CancellationError` instead. Otherwise, cancelling the iterating task cancels the call. + /// + /// - Parameter queryFragment: A canonical query fragment. Live queries ensure this is already canonicalized before + /// calling this function. + public func resultUpdates( + forQueryFragment queryFragment: String + ) -> some AsyncSequence & Sendable { + return OneShotLiveQueryResultUpdates(resultsProducer: self, queryFragment: queryFragment) } } diff --git a/Sources/DevFoundation/Live Query/OneShotLiveQueryResultUpdates.swift b/Sources/DevFoundation/Live Query/OneShotLiveQueryResultUpdates.swift new file mode 100644 index 0000000..285e751 --- /dev/null +++ b/Sources/DevFoundation/Live Query/OneShotLiveQueryResultUpdates.swift @@ -0,0 +1,58 @@ +// +// OneShotLiveQueryResultUpdates.swift +// DevFoundation +// +// Created by Prachi Gauriar on 11/24/2026. +// + +import Foundation + +/// A sequence that produces a query fragment’s results from a results producer once. +/// +/// The sequence’s iterator gets results from the results producer in its first call to `next()`, so cancelling the task +/// that’s iterating the sequence cancels result production. If the task is already cancelled, the iterator throws a +/// `CancellationError` without calling the results producer. +struct OneShotLiveQueryResultUpdates: AsyncSequence, Sendable +where ResultsProducer: LiveQueryResultsProducer { + typealias Element = ResultsProducer.Results + typealias Failure = any Error + + + /// The results producer that produces the query fragment’s results. + let resultsProducer: ResultsProducer + + /// The query fragment whose results are produced. + let queryFragment: String + + + func makeAsyncIterator() -> AsyncIterator { + return AsyncIterator(resultsProducer: resultsProducer, queryFragment: queryFragment) + } +} + + +extension OneShotLiveQueryResultUpdates { + /// The iterator for one-shot result updates. + struct AsyncIterator: AsyncIteratorProtocol { + typealias Element = ResultsProducer.Results + typealias Failure = any Error + + + /// The results producer, or `nil` if the iterator has already produced results. + var resultsProducer: ResultsProducer? + + /// The query fragment whose results are produced. + let queryFragment: String + + + mutating func next() async throws -> ResultsProducer.Results? { + guard let resultsProducer else { + return nil + } + + self.resultsProducer = nil + try Task.checkCancellation() + return try await resultsProducer.results(forQueryFragment: queryFragment) + } + } +} diff --git a/Tests/DevFoundationTests/Live Query/LiveQueryResultUpdatesProducerTests.swift b/Tests/DevFoundationTests/Live Query/LiveQueryResultUpdatesProducerTests.swift new file mode 100644 index 0000000..09f1458 --- /dev/null +++ b/Tests/DevFoundationTests/Live Query/LiveQueryResultUpdatesProducerTests.swift @@ -0,0 +1,51 @@ +// +// LiveQueryResultUpdatesProducerTests.swift +// DevFoundation +// +// Created by Prachi Gauriar on 11/24/2026. +// + +import Foundation +import Testing + +@testable import DevFoundation + +struct LiveQueryResultUpdatesProducerTests { + @Test( + arguments: [ + ("hello", "hello"), + (" hello ", "hello"), + ("hello world", "hello world"), + (" hello world ", "hello world"), + ("hello\nworld", "hello world"), + ("hello\tworld", "hello world"), + (" hello \n world \t test ", "hello world test"), + ("", nil), + (" ", nil), + ("\n\t", nil), + (" \n \t ", nil), + ] + ) + func canonicalQueryFragment(input: String, expected: String?) { + // set up the test by creating a result updates producer + let producer = TestResultUpdatesProducer() + + // exercise the test by canonicalizing the query fragment + let result = producer.canonicalQueryFragment(from: input) + + // expect the result matches the expected canonical form + #expect(result == expected) + } + + + struct TestResultUpdatesProducer: LiveQueryResultUpdatesProducer { + var schedulingStrategy: LiveQuerySchedulingStrategy { + .passthrough + } + + + func resultUpdates(forQueryFragment queryFragment: String) -> AsyncThrowingStream<[String], any Error> { + AsyncThrowingStream { $0.finish() } + } + } +} diff --git a/Tests/DevFoundationTests/Live Query/LiveQueryResultsProducerTests.swift b/Tests/DevFoundationTests/Live Query/LiveQueryResultsProducerTests.swift index 126fa9f..5d6da6a 100644 --- a/Tests/DevFoundationTests/Live Query/LiveQueryResultsProducerTests.swift +++ b/Tests/DevFoundationTests/Live Query/LiveQueryResultsProducerTests.swift @@ -5,12 +5,18 @@ // Created by Prachi Gauriar on 10/24/2025. // +import DevTesting import Foundation import Testing @testable import DevFoundation -struct LiveQueryResultsProducerTests { +struct LiveQueryResultsProducerTests: RandomValueGenerating { + var randomNumberGenerator = makeRandomNumberGenerator() + + + // MARK: - canonicalQueryFragment(from:) + @Test( arguments: [ ("hello", "hello"), @@ -38,6 +44,74 @@ struct LiveQueryResultsProducerTests { } + // MARK: - resultUpdates(forQueryFragment:) + + @Test + mutating func resultUpdatesProducesResultsOnce() async throws { + // set up the test by creating a results producer that returns random results + let resultsProducer = MockLiveQueryResultsProducer<[String]>() + let results = Array(count: randomInt(in: 1 ... 5)) { randomAlphanumericString() } + resultsProducer.resultsStub = ThrowingStub(defaultReturnValue: results) + let queryFragment = randomAlphanumericString() + + // exercise the test by collecting the result updates + var resultUpdates: [[String]] = [] + for try await update in resultsProducer.resultUpdates(forQueryFragment: queryFragment) { + resultUpdates.append(update) + } + + // expect the sequence produced the results once + #expect(resultUpdates == [results]) + #expect(resultsProducer.resultsStub.callArguments == [queryFragment]) + } + + + @Test + mutating func resultUpdatesThrowsResultsProducerError() async throws { + // set up the test by creating a results producer that throws an error + let resultsProducer = MockLiveQueryResultsProducer<[String]>() + let error = randomError() + resultsProducer.resultsStub = ThrowingStub(defaultError: error) + let queryFragment = randomAlphanumericString() + + // exercise the test by iterating the result updates + let resultUpdates = resultsProducer.resultUpdates(forQueryFragment: queryFragment) + + // expect the sequence throws the results producer’s error + await #expect(throws: error) { + for try await _ in resultUpdates { + // Does nothing, because the sequence throws before producing a value. + } + } + #expect(resultsProducer.resultsStub.callArguments == [queryFragment]) + } + + + @Test + mutating func resultUpdatesThrowsCancellationErrorWithoutProducingResultsWhenCancelled() async throws { + // set up the test by creating a results producer + let resultsProducer = MockLiveQueryResultsProducer<[String]>() + resultsProducer.resultsStub = ThrowingStub(defaultReturnValue: [randomAlphanumericString()]) + let resultUpdates = resultsProducer.resultUpdates(forQueryFragment: randomAlphanumericString()) + + // exercise the test by iterating the result updates in a cancelled task + let task = Task { + withUnsafeCurrentTask { $0?.cancel() } + for try await _ in resultUpdates { + // Does nothing, because the sequence throws before producing a value. + } + } + + // expect the sequence throws a cancellation error without calling the results producer + await #expect(throws: CancellationError.self) { + try await task.value + } + #expect(resultsProducer.resultsStub.calls.isEmpty) + } + + + // MARK: - Test Types + struct TestResultsProducer: LiveQueryResultsProducer { var schedulingStrategy: LiveQuerySchedulingStrategy { .passthrough diff --git a/Tests/DevFoundationTests/Live Query/LiveQueryTests.swift b/Tests/DevFoundationTests/Live Query/LiveQueryTests.swift index 6e5ab3a..b94baa6 100644 --- a/Tests/DevFoundationTests/Live Query/LiveQueryTests.swift +++ b/Tests/DevFoundationTests/Live Query/LiveQueryTests.swift @@ -7,6 +7,8 @@ import DevTesting import Foundation +import Observation +import Synchronization import Testing @testable import DevFoundation @@ -82,7 +84,7 @@ struct LiveQueryTests: RandomValueGenerating { liveQuery.queryFragment = fragment2 // wait for the first call to complete - await signalStream.first { _ in true } + await signalStream.first { @Sendable _ in true } // expect canonicalQueryFragment was called twice with correct arguments #expect(resultsProducer.canonicalQueryFragmentStub.callArguments == [fragment1, fragment2]) @@ -94,7 +96,7 @@ struct LiveQueryTests: RandomValueGenerating { // MARK: - results - @Test + @MainActor @Test mutating func settingValidQueryFragmentProducesResults() async throws { // set up the test by creating a mock results producer let resultsProducer = MockLiveQueryResultsProducer<[String]>() @@ -106,18 +108,13 @@ struct LiveQueryTests: RandomValueGenerating { let expectedResults = [randomAlphanumericString(), randomAlphanumericString()] resultsProducer.resultsStub = ThrowingStub(defaultReturnValue: expectedResults) - let (signalStream, signaler) = AsyncStream.makeStream() - resultsProducer.resultsEpilogue = { - signaler.yield() - } - let liveQuery = LiveQuery(resultsProducer: resultsProducer) // exercise the test by setting a valid query fragment liveQuery.queryFragment = queryFragment // wait for results to be produced - await signalStream.first { _ in true } + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == expectedResults } // expect the results match what the producer returned #expect(liveQuery.results == expectedResults) @@ -127,7 +124,7 @@ struct LiveQueryTests: RandomValueGenerating { // MARK: - lastError - @Test + @MainActor @Test mutating func errorFromProducerUpdatesLastErrorAndPreservesResults() async throws { // set up the test by creating a mock results producer let resultsProducer = MockLiveQueryResultsProducer<[String]>() @@ -149,23 +146,17 @@ struct LiveQueryTests: RandomValueGenerating { resultQueue: [.success(initialResults)], ) - let (signalStream, signaler) = AsyncStream.makeStream() - resultsProducer.resultsEpilogue = { - signaler.yield() - } - let liveQuery = LiveQuery(resultsProducer: resultsProducer) // exercise the test by first producing successful results liveQuery.queryFragment = fragment1 - await signalStream.first { _ in true } + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == initialResults } - #expect(liveQuery.results == initialResults) #expect(liveQuery.lastError == nil) // exercise the test by producing an error liveQuery.queryFragment = fragment2 - await signalStream.first { _ in true } + _ = await Observations({ liveQuery.lastError != nil }).first { @Sendable in $0 } // expect the error is captured and previous results are preserved #expect(liveQuery.results == initialResults) @@ -173,7 +164,7 @@ struct LiveQueryTests: RandomValueGenerating { } - @Test + @MainActor @Test mutating func successfulResultAfterErrorClearsLastError() async throws { // set up the test by creating a mock results producer let resultsProducer = MockLiveQueryResultsProducer<[String]>() @@ -195,23 +186,18 @@ struct LiveQueryTests: RandomValueGenerating { resultQueue: [.failure(expectedError)], ) - let (signalStream, signaler) = AsyncStream.makeStream() - resultsProducer.resultsEpilogue = { - signaler.yield() - } - let liveQuery = LiveQuery(resultsProducer: resultsProducer) // exercise the test by first producing an error liveQuery.queryFragment = fragment1 - await signalStream.first { _ in true } + _ = await Observations({ liveQuery.lastError != nil }).first { @Sendable in $0 } #expect(liveQuery.results == nil) #expect(liveQuery.lastError as? ArbitraryError == expectedError) // exercise the test by producing successful results liveQuery.queryFragment = fragment2 - await signalStream.first { _ in true } + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == newResults } // expect the error is cleared #expect(liveQuery.results == newResults) @@ -221,7 +207,7 @@ struct LiveQueryTests: RandomValueGenerating { // MARK: - Scheduling Strategies - @Test + @MainActor @Test mutating func passthroughStrategyProducesResultsForAllFragments() async throws { // set up the test by creating a mock results producer with passthrough strategy let resultsProducer = MockLiveQueryResultsProducer<[String]>() @@ -243,30 +229,26 @@ struct LiveQueryTests: RandomValueGenerating { resultQueue: [.success(results1), .success(results2)], ) - let (signalStream, signaler) = AsyncStream.makeStream() - resultsProducer.resultsEpilogue = { - signaler.yield() - } - let liveQuery = LiveQuery(resultsProducer: resultsProducer) - // exercise the test by setting multiple query fragments - liveQuery.queryFragment = randomAlphanumericString() + // exercise the test by setting multiple query fragments, waiting for each one’s results liveQuery.queryFragment = randomAlphanumericString() + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results1 } + liveQuery.queryFragment = randomAlphanumericString() + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results2 } - // wait for all three results to be produced - for try await _ in signalStream.prefix(3) {} + liveQuery.queryFragment = randomAlphanumericString() + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results3 } // expect all three results were produced #expect( resultsProducer.resultsStub.callArguments == [canonicalFragment1, canonicalFragment2, canonicalFragment3] ) - #expect(liveQuery.results == results3) } - @Test + @MainActor @Test mutating func debounceStrategyDelaysResultProduction() async throws { // set up the test by creating a mock results producer with debounce strategy let resultsProducer = MockLiveQueryResultsProducer<[String]>() @@ -279,11 +261,6 @@ struct LiveQueryTests: RandomValueGenerating { let expectedResults = [randomAlphanumericString()] resultsProducer.resultsStub = ThrowingStub(defaultReturnValue: expectedResults) - let (signalStream, signaler) = AsyncStream.makeStream() - resultsProducer.resultsEpilogue = { - signaler.yield() - } - let liveQuery = LiveQuery(resultsProducer: resultsProducer) // exercise the test by setting a query fragment @@ -295,10 +272,405 @@ struct LiveQueryTests: RandomValueGenerating { #expect(resultsProducer.resultsStub.callArguments.isEmpty) // wait for debounce to complete - await signalStream.first { _ in true } + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == expectedResults } // expect results are now available #expect(liveQuery.results == expectedResults) #expect(resultsProducer.resultsStub.callArguments == [canonicalFragment]) } + + + // MARK: - Result Updates + + @Test + mutating func initializationWithResultUpdatesProducerSetsCorrectDefaults() { + // set up the test by creating a mock result updates producer + let resultUpdatesProducer = StreamResultUpdatesProducer() + resultUpdatesProducer.schedulingStrategyStub = Stub(defaultReturnValue: randomLiveQuerySchedulingStrategy()) + + // exercise the test by initializing a live query + let liveQuery = LiveQuery(resultUpdatesProducer: resultUpdatesProducer) + + // expect the initial state is correct + #expect(liveQuery.queryFragment == "") + #expect(liveQuery.results == nil) + #expect(liveQuery.lastError == nil) + } + + + @MainActor @Test + mutating func eachValueFromResultUpdatesUpdatesResults() async throws { + // set up the test by creating a mock result updates producer that returns a stream + let resultUpdatesProducer = StreamResultUpdatesProducer() + resultUpdatesProducer.schedulingStrategyStub = Stub(defaultReturnValue: .passthrough) + + let canonicalFragment = randomAlphanumericString() + resultUpdatesProducer.canonicalQueryFragmentStub = Stub(defaultReturnValue: canonicalFragment) + + let (resultUpdates, resultUpdatesContinuation) = AsyncThrowingStream<[String], any Error>.makeStream() + resultUpdatesProducer.resultUpdatesStub = Stub(defaultReturnValue: resultUpdates) + + let liveQuery = LiveQuery(resultUpdatesProducer: resultUpdatesProducer) + + let results1 = [randomAlphanumericString()] + let results2 = [randomAlphanumericString()] + + // exercise the test by setting a query fragment and producing two values + liveQuery.queryFragment = randomAlphanumericString() + + // expect each value updates the results + resultUpdatesContinuation.yield(results1) + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results1 } + + resultUpdatesContinuation.yield(results2) + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results2 } + + #expect(resultUpdatesProducer.resultUpdatesStub.callArguments == [canonicalFragment]) + } + + + @MainActor @Test + mutating func changingQueryFragmentCancelsPreviousResultUpdates() async throws { + // set up the test by creating a mock result updates producer whose first stream signals its termination + let resultUpdatesProducer = StreamResultUpdatesProducer() + resultUpdatesProducer.schedulingStrategyStub = Stub(defaultReturnValue: .passthrough) + + let canonicalFragment1 = randomAlphanumericString() + let canonicalFragment2 = randomAlphanumericString() + resultUpdatesProducer.canonicalQueryFragmentStub = Stub( + defaultReturnValue: canonicalFragment2, + returnValueQueue: [canonicalFragment1], + ) + + let (terminationStream, terminationSignaler) = AsyncStream.makeStream() + let (resultUpdates1, resultUpdatesContinuation1) = AsyncThrowingStream<[String], any Error>.makeStream() + resultUpdatesContinuation1.onTermination = { _ in + terminationSignaler.yield() + } + + let (resultUpdates2, _) = AsyncThrowingStream<[String], any Error>.makeStream() + resultUpdatesProducer.resultUpdatesStub = Stub( + defaultReturnValue: resultUpdates2, + returnValueQueue: [resultUpdates1], + ) + + let liveQuery = LiveQuery(resultUpdatesProducer: resultUpdatesProducer) + + let results1 = [randomAlphanumericString()] + liveQuery.queryFragment = randomAlphanumericString() + resultUpdatesContinuation1.yield(results1) + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results1 } + + // exercise the test by changing the query fragment + liveQuery.queryFragment = randomAlphanumericString() + + // expect the first fragment’s result updates are cancelled + await terminationStream.first { @Sendable _ in true } + #expect(resultUpdatesProducer.resultUpdatesStub.callArguments == [canonicalFragment1, canonicalFragment2]) + #expect(liveQuery.results == results1) + } + + + @MainActor @Test + mutating func valuesFromSupersededResultUpdatesAreIgnored() async throws { + // set up the test by creating a mock result updates producer whose first sequence ignores cancellation and + // produces a stale value when the test opens a gate + let resultUpdatesProducer = ClosureResultUpdatesProducer() + resultUpdatesProducer.schedulingStrategyStub = Stub(defaultReturnValue: .passthrough) + resultUpdatesProducer.canonicalQueryFragmentStub = Stub( + defaultReturnValue: randomAlphanumericString(), + returnValueQueue: [randomAlphanumericString()], + ) + + let results1 = [randomAlphanumericString()] + let staleResults = [randomAlphanumericString()] + let results2 = [randomAlphanumericString()] + + let (waitingStream, waitingSignaler) = AsyncStream.makeStream() + let (gateStream, gateSignaler) = AsyncStream.makeStream() + let (handledStream, handledSignaler) = AsyncStream.makeStream() + let resultUpdates1 = ClosureAsyncSequence<[String]> { index in + switch index { + case 0: + return results1 + case 1: + waitingSignaler.yield() + await Task { await gateStream.first { @Sendable _ in true } }.value + return staleResults + default: + // the live query asks for the next value only after handling the stale one + handledSignaler.yield() + return nil + } + } + + let resultUpdates2 = ClosureAsyncSequence<[String]> { index in + return index == 0 ? results2 : nil + } + resultUpdatesProducer.resultUpdatesStub = Stub( + defaultReturnValue: resultUpdates2, + returnValueQueue: [resultUpdates1], + ) + + let liveQuery = LiveQuery(resultUpdatesProducer: resultUpdatesProducer) + + liveQuery.queryFragment = randomAlphanumericString() + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results1 } + await waitingStream.first { @Sendable _ in true } + + // exercise the test by changing the query fragment, then letting the first sequence produce a stale value + liveQuery.queryFragment = randomAlphanumericString() + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results2 } + + gateSignaler.yield() + await handledStream.first { @Sendable _ in true } + + // expect the stale value was ignored + #expect(liveQuery.results == results2) + #expect(liveQuery.lastError == nil) + } + + + @MainActor @Test + mutating func errorFromResultUpdatesSetsLastErrorUntilNextFragmentProducesResults() async throws { + // set up the test by creating a mock result updates producer that returns two streams + let resultUpdatesProducer = StreamResultUpdatesProducer() + resultUpdatesProducer.schedulingStrategyStub = Stub(defaultReturnValue: .passthrough) + + let canonicalFragment1 = randomAlphanumericString() + let canonicalFragment2 = randomAlphanumericString() + resultUpdatesProducer.canonicalQueryFragmentStub = Stub( + defaultReturnValue: canonicalFragment2, + returnValueQueue: [canonicalFragment1], + ) + + let (resultUpdates1, resultUpdatesContinuation1) = AsyncThrowingStream<[String], any Error>.makeStream() + let (resultUpdates2, resultUpdatesContinuation2) = AsyncThrowingStream<[String], any Error>.makeStream() + resultUpdatesProducer.resultUpdatesStub = Stub( + defaultReturnValue: resultUpdates2, + returnValueQueue: [resultUpdates1], + ) + + let liveQuery = LiveQuery(resultUpdatesProducer: resultUpdatesProducer) + + let results1 = [randomAlphanumericString()] + liveQuery.queryFragment = randomAlphanumericString() + resultUpdatesContinuation1.yield(results1) + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results1 } + + // exercise the test by making the first stream throw an error + let expectedError = randomError() + resultUpdatesContinuation1.finish(throwing: expectedError) + _ = await Observations({ liveQuery.lastError != nil }).first { @Sendable in $0 } + + // expect the error is captured and the results are preserved + #expect(liveQuery.results == results1) + #expect(liveQuery.lastError as? ArbitraryError == expectedError) + + // exercise the test by changing the query fragment and producing results + let results2 = [randomAlphanumericString()] + liveQuery.queryFragment = randomAlphanumericString() + resultUpdatesContinuation2.yield(results2) + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results2 } + + // expect the error is cleared + #expect(liveQuery.lastError == nil) + } + + + @MainActor @Test + mutating func cancellationOfSupersededResultUpdatesIsNotReportedAsError() async throws { + // set up the test by creating a mock result updates producer whose first sequence throws when cancelled + let resultUpdatesProducer = ClosureResultUpdatesProducer() + resultUpdatesProducer.schedulingStrategyStub = Stub(defaultReturnValue: .passthrough) + resultUpdatesProducer.canonicalQueryFragmentStub = Stub( + defaultReturnValue: randomAlphanumericString(), + returnValueQueue: [randomAlphanumericString()], + ) + + let results1 = [randomAlphanumericString()] + let results2 = [randomAlphanumericString()] + + let (waitingStream, waitingSignaler) = AsyncStream.makeStream() + let (cancellationStream, cancellationSignaler) = AsyncStream.makeStream() + let resultUpdates1 = ClosureAsyncSequence<[String]> { index in + guard index > 0 else { + return results1 + } + + defer { + cancellationSignaler.yield() + } + + waitingSignaler.yield() + try await Task.sleep(for: .seconds(3600)) + return nil + } + + let resultUpdates2 = ClosureAsyncSequence<[String]> { index in + return index == 0 ? results2 : nil + } + resultUpdatesProducer.resultUpdatesStub = Stub( + defaultReturnValue: resultUpdates2, + returnValueQueue: [resultUpdates1], + ) + + let liveQuery = LiveQuery(resultUpdatesProducer: resultUpdatesProducer) + + liveQuery.queryFragment = randomAlphanumericString() + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results1 } + await waitingStream.first { @Sendable _ in true } + + // exercise the test by changing the query fragment + liveQuery.queryFragment = randomAlphanumericString() + await cancellationStream.first { @Sendable _ in true } + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results2 } + + // expect the cancellation wasn’t reported as an error + #expect(liveQuery.lastError == nil) + } + + + @MainActor @Test + mutating func supersededResultsProducerCallIsCancelledAndItsResultsAreIgnored() async throws { + // set up the test by creating a mock results producer whose first call waits for a gate, ignoring + // cancellation, and then reports whether it was cancelled + let resultsProducer = MockLiveQueryResultsProducer<[String]>() + resultsProducer.schedulingStrategyStub = Stub(defaultReturnValue: .passthrough) + + let canonicalFragment1 = randomAlphanumericString() + let canonicalFragment2 = randomAlphanumericString() + resultsProducer.canonicalQueryFragmentStub = Stub( + defaultReturnValue: canonicalFragment2, + returnValueQueue: [canonicalFragment1], + ) + + // the second call reaches the stub first, so it gets the queued results + let results1 = [randomAlphanumericString()] + let results2 = [randomAlphanumericString()] + resultsProducer.resultsStub = ThrowingStub( + defaultReturnValue: results1, + resultQueue: [.success(results2)], + ) + + let callCounter = CallCounter() + let (waitingStream, waitingSignaler) = AsyncStream.makeStream() + let (gateStream, gateSignaler) = AsyncStream.makeStream() + let (cancellationStream, cancellationSignaler) = AsyncStream.makeStream() + resultsProducer.resultsPrologue = { + guard callCounter.increment() == 0 else { + return + } + + waitingSignaler.yield() + await Task { await gateStream.first { @Sendable _ in true } }.value + cancellationSignaler.yield(Task.isCancelled) + } + + let (epilogueStream, epilogueSignaler) = AsyncStream.makeStream() + resultsProducer.resultsEpilogue = { + epilogueSignaler.yield() + } + + let liveQuery = LiveQuery(resultsProducer: resultsProducer) + + liveQuery.queryFragment = randomAlphanumericString() + await waitingStream.first { @Sendable _ in true } + + // exercise the test by changing the query fragment while the first call is running + liveQuery.queryFragment = randomAlphanumericString() + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results2 } + + // let the first call finish + gateSignaler.yield() + let wasCancelled = await cancellationStream.first { @Sendable _ in true } + for await _ in epilogueStream.prefix(2) {} + + // expect the first call was cancelled and its results were ignored + #expect(wasCancelled == true) + #expect(resultsProducer.resultsStub.callArguments == [canonicalFragment2, canonicalFragment1]) + #expect(liveQuery.results == results2) + #expect(liveQuery.lastError == nil) + } + + + @MainActor @Test + mutating func releasingLiveQueryCancelsResultUpdates() async throws { + // set up the test by creating a mock result updates producer whose sequence waits for a gate, ignoring + // cancellation, and then reports whether it was cancelled + let resultUpdatesProducer = ClosureResultUpdatesProducer() + resultUpdatesProducer.schedulingStrategyStub = Stub(defaultReturnValue: .passthrough) + resultUpdatesProducer.canonicalQueryFragmentStub = Stub(defaultReturnValue: randomAlphanumericString()) + + let results1 = [randomAlphanumericString()] + let results2 = [randomAlphanumericString()] + + let (waitingStream, waitingSignaler) = AsyncStream.makeStream() + let (gateStream, gateSignaler) = AsyncStream.makeStream() + let (cancellationStream, cancellationSignaler) = AsyncStream.makeStream() + resultUpdatesProducer.resultUpdatesStub = Stub( + defaultReturnValue: ClosureAsyncSequence<[String]> { index in + switch index { + case 0: + return results1 + case 1: + waitingSignaler.yield() + await Task { await gateStream.first { @Sendable _ in true } }.value + cancellationSignaler.yield(Task.isCancelled) + return results2 + default: + return nil + } + } + ) + + weak var weakLiveQuery: LiveQuery<[String]>? + do { + let liveQuery = LiveQuery(resultUpdatesProducer: resultUpdatesProducer) + weakLiveQuery = liveQuery + + liveQuery.queryFragment = randomAlphanumericString() + _ = await Observations({ liveQuery.results }).first { @Sendable in $0 == results1 } + await waitingStream.first { @Sendable _ in true } + } + + // exercise the test by releasing the live query, then letting the sequence continue + #expect(weakLiveQuery == nil) + gateSignaler.yield() + + // expect the sequence’s iteration was cancelled + let wasCancelled = await cancellationStream.first { @Sendable _ in true } + #expect(wasCancelled == true) + } +} + + +/// A mock result updates producer whose result updates are async throwing streams. +private typealias StreamResultUpdatesProducer = MockLiveQueryResultUpdatesProducer< + [String], AsyncThrowingStream<[String], any Error> +> + + +/// A mock result updates producer whose result updates are closure async sequences. +private typealias ClosureResultUpdatesProducer = MockLiveQueryResultUpdatesProducer< + [String], ClosureAsyncSequence<[String]> +> + + +/// A thread-safe counter that tests use to tell calls apart. +private final class CallCounter: Sendable { + /// A mutex that synchronizes access to the count. + private let count = Mutex(0) + + + /// Increments the count, returning its value before the increment. + func increment() -> Int { + return count.withLock { count in + defer { + count += 1 + } + + return count + } + } } diff --git a/Tests/DevFoundationTests/Testing Helpers/ClosureAsyncSequence.swift b/Tests/DevFoundationTests/Testing Helpers/ClosureAsyncSequence.swift new file mode 100644 index 0000000..ddb8f04 --- /dev/null +++ b/Tests/DevFoundationTests/Testing Helpers/ClosureAsyncSequence.swift @@ -0,0 +1,46 @@ +// +// ClosureAsyncSequence.swift +// DevFoundation +// +// Created by Prachi Gauriar on 11/24/2026. +// + +import Foundation + +/// An async sequence whose iterator calls a closure to get each element. +/// +/// Tests use this sequence to control exactly what happens each time a sequence is asked for its next element, +/// including ignoring cancellation. Because a consumer only asks for the next element after it’s handled the previous +/// one, a call to the closure also tells the test that the previous element was handled. +struct ClosureAsyncSequence: AsyncSequence, Sendable where Element: Sendable { + typealias Failure = any Error + + + /// The closure that returns each element. + /// + /// The closure’s parameter is the zero-based index of the call. Return `nil` to end the sequence. + let nextElement: @Sendable (Int) async throws -> Element? + + + func makeAsyncIterator() -> AsyncIterator { + return AsyncIterator(nextElement: nextElement) + } + + + struct AsyncIterator: AsyncIteratorProtocol { + typealias Failure = any Error + + + let nextElement: @Sendable (Int) async throws -> Element? + var index = 0 + + + mutating func next() async throws -> Element? { + defer { + index += 1 + } + + return try await nextElement(index) + } + } +} diff --git a/Tests/DevFoundationTests/Testing Helpers/MockLiveQueryResultUpdatesProducer.swift b/Tests/DevFoundationTests/Testing Helpers/MockLiveQueryResultUpdatesProducer.swift new file mode 100644 index 0000000..a5c86c9 --- /dev/null +++ b/Tests/DevFoundationTests/Testing Helpers/MockLiveQueryResultUpdatesProducer.swift @@ -0,0 +1,33 @@ +// +// MockLiveQueryResultUpdatesProducer.swift +// DevFoundation +// +// Created by Prachi Gauriar on 11/24/2026. +// + +import DevTesting +import Foundation + +@testable import DevFoundation + +final class MockLiveQueryResultUpdatesProducer: LiveQueryResultUpdatesProducer +where Results: Sendable, ResultUpdates: AsyncSequence & Sendable { + nonisolated(unsafe) var schedulingStrategyStub = Stub() + nonisolated(unsafe) var canonicalQueryFragmentStub = Stub() + nonisolated(unsafe) var resultUpdatesStub: Stub! + + + var schedulingStrategy: LiveQuerySchedulingStrategy { + schedulingStrategyStub() + } + + + func canonicalQueryFragment(from queryFragment: String) -> String? { + canonicalQueryFragmentStub(queryFragment) + } + + + func resultUpdates(forQueryFragment queryFragment: String) -> ResultUpdates { + resultUpdatesStub(queryFragment) + } +} diff --git a/Tests/DevFoundationTests/Testing Helpers/MockLiveQueryResultsProducer.swift b/Tests/DevFoundationTests/Testing Helpers/MockLiveQueryResultsProducer.swift index ffa5eae..58a8eda 100644 --- a/Tests/DevFoundationTests/Testing Helpers/MockLiveQueryResultsProducer.swift +++ b/Tests/DevFoundationTests/Testing Helpers/MockLiveQueryResultsProducer.swift @@ -13,6 +13,7 @@ import Foundation final class MockLiveQueryResultsProducer: LiveQueryResultsProducer where Results: Sendable { nonisolated(unsafe) var schedulingStrategyStub = Stub() nonisolated(unsafe) var canonicalQueryFragmentStub = Stub() + nonisolated(unsafe) var resultsPrologue: (() async throws -> Void)? nonisolated(unsafe) var resultsStub = ThrowingStub() nonisolated(unsafe) var resultsEpilogue: (() async throws -> Void)? @@ -33,6 +34,8 @@ final class MockLiveQueryResultsProducer: LiveQueryResultsProducer wher Task { try? await epilogue() } } } + + try await resultsPrologue?() return try resultsStub(queryFragment) } }