import Foundation import XCTest @testable import OldFella extension ATProtoServiceTests { func testNotificationPostHydrationRunsThreeRequestsAtOnceAndPreservesOrder() async throws { let suiteName = "OldFellaNotificationConcurrencyTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) let configuration = URLSessionConfiguration.ephemeral configuration.protocolClasses = [RefreshRaceURLProtocol.self] let session = URLSession(configuration: configuration) let expiry = Int(Date().addingTimeInterval(3600).timeIntervalSince1970) let payload = Data("{\"exp\":\(expiry)}".utf8).base64EncodedString().replacingOccurrences(of: "=", with: "") let token = "header.\(payload).signature" let started = expectation(description: "Three post requests started") started.expectedFulfillmentCount = 3 let gate = NotificationHydrationGate(started: started) let notifications = concurrentNotifications RefreshRaceURLProtocol.handler = { request in try self.concurrentHydrationResponse(request, token: token, notifications: notifications, gate: gate) } defer { gate.resume() RefreshRaceURLProtocol.handler = nil session.invalidateAndCancel() defaults.removePersistentDomain(forName: suiteName) } let service = ATProtoBlueskyService(defaults: defaults, session: session) _ = try await service.signIn(handle: "reader.example", appPassword: "test-password", authFactorToken: nil) let loading = Task { try await service.loadNotifications(cursor: nil) } await fulfillment(of: [started], timeout: 3) XCTAssertEqual(gate.requestCount, 3) XCTAssertEqual(gate.maximumConcurrentRequests, 3) gate.resume() let page = try await loading.value XCTAssertEqual(gate.requestCount, 5) XCTAssertEqual(gate.maximumConcurrentRequests, 3) XCTAssertEqual(page.notifications.map(\.id), notifications.compactMap { $0["uri"] as? String }) XCTAssertTrue(page.notifications.allSatisfy { $0.relatedPost != nil && $0.parentPost != nil }) XCTAssertTrue(page.notifications.allSatisfy { $0.author.isFollowing && $0.isFollowedBy }) try await service.signOut() } private func concurrentHydrationResponse( _ request: URLRequest, token: String, notifications: [[String: Any]], gate: NotificationHydrationGate ) throws -> (Int, Data) { if let response = try concurrentHydrationResponseIdentity( request, token: token, notifications: notifications, gate: gate) { return response } return try concurrentHydrationResponseAction(request, token: token, notifications: notifications, gate: gate) } private func concurrentHydrationResponseIdentity( _ request: URLRequest, token: String, notifications: [[String: Any]], gate: NotificationHydrationGate ) throws -> (Int, Data)? { switch request.url?.path { case "/xrpc/com.atproto.identity.resolveHandle": return (200, Data("{\"did\":\"did:plc:reader\"}".utf8)) case "/did:plc:reader": return ( 200, Data( ("{\"id\":\"did:plc:reader\",\"service\":[{\"id\":\"#atproto_pds\"," + "\"type\":\"AtprotoPersonalDataServer\"," + "\"serviceEndpoint\":\"https://pds.example.test\"}]}") .utf8) ) case "/xrpc/com.atproto.server.createSession": return ( 200, Data( ("{\"handle\":\"reader.example\",\"did\":\"did:plc:reader\"," + "\"accessJwt\":\"\(token)\",\"refreshJwt\":\"refresh-token\"}") .utf8) ) case "/xrpc/app.bsky.actor.getProfile": return (200, Data("{\"did\":\"did:plc:reader\",\"handle\":\"reader.example\"}".utf8)) default: return nil } } private func concurrentHydrationResponseAction( _ request: URLRequest, token: String, notifications: [[String: Any]], gate: NotificationHydrationGate ) throws -> (Int, Data) { switch request.url?.path { case "/xrpc/app.bsky.notification.listNotifications": return (200, try JSONSerialization.data(withJSONObject: ["notifications": notifications])) case "/xrpc/app.bsky.feed.getPosts": gate.wait() let uris = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)?.queryItems?.filter { $0.name == "uris" }.compactMap(\.value) ?? [] let posts: [[String: Any]] = uris.reversed().map { uri in [ "uri": uri, "cid": "post-cid", "author": ["did": "did:plc:reader", "handle": "reader.example"], "record": ["text": "Post"], "indexedAt": "2025-01-02T03:04:05.000Z" ] } return (200, try JSONSerialization.data(withJSONObject: ["posts": posts])) default: return (404, Data("{\"error\":\"NotFound\"}".utf8)) } } private var concurrentNotifications: [[String: Any]] { (0..<40).map { index in [ "uri": "at://did:plc:actor/app.bsky.feed.post/reply-\(index)", "cid": "notice-cid", "reason": "reply", "reasonSubject": "at://did:plc:reader/app.bsky.feed.post/root-\(index)", "record": [ "$type": "app.bsky.feed.post", "text": "Reply", "createdAt": "2025-01-02T03:04:05.000Z", "reply": [ "root": ["uri": "at://did:plc:reader/app.bsky.feed.post/root-\(index)", "cid": "root-cid"], "parent": [ "uri": "at://did:plc:reader/app.bsky.feed.post/parent-\(index)", "cid": "parent-cid" ] ] ], "indexedAt": "2025-01-02T03:04:05.000Z", "isRead": true, "author": [ "did": "did:plc:actor", "handle": "actor.example", "viewer": ["following": "at://following", "followedBy": "at://followed-by"] ] ] } } }