Skip to content

Move LocalConnection to LSPTestSupport #1318

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions Sources/LSPTestSupport/LocalConnection.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import Dispatch
import LSPLogging
import LanguageServerProtocol

/// A connection between two message handlers in the same process.
///
/// You must call `start(handler:)` before sending any messages, and must call `close()` when finished to avoid a memory leak.
///
/// ```
/// let client: MessageHandler = ...
/// let server: MessageHandler = ...
/// let conn = LocalConnection()
/// conn.start(handler: server)
/// conn.send(...) // handled by server
/// conn.close()
/// ```
///
/// - Note: Unchecked sendable conformance because shared state is guarded by `queue`.
public final class LocalConnection: Connection, @unchecked Sendable {
enum State {
case ready, started, closed
}

/// A name of the endpoint for this connection, used for logging, e.g. `clangd`.
private let name: String

/// The queue guarding `_nextRequestID`.
let queue: DispatchQueue = DispatchQueue(label: "local-connection-queue")

var _nextRequestID: Int = 0

var state: State = .ready

var handler: MessageHandler? = nil

public init(name: String) {
self.name = name
}

deinit {
if state != .closed {
close()
}
}

public func start(handler: MessageHandler) {
precondition(state == .ready)
state = .started
self.handler = handler
}

public func close() {
precondition(state != .closed)
handler = nil
state = .closed
}

func nextRequestID() -> RequestID {
return queue.sync {
_nextRequestID += 1
return .number(_nextRequestID)
}
}

public func send<Notification: NotificationType>(_ notification: Notification) {
logger.info(
"""
Sending notification to \(self.name, privacy: .public)
\(notification.forLogging)
"""
)
self.handler?.handle(notification)
}

public func send<Request: RequestType>(
_ request: Request,
reply: @Sendable @escaping (LSPResult<Request.Response>) -> Void
) -> RequestID {
let id = nextRequestID()

logger.info(
"""
Sending request to \(self.name, privacy: .public) (id: \(id, privacy: .public)):
\(request.forLogging)
"""
)

guard let handler = self.handler else {
logger.info(
"""
Replying to request \(id, privacy: .public) with .serverCancelled because no handler is specified in \(self.name, privacy: .public)
"""
)
reply(.failure(.serverCancelled))
return id
}

precondition(self.state == .started)
handler.handle(request, id: id) { result in
switch result {
case .success(let response):
logger.info(
"""
Received reply for request \(id, privacy: .public) from \(self.name, privacy: .public)
\(response.forLogging)
"""
)
case .failure(let error):
logger.error(
"""
Received error for request \(id, privacy: .public) from \(self.name, privacy: .public)
\(error.forLogging)
"""
)
}
reply(result)
}

return id
}
}
4 changes: 2 additions & 2 deletions Sources/LSPTestSupport/TestJSONRPCConnection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,9 @@ public final class TestJSONRPCConnection: Sendable {

public struct TestLocalConnection {
public let client: TestClient
public let clientConnection: LocalConnection = LocalConnection()
public let clientConnection: LocalConnection = LocalConnection(name: "Test")
public let server: TestServer
public let serverConnection: LocalConnection = LocalConnection()
public let serverConnection: LocalConnection = LocalConnection(name: "Test")

public init(allowUnexpectedNotification: Bool = true) {
client = TestClient(connectionToServer: serverConnection, allowUnexpectedNotification: allowUnexpectedNotification)
Expand Down
82 changes: 0 additions & 82 deletions Sources/LanguageServerProtocol/Connection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@
//
//===----------------------------------------------------------------------===//

import Dispatch

/// An abstract connection, allow messages to be sent to a (potentially remote) `MessageHandler`.
public protocol Connection: AnyObject, Sendable {

Expand Down Expand Up @@ -47,83 +45,3 @@ public protocol MessageHandler: AnyObject, Sendable {
reply: @Sendable @escaping (LSPResult<Request.Response>) -> Void
)
}

/// A connection between two message handlers in the same process.
///
/// You must call `start(handler:)` before sending any messages, and must call `close()` when finished to avoid a memory leak.
///
/// ```
/// let client: MessageHandler = ...
/// let server: MessageHandler = ...
/// let conn = LocalConnection()
/// conn.start(handler: server)
/// conn.send(...) // handled by server
/// conn.close()
/// ```
///
/// - Note: Unchecked sendable conformance because shared state is guarded by `queue`.
public final class LocalConnection: Connection, @unchecked Sendable {

enum State {
case ready, started, closed
}

/// The queue guarding `_nextRequestID`.
let queue: DispatchQueue = DispatchQueue(label: "local-connection-queue")

var _nextRequestID: Int = 0

var state: State = .ready

var handler: MessageHandler? = nil

public init() {}

deinit {
if state != .closed {
close()
}
}

public func start(handler: MessageHandler) {
precondition(state == .ready)
state = .started
self.handler = handler
}

public func close() {
precondition(state != .closed)
handler = nil
state = .closed
}

func nextRequestID() -> RequestID {
return queue.sync {
_nextRequestID += 1
return .number(_nextRequestID)
}
}

public func send<Notification>(_ notification: Notification) where Notification: NotificationType {
self.handler?.handle(notification)
}

public func send<Request: RequestType>(
_ request: Request,
reply: @Sendable @escaping (LSPResult<Request.Response>) -> Void
) -> RequestID {
let id = nextRequestID()

guard let handler = self.handler else {
reply(.failure(.serverCancelled))
return id
}

precondition(self.state == .started)
handler.handle(request, id: id) { result in
reply(result)
}

return id
}
}
2 changes: 1 addition & 1 deletion Sources/SKTestSupport/TestSourceKitLSPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public final class TestSourceKitLSPClient: MessageHandler {
}
self.notificationYielder = notificationYielder

let serverToClientConnection = LocalConnection()
let serverToClientConnection = LocalConnection(name: "client")
self.serverToClientConnection = serverToClientConnection
server = SourceKitLSPServer(
client: serverToClientConnection,
Expand Down
1 change: 0 additions & 1 deletion Sources/SourceKitLSP/SourceKitLSPServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -699,7 +699,6 @@ public actor SourceKitLSPServer {

/// Send the given notification to the editor.
public func sendNotificationToClient(_ notification: some NotificationType) {
logger.log("Sending notification: \(notification.forLogging)")
client.send(notification)
}

Expand Down