Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XUtils / DataChannel.swift

DataChannel.swift132 lines · 4.4 KiBRaw
1import Foundation
2import ConcurrencyExtras
3
4/// A bi-directional channel for streaming data from producer -> consumer.
5///
6/// Supports backpressure via `onRequest`.
7public struct DataChannel: Sendable {
8 enum Phase {
9 case active
10 case closed(Error?)
11 }
12
13 public enum Errors: Error {
14 case concurrentRead
15 }
16
17 public struct Limit: Sendable {
18 public var limit: @Sendable (Data) throws -> Int
19
20 public init(limit: @escaping @Sendable (Data) throws -> Int) {
21 self.limit = limit
22 }
23
24 public static var unlimited: Limit {
25 Limit { _ in .max }
26 }
27
28 public static func bytes(_ count: Int) -> Limit {
29 Limit { _ in count }
30 }
31
32 public static var newline: Limit {
33 Limit { buffer in
34 if let newlineIndex = buffer.firstIndex(of: UInt8(ascii: "\n")) {
35 return buffer.distance(from: buffer.startIndex, to: newlineIndex) + 1
36 } else {
37 return .max
38 }
39 }
40 }
41 }
42
43 private struct State {
44 var waiter: (@Sendable () -> Void)?
45 var phase: Phase = .active
46 var buffer = Data()
47 var request: (@Sendable () -> Void)?
48 }
49 private let state = LockIsolated(State())
50
51 public init() {}
52
53 public func onRequest(_ request: @escaping @Sendable () -> Void) {
54 self.state.withValue { $0.request = request }
55 }
56
57 public func write(_ data: Data) {
58 let waiter: (@Sendable () -> Void)? = self.state.withValue { state in
59 guard case .active = state.phase else { return nil }
60 state.buffer.append(contentsOf: data)
61 return state.waiter.take()
62 }
63 waiter?()
64 }
65
66 public func finish(error: Error?) {
67 let waiter: (@Sendable () -> Void)? = self.state.withValue { state in
68 guard case .active = state.phase else { return nil }
69 state.phase = .closed(error)
70 return state.waiter.take()
71 }
72 waiter?()
73 }
74
75 private enum Outcome<T: Sendable>: Sendable {
76 case result(Result<T?, Error>)
77 case callRequest((@Sendable () -> Void)?)
78 }
79
80 nonisolated(nonsending) public func read<T: Sendable>(drain: @Sendable (inout Data) throws -> T) async throws -> T? {
81 while true {
82 try Task.checkCancellation()
83
84 let result: Result<T?, Error>? = await withTaskCancellationHandler {
85 await withCheckedContinuation { continuation in
86 let outcome: Outcome<T> = state.withValue { state in
87 guard !Task.isCancelled else {
88 return .result(.failure(CancellationError()))
89 }
90 if !state.buffer.isEmpty {
91 return .result(Result { try drain(&state.buffer) })
92 }
93 switch state.phase {
94 case .active:
95 guard state.waiter == nil else {
96 return .result(.failure(Errors.concurrentRead))
97 }
98 state.waiter = { continuation.resume(returning: nil) }
99 return .callRequest(state.request)
100 case .closed(nil):
101 return .result(.success(nil))
102 case .closed(let error?):
103 return .result(.failure(error))
104 }
105 }
106 switch outcome {
107 case .result(let result):
108 continuation.resume(returning: result)
109 case .callRequest(let request):
110 request?()
111 }
112 }
113 } onCancel: {
114 self.state.withValue { $0.waiter.take()?() }
115 }
116
117 if let result {
118 return try result.get()
119 }
120 }
121 }
122
123 nonisolated(nonsending) public func read(upTo limit: Limit = .unlimited) async throws -> Data? {
124 try await self.read { buffer in
125 let count = min(try limit.limit(buffer), buffer.count)
126 guard count > 0 else { return Data() }
127 let result = buffer.prefix(count)
128 buffer.removeFirst(count)
129 return result
130 }
131 }
132}