MCPcopy Create free account
hub / github.com/apple/coremltools / PassThroughSocket

Class PassThroughSocket

coremltools/modelrunner/ModelRunner/Socket.swift:170–233  ·  view source on GitHub ↗

A generic actor that implements the `Socket` protocol, designed to pass through requests and responses.

Source from the content-addressed store, hash-verified

168
169/// A generic actor that implements the `Socket` protocol, designed to pass through requests and responses.
170actor PassThroughSocket<Request, Response>: Socket where Request: Sendable, Response:Sendable {
171 /// Dictionary to store active continuations
172 private var continuations: [Int : AsyncStream<Request>.Continuation] = [:]
173 /// ID for the next continuation
174 private var nextContinuationID: Int = 0
175 /// The response stream.
176 nonisolated let responseStream: AsyncStream<Response>
177 /// The response continuation.
178 private let responseContinuation: AsyncStream<Response>.Continuation
179
180 init() {
181 (responseStream, responseContinuation) = AsyncStream.makeStream(of: Response.self)
182 }
183
184 func receive() async throws -> AsyncStream<Request> {
185 defer {
186 nextContinuationID += 1
187 }
188
189 let continuationID = nextContinuationID
190 // Create a new stream and store its continuation
191 let (stream, continuation) = AsyncStream.makeStream(of: Request.self)
192 continuations[continuationID] = continuation
193
194 // Set up termination handler for the continuation
195 continuation.onTermination = { [weak self] _ in
196 guard let self else { return }
197 Task {
198 await self.removeContinuation(continuationID)
199 }
200 }
201
202 return stream
203 }
204
205 // Remove a continuation when it's terminated
206 private func removeContinuation(_ continuationID: Int) async {
207 continuations.removeValue(forKey: continuationID)
208 }
209
210 func send(value: Response) async throws {
211 responseContinuation.yield(value)
212 }
213
214 /// Pushes a request value to all active continuations.
215 ///
216 /// This method broadcasts the request to all current listeners.
217 ///
218 /// - Parameter value: The `Request` object to push.
219 func push(value: Request) async throws {
220 for continuation in continuations.values {
221 continuation.yield(value)
222 }
223 }
224
225 func shutdown() async {
226 responseContinuation.finish()
227 for continuation in continuations.values {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected