Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Store leak when async effect is in flight #2643

Merged
merged 5 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 45 additions & 38 deletions Sources/ComposableArchitecture/Store.swift
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,10 @@ public final class Store<State, Action> {
for id in self.children.keys {
self.invalidateChild(id: id)
}
self.effectCancellables.values.forEach { cancellable in
cancellable.cancel()
}
self.effectCancellables.removeAll()
}

fileprivate func invalidateChild(id: ScopeID<State, Action>) {
Expand Down Expand Up @@ -526,14 +530,14 @@ public final class Store<State, Action> {
defer { index += 1 }
let action = self.bufferedActions[index]
let effect = self.reducer.reduce(into: &currentState, action: action)
let uuid = UUID()

switch effect.operation {
case .none:
break
case let .publisher(publisher):
var didComplete = false
let boxedTask = Box<Task<Void, Never>?>(wrappedValue: nil)
let uuid = UUID()
let effectCancellable = withEscapedDependencies { continuation in
publisher
.handleEvents(
Expand Down Expand Up @@ -571,45 +575,48 @@ public final class Store<State, Action> {
}
case let .run(priority, operation):
withEscapedDependencies { continuation in
tasks.wrappedValue.append(
Task(priority: priority) { @MainActor in
#if DEBUG
let isCompleted = LockIsolated(false)
defer { isCompleted.setValue(true) }
#endif
await operation(
Send { effectAction in
#if DEBUG
if isCompleted.value {
runtimeWarn(
"""
An action was sent from a completed effect:

Action:
\(debugCaseOutput(effectAction))

Effect returned from:
\(debugCaseOutput(action))

Avoid sending actions using the 'send' argument from 'Effect.run' after \
the effect has completed. This can happen if you escape the 'send' \
argument in an unstructured context.

To fix this, make sure that your 'run' closure does not return until \
you're done calling 'send'.
"""
)
}
#endif
if let task = continuation.yield({
self.send(effectAction, originatingFrom: action)
}) {
tasks.wrappedValue.append(task)
let task = Task(priority: priority) { @MainActor [weak self] in
#if DEBUG
let isCompleted = LockIsolated(false)
defer { isCompleted.setValue(true) }
#endif
await operation(
Send { effectAction in
#if DEBUG
if isCompleted.value {
runtimeWarn(
"""
An action was sent from a completed effect:

Action:
\(debugCaseOutput(effectAction))

Effect returned from:
\(debugCaseOutput(action))

Avoid sending actions using the 'send' argument from 'Effect.run' after \
the effect has completed. This can happen if you escape the 'send' \
argument in an unstructured context.

To fix this, make sure that your 'run' closure does not return until \
you're done calling 'send'.
"""
)
}
#endif
if let task = continuation.yield({
self?.send(effectAction, originatingFrom: action)
}) {
tasks.wrappedValue.append(task)
}
)
}
)
}
)
self?.effectCancellables[uuid] = nil
}
tasks.wrappedValue.append(task)
self.effectCancellables[uuid] = AnyCancellable {
task.cancel()
}
}
}
}
Expand Down
80 changes: 79 additions & 1 deletion Tests/ComposableArchitectureTests/StoreTests.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Combine
@_spi(Internals) import ComposableArchitecture
@_spi(Internals) @_spi(Logging) import ComposableArchitecture
import XCTest

@MainActor
Expand Down Expand Up @@ -931,6 +931,84 @@ final class StoreTests: BaseTCATestCase {
store.send(.child(.dismiss))
_ = (childViewStore1, childViewStore2, childStore1, childStore2)
}

func testStoreDeinit() {
Logger.shared.isEnabled = true
defer { Logger.shared.isEnabled = false }
Logger.shared.clear()
do {
let store = Store<Void, Void>(initialState: ()) {}
_ = store
}

XCTAssertEqual(
Logger.shared.logs,
[
"Store<(), ()>.init",
"Store<(), ()>.deinit",
]
)
}

func testStoreDeinit_RunningEffect() async {
Logger.shared.isEnabled = true
defer { Logger.shared.isEnabled = false }
Logger.shared.clear()

let effectFinished = self.expectation(description: "Effect finished")
do {
let store = Store<Void, Void>(initialState: ()) {
Reduce { state, _ in
.run { _ in
try? await Task.never()
effectFinished.fulfill()
}
}
}
store.send(())
_ = store
}

XCTAssertEqual(
Logger.shared.logs,
[
"Store<(), ()>.init",
"Store<(), ()>.deinit",
]
)
await self.fulfillment(of: [effectFinished], timeout: 0.5)
}

func testStoreDeinit_RunningCombineEffect() async {
Logger.shared.isEnabled = true
defer { Logger.shared.isEnabled = false }
Logger.shared.clear()

let effectFinished = self.expectation(description: "Effect finished")
do {
let store = Store<Void, Void>(initialState: ()) {
Reduce { state, _ in
.publisher {
Empty(completeImmediately: false)
.handleEvents(receiveCancel: {
effectFinished.fulfill()
})
}
}
}
store.send(())
_ = store
}

XCTAssertEqual(
Logger.shared.logs,
[
"Store<(), ()>.init",
"Store<(), ()>.deinit",
]
)
await self.fulfillment(of: [effectFinished], timeout: 0.5)
}
}

private struct Count: TestDependencyKey {
Expand Down