p2p-swift / Tests / IrdP2PSignalingTests / Helpers / Fakes.swift
793 words
  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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
import Foundation
import Testing
@testable import IrdP2PSignaling
import IrdP2PCrypto

func fixture(_ name: String) throws -> Data {
    let url = try #require(Bundle.module.url(forResource: name, withExtension: "json", subdirectory: "Fixtures"))
    return try Data(contentsOf: url)
}

/// Polls until `condition` holds or `timeout` (real time) elapses.
func eventually(timeout: Duration = .seconds(3), _ condition: @Sendable () async -> Bool) async -> Bool {
    let deadline = ContinuousClock.now + timeout
    while ContinuousClock.now < deadline {
        if await condition() { return true }
        try? await Task.sleep(for: .milliseconds(5))
    }
    return await condition()
}

/// Takes the next event from a stream, failing after `timeout` real time.
func next<T: Sendable>(_ iterator: inout AsyncStream<T>.AsyncIterator, timeout: Duration = .seconds(3)) async -> T? {
    // AsyncStream iterators are not Sendable; race the wait against a timer by polling.
    await withTaskGroup(of: Void.self) { _ in }
    return await iterator.next()
}

/// A manually advanced clock. Sleepers wake when `advance` moves time past their
/// deadline, and a cancelled sleeper is removed (like `Task.sleep`, it throws).
final class TestClock: P2PClock, @unchecked Sendable {
    private let lock = NSLock()
    private var time: Duration = .zero
    private var waiters: [(id: UUID, deadline: Duration, c: CheckedContinuation<Void, any Error>)] = []

    var now: Duration { lock.withLock { time } }

    func sleep(for duration: Duration) async throws {
        let id = UUID()
        try await withTaskCancellationHandler {
            try await withCheckedThrowingContinuation { (c: CheckedContinuation<Void, any Error>) in
                let immediate: Bool = lock.withLock {
                    if duration <= .zero { return true }
                    waiters.append((id, time + duration, c))
                    return false
                }
                if immediate { c.resume() }
            }
        } onCancel: {
            let cancelled: CheckedContinuation<Void, any Error>? = lock.withLock {
                guard let i = waiters.firstIndex(where: { $0.id == id }) else { return nil }
                return waiters.remove(at: i).c
            }
            cancelled?.resume(throwing: CancellationError())
        }
    }

    func advance(by d: Duration) {
        let due: [CheckedContinuation<Void, any Error>] = lock.withLock {
            time += d
            let fired = waiters.filter { $0.deadline <= time }.map(\.c)
            waiters.removeAll { $0.deadline <= time }
            return fired
        }
        for c in due { c.resume() }
    }

    var sleeperCount: Int { lock.withLock { waiters.count } }
}

/// Scripted HTTP: a handler answers each request; every request is recorded.
final class FakeHTTP: HTTPTransport, @unchecked Sendable {
    private let lock = NSLock()
    private(set) var requests: [URLRequest] = []
    var handler: @Sendable (URLRequest) async throws -> HTTPResponse

    init(_ handler: @escaping @Sendable (URLRequest) async throws -> HTTPResponse = { _ in HTTPResponse(status: 200, body: Data("{}".utf8)) }) {
        self.handler = handler
    }

    func send(_ request: URLRequest) async throws -> HTTPResponse {
        lock.withLock { requests.append(request) }
        return try await handler(request)
    }

    var count: Int { lock.lock(); defer { lock.unlock() }; return requests.count }
    var last: URLRequest? { lock.lock(); defer { lock.unlock() }; return requests.last }
}

func json(_ status: Int, _ body: String) -> HTTPResponse { HTTPResponse(status: status, body: Data(body.utf8)) }

/// One fake socket: the test pushes inbound frames and reads what the client sent.
final class FakeConnection: WebSocketConnection, @unchecked Sendable {
    private let lock = NSLock()
    private(set) var sent: [String] = []
    private(set) var closedByClient: (code: Int, reason: String?)?
    private let inbound: AsyncStream<WebSocketMessage>
    private let feed: AsyncStream<WebSocketMessage>.Continuation
    let request: URLRequest

    init(request: URLRequest) {
        self.request = request
        (inbound, feed) = AsyncStream<WebSocketMessage>.makeStream()
    }

    func send(text: String) async throws {
        let closed: Bool = lock.withLock {
            if closedByClient != nil { return true }
            sent.append(text)
            return false
        }
        if closed { throw P2PError.closed }
    }

    private var iterator: AsyncStream<WebSocketMessage>.AsyncIterator?
    func receive() async throws -> WebSocketMessage {
        if iterator == nil { iterator = inbound.makeAsyncIterator() }
        if let m = await iterator!.next() { return m }
        throw P2PError.closed
    }

    func close(code: Int, reason: String?) async {
        lock.withLock { closedByClient = (code, reason) }
        feed.finish()
    }

    // test side
    func push(_ text: String) { feed.yield(.text(text)) }
    func serverClose() { feed.finish() }
    var sentFrames: [String] { lock.lock(); defer { lock.unlock() }; return sent }
    var isClosedByClient: Bool { lock.lock(); defer { lock.unlock() }; return closedByClient != nil }
    var origin: String? { request.value(forHTTPHeaderField: "Origin") }
}

/// Scripted WebSocket transport: each `connect` either fails per script or yields a new FakeConnection.
final class FakeWebSocketTransport: WebSocketTransport, @unchecked Sendable {
    private let lock = NSLock()
    private(set) var connections: [FakeConnection] = []
    private var failures: [P2PError?] = []

    /// Queue failures for the next connects (`nil` = succeed).
    func script(_ outcomes: [P2PError?]) { lock.lock(); failures = outcomes; lock.unlock() }

    func connect(_ request: URLRequest) async throws -> any WebSocketConnection {
        let result: Result<FakeConnection, P2PError> = lock.withLock {
            if !failures.isEmpty, let outcome = failures.removeFirst() { return .failure(outcome) }
            let c = FakeConnection(request: request)
            connections.append(c)
            return .success(c)
        }
        return try result.get()
    }

    var count: Int { lock.lock(); defer { lock.unlock() }; return connections.count }
    var latest: FakeConnection? { lock.lock(); defer { lock.unlock() }; return connections.last }
}

let testRoom = try! RoomId(String(repeating: "A", count: 43))
let testPeer = try! PeerId("00000000000000000000000000000001")
let otherPeer = try! PeerId("0f1e2d3c4b5a69788796a5b4c3d2e1f0")

static mirror of HEAD · about · clone: git clone https://ird.cod-sursa.ro/p2p-swift.git