Skip to content

Improve EventEmitter implementation #241

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

Merged
merged 2 commits into from
Feb 15, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
58 changes: 48 additions & 10 deletions Sources/Auth/AuthClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,29 @@ import Foundation
import FoundationNetworking
#endif

public final class AuthStateChangeListenerHandle {
var onCancel: (@Sendable () -> Void)?

public func cancel() {
onCancel?()
onCancel = nil
}

deinit {
cancel()
}
}

public typealias AuthStateChangeListener = @Sendable (
_ event: AuthChangeEvent,
_ session: Session?
) -> Void

public actor AuthClient {
/// FetchHandler is a type alias for asynchronous network request handling.
public typealias FetchHandler =
@Sendable (_ request: URLRequest) async throws -> (Data, URLResponse)
public typealias FetchHandler = @Sendable (
_ request: URLRequest
) async throws -> (Data, URLResponse)

/// Configuration struct represents the client configuration.
public struct Configuration: Sendable {
Expand Down Expand Up @@ -150,7 +169,7 @@ public actor AuthClient {
sessionManager: .live,
codeVerifierStorage: .live,
api: api,
eventEmitter: .live,
eventEmitter: EventEmitter(),
sessionStorage: .live,
logger: configuration.logger
)
Expand Down Expand Up @@ -187,19 +206,38 @@ public actor AuthClient {
)
}

/// Listen for auth state changes.
///
/// An `.initialSession` is always emitted when this method is called.
@discardableResult
public func onAuthStateChange(
_ listener: @escaping AuthStateChangeListener
) -> AuthStateChangeListenerHandle {
let handle = eventEmitter.attachListener(listener)
Task {
await emitInitialSession(forHandle: handle)
}
return handle
}

/// Listen for auth state changes.
///
/// An `.initialSession` is always emitted when this method is called.
public var authStateChanges: AsyncStream<(
event: AuthChangeEvent,
session: Session?
)> {
let (id, stream) = eventEmitter.attachListener()
logger?.debug("auth state change listener with id '\(id.uuidString)' attached.")
let (stream, continuation) = AsyncStream<(
event: AuthChangeEvent,
session: Session?
)>.makeStream()

let handle = onAuthStateChange { event, session in
continuation.yield((event, session))
}

Task { [id] in
await emitInitialSession(forStreamWithID: id)
logger?.debug("initial session for listener with id '\(id.uuidString)' emitted.")
continuation.onTermination = { _ in
handle.cancel()
}

return stream
Expand Down Expand Up @@ -884,9 +922,9 @@ public actor AuthClient {
return session
}

private func emitInitialSession(forStreamWithID id: UUID) async {
private func emitInitialSession(forHandle handle: AuthStateChangeListenerHandle) async {
let session = try? await session
eventEmitter.emit(.initialSession, session, id)
eventEmitter.emit(.initialSession, session: session, handle: handle)
}

private func prepareForPKCE() -> (codeChallenge: String?, codeChallengeMethod: String?) {
Expand Down
92 changes: 40 additions & 52 deletions Sources/Auth/Internal/EventEmitter.swift
Original file line number Diff line number Diff line change
@@ -1,62 +1,50 @@
import ConcurrencyExtras
import Foundation

struct EventEmitter: Sendable {
var attachListener: @Sendable () -> (
id: UUID,
stream: AsyncStream<(event: AuthChangeEvent, session: Session?)>
)
var emit: @Sendable (_ event: AuthChangeEvent, _ session: Session?, _ id: UUID?) -> Void
}
class EventEmitter: @unchecked Sendable {
let listeners = LockIsolated<[ObjectIdentifier: AuthStateChangeListener]>([:])

func attachListener(_ listener: @escaping AuthStateChangeListener)
-> AuthStateChangeListenerHandle
{
let handle = AuthStateChangeListenerHandle()
let key = ObjectIdentifier(handle)

handle.onCancel = { [weak self] in
self?.listeners.withValue {
$0[key] = nil
}
}

extension EventEmitter {
func emit(_ event: AuthChangeEvent, session: Session?) {
emit(event, session, nil)
listeners.withValue {
$0[key] = listener
}

return handle
}
}

extension EventEmitter {
static var live: Self = {
let continuations = LockIsolated(
[UUID: AsyncStream<(event: AuthChangeEvent, session: Session?)>.Continuation]()
func emit(
_ event: AuthChangeEvent,
session: Session?,
handle: AuthStateChangeListenerHandle? = nil
) {
NotificationCenter.default.post(
name: AuthClient.didChangeAuthStateNotification,
object: nil,
userInfo: [
AuthClient.authChangeEventInfoKey: event,
AuthClient.authChangeSessionInfoKey: session as Any,
]
)

return Self(
attachListener: {
let id = UUID()

let (stream, continuation) = AsyncStream<(event: AuthChangeEvent, session: Session?)>
.makeStream()

continuation.onTermination = { [id] _ in
continuations.withValue {
$0[id] = nil
}
}

continuations.withValue {
$0[id] = continuation
}

return (id, stream)
},
emit: { event, session, id in
NotificationCenter.default.post(
name: AuthClient.didChangeAuthStateNotification,
object: nil,
userInfo: [
AuthClient.authChangeEventInfoKey: event,
AuthClient.authChangeSessionInfoKey: session as Any,
]
)
if let id {
continuations.value[id]?.yield((event, session))
} else {
for continuation in continuations.value.values {
continuation.yield((event, session))
}
}
let listeners = listeners.value

if let handle {
listeners[ObjectIdentifier(handle)]?(event, session)
} else {
for listener in listeners.values {
listener(event, session)
}
)
}()
}
}
}
Loading