@@ -7,17 +7,27 @@ import FoundationNetworking
77/// Protocol for observing network request lifecycle events.
88///
99/// Implement this protocol to add logging, analytics, or request tracking.
10- /// The `context` parameter allows passing correlation data (request ID, start time, etc.)
11- /// between `willSendRequest` and the completion callbacks.
10+ ///
11+ /// ## Context Lifecycle
12+ /// The `Context` associated type allows passing correlation data (request ID, start time, etc.)
13+ /// through the request lifecycle:
14+ /// 1. `willSendRequest` is called before the request starts and returns a `Context` value
15+ /// 2. `didReceiveResponse` is always called with the raw response data (useful for debugging)
16+ /// 3. `didFail` is called additionally if the request processing fails (network, HTTP status, or decoding error)
17+ /// 4. If the observer is deallocated before the request completes, the context is discarded
18+ /// and no completion callback is invoked
1219public protocol NetworkObserver : AnyObject , Sendable {
1320 associatedtype Context : Sendable
1421
1522 /// Called immediately before a request is sent.
1623 /// - Parameter request: The URLRequest about to be sent
17- /// - Returns: Context to be passed to `didReceiveResponse` or `didFail`
24+ /// - Returns: Context to be passed to `didReceiveResponse` and optionally `didFail`
1825 func willSendRequest( _ request: URLRequest ) -> Context
1926
20- /// Called when a response is received.
27+ /// Called when a response is received from the server.
28+ ///
29+ /// This is always called with the raw response data, even if processing subsequently fails.
30+ /// This allows observers to inspect the actual response for debugging purposes.
2131 /// - Parameters:
2232 /// - request: The original request
2333 /// - response: The URL response (may be HTTPURLResponse)
@@ -26,9 +36,11 @@ public protocol NetworkObserver: AnyObject, Sendable {
2636 func didReceiveResponse( for request: URLRequest , response: URLResponse ? , data: Data ? , context: Context )
2737
2838 /// Called when a request fails with an error.
39+ ///
40+ /// Called after `didReceiveResponse` if processing determines the request failed.
2941 /// - Parameters:
3042 /// - request: The original request
31- /// - error: The error that occurred
43+ /// - error: The error that occurred (may be network, HTTP status, or decoding error)
3244 /// - context: Value returned from `willSendRequest`
3345 func didFail( request: URLRequest , error: Error , context: Context )
3446}
0 commit comments