Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Alerts/OpsEventStream.swift3// Description: The streaming loader of the wallet's two Server-Sent-Events routes (alert counters, research-job log). It runs the request the Core built (session cookie, no cookie jar), refuses redirects, and feeds the Core's incremental parser. It owns no reconnection policy: callers decide when to reconnect and stop the stream by cancelling their task.4import Foundation5import SPWalletCore67/// A session cookie must never follow a redirect to another host.8private final class OpsNoRedirect: NSObject, URLSessionTaskDelegate, Sendable {9 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest) async -> URLRequest? { nil }10}1112enum OpsEventStream {13 private static let session: URLSession = {14 let c = URLSessionConfiguration.ephemeral15 c.httpCookieStorage = nil; c.httpShouldSetCookies = false; c.urlCache = nil16 c.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData17 // the server ends every stream by itself after ten minutes; a silent research job sends nothing in between18 c.timeoutIntervalForRequest = 660; c.timeoutIntervalForResource = 72019 c.waitsForConnectivity = false20 return URLSession(configuration: c, delegate: OpsNoRedirect(), delegateQueue: nil)21 }()2223 /// The events of one connection. Finishes when the server closes the stream; throws an `APIError` when the connection fails or is refused.24 static func events(_ request: URLRequest) -> AsyncThrowingStream<ServerSentEvent, Error> {25 AsyncThrowingStream { continuation in26 let task = Task {27 do {28 let (bytes, response) = try await session.bytes(for: request)29 guard let http = response as? HTTPURLResponse else { throw APIError.offline("réponse sans en-tête HTTP") }30 guard http.statusCode == 200 else { throw refusal(http.statusCode) }31 var parser = ServerSentEventParser(); var chunk = Data()32 for try await byte in bytes {33 chunk.append(byte)34 guard byte == 0x0a else { continue }35 for e in parser.feed(chunk) { continuation.yield(e) }36 chunk.removeAll(keepingCapacity: true)37 }38 continuation.finish()39 } catch is CancellationError { continuation.finish() }40 catch let e as URLError where e.code == .cancelled { continuation.finish() }41 catch let e as URLError { continuation.finish(throwing: APIError.offline(e.localizedDescription)) }42 catch { continuation.finish(throwing: error) }43 }44 continuation.onTermination = { _ in task.cancel() }45 }46 }4748 /// The same events, for as long as `keep` stays true (checked every second on the main actor): used to drop a stream when the app goes to the background.49 static func events(_ request: URLRequest, while keep: @escaping @MainActor @Sendable () -> Bool) -> AsyncThrowingStream<ServerSentEvent, Error> {50 AsyncThrowingStream { continuation in51 let reader = Task {52 do { for try await e in events(request) { continuation.yield(e) }; continuation.finish() } catch { continuation.finish(throwing: error) }53 }54 let watchdog = Task { @MainActor in55 while !Task.isCancelled {56 if !keep() { reader.cancel(); continuation.finish(); return }57 try? await Task.sleep(for: .seconds(1))58 }59 }60 continuation.onTermination = { _ in reader.cancel(); watchdog.cancel() }61 }62 }6364 private static func refusal(_ status: Int) -> APIError {65 switch status {66 case 401: APIError(status: 401, code: "unauthenticated", message: "")67 case 429: APIError(status: 429, code: "too_many_streams", message: "Trop de flux en direct ouverts à la fois sur ce portefeuille. Fermez-en un (autre appareil, autre fenêtre) ou patientez.")68 case 404: APIError(status: 404, code: "not_found", message: "Flux introuvable sur le serveur.")69 case 300..<400: APIError(status: status, code: "redirect_refused", message: "Le serveur a répondu par une redirection : refusée, la session n’est jamais envoyée ailleurs.")70 default: APIError(status: status, code: "stream_failed", message: "Le flux en direct a été refusé par le serveur (HTTP \(status)).")71 }72 }73}7475/// Exponential backoff with jitter for the reconnection of a stream: 2 s, 4 s, 8 s… capped at one minute.76struct OpsBackoff {77 private(set) var attempt = 078 mutating func reset() { attempt = 0 }79 mutating func next() -> Duration {80 attempt = min(attempt + 1, 6)81 let base = min(60.0, pow(2.0, Double(attempt)))82 return .milliseconds(Int((base + Double.random(in: 0...1)) * 1000))83 }84}85