Modern Apps git

xtool.git

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

xtool.git / Sources / XUtils / DispatchInput.swift

DispatchInput.swift141 lines · 4.0 KiBRaw
1import Foundation
2import ConcurrencyExtras
3
4public final class DispatchInput: Sendable {
5 private struct State {
6 var hasClosed = false
7 var isReading = false
8 }
9
10 public static let defaultChunkSize: Int = 64 * 1024
11
12 let queue = DispatchQueue(label: "xtool.dispatch-reader")
13 let channel: DispatchIO
14 let chunkSize: Int
15 private let closeSignal: Task<Void, Never>
16 private let dataChannel = DataChannel()
17 private let state = LockIsolated(State())
18
19 public init(fileDesciptor: FileDescriptor, chunkSize: Int = DispatchInput.defaultChunkSize) throws {
20 let closeSignal = Task { _ = try? await Task.never() }
21 self.closeSignal = closeSignal
22 self.chunkSize = chunkSize
23
24 enum InitState {
25 case pending
26 case done(onClose: @Sendable (Int32) -> Void)
27 case failed(Int32)
28 }
29 let initState = LockIsolated<InitState>(.pending)
30 self.channel = DispatchIO(
31 type: .stream,
32 fileDescriptor: fileDesciptor.rawValue,
33 queue: queue,
34 ) { err in
35 initState.withValue { state in
36 switch state {
37 case .pending:
38 state = .failed(err)
39 case .done(let onClose):
40 onClose(err)
41 case .failed: // wat
42 break
43 }
44 }
45 }
46 channel.setLimit(lowWater: 1)
47
48 try initState.withValue { state in
49 switch state {
50 case .pending:
51 state = .done { [weak self] err in
52 self?.didClose(code: err)
53 closeSignal.cancel()
54 }
55 case .done: // wat
56 break
57 case .failed(let err):
58 throw Errno(rawValue: err)
59 }
60 }
61
62 dataChannel.onRequest { [weak self] in
63 self?.onRequest()
64 }
65 }
66
67 nonisolated(nonsending) public func read(upTo limit: DataChannel.Limit = .unlimited) async throws -> Data? {
68 try await dataChannel.read(upTo: limit)
69 }
70
71 private func onRequest() {
72 let didMarkStarted = state.withValue { state in
73 guard !state.isReading else { return false }
74 state.isReading = true
75 return true
76 }
77 guard didMarkStarted else { return }
78 channel.read(
79 offset: 0,
80 length: chunkSize,
81 queue: queue,
82 ) { [weak self] done, data, error in
83 guard let self else { return }
84 let data = data.map { Data($0) }
85 self.onRead(
86 done: done,
87 data: data,
88 error: error,
89 )
90 }
91 }
92
93 private func onRead(
94 done: Bool,
95 data: Data?,
96 error: Int32,
97 ) {
98 if done {
99 state.withValue { $0.isReading = false }
100 }
101 let data = data.map { Data($0) }
102 if let data, !data.isEmpty {
103 dataChannel.write(data)
104 }
105 if error != 0 {
106 requestClose(error: Errno(rawValue: error))
107 } else if done, data?.isEmpty == true {
108 requestClose(error: nil)
109 }
110 }
111
112 nonisolated(nonsending) public func close() async {
113 requestClose(error: nil)
114 await closeSignal.value
115 }
116
117 private func requestClose(error: Error?) {
118 guard markClosedIfNeeded() else { return }
119 channel.close(flags: .stop)
120 dataChannel.finish(error: error)
121 }
122
123 private func didClose(code: Int32) {
124 guard markClosedIfNeeded() else { return }
125 dataChannel.finish(error: code == 0 ? nil : Errno(rawValue: code))
126 }
127
128 private func markClosedIfNeeded() -> Bool {
129 state.withValue { state in
130 let hadClosed = state.hasClosed
131 state.hasClosed = true
132 return !hadClosed
133 }
134 }
135
136 deinit {
137 guard !state.withValue(\.hasClosed) else { return }
138 channel.close(flags: .stop)
139 dataChannel.finish(error: nil)
140 }
141}