1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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"]
]
]
}
}
}