File: TestJSONRPCConnection.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (243 lines) | stat: -rw-r--r-- 7,691 bytes parent folder | download
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
//===----------------------------------------------------------------------===//
//
// 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 InProcessClient
import LanguageServerProtocol
import LanguageServerProtocolJSONRPC
import SKSupport
import SwiftExtensions
import XCTest

import class Foundation.Pipe

public final class TestJSONRPCConnection: Sendable {
  public let clientToServer: Pipe = Pipe()
  public let serverToClient: Pipe = Pipe()

  /// Mocks a client (aka. editor) that can send requests to the LSP server.
  public let client: TestClient

  /// The connection with which the client can send requests and notifications to the LSP server and using which it
  /// receives replies to the requests.
  public let clientToServerConnection: JSONRPCConnection

  /// Mocks an LSP server that handles requests from the client.
  public let server: TestServer

  /// The connection with which the server can send requests and notifications to the client and using which it
  /// receives replies to the requests.
  public let serverToClientConnection: JSONRPCConnection

  public init(allowUnexpectedNotification: Bool = true) {
    clientToServerConnection = JSONRPCConnection(
      name: "client",
      protocol: testMessageRegistry,
      inFD: serverToClient.fileHandleForReading,
      outFD: clientToServer.fileHandleForWriting
    )

    serverToClientConnection = JSONRPCConnection(
      name: "server",
      protocol: testMessageRegistry,
      inFD: clientToServer.fileHandleForReading,
      outFD: serverToClient.fileHandleForWriting
    )

    client = TestClient(
      connectionToServer: clientToServerConnection,
      allowUnexpectedNotification: allowUnexpectedNotification
    )
    server = TestServer(client: serverToClientConnection)

    clientToServerConnection.start(receiveHandler: client) {
      // FIXME: keep the pipes alive until we close the connection. This
      // should be fixed systemically.
      withExtendedLifetime(self) {}
    }
    serverToClientConnection.start(receiveHandler: server) {
      // FIXME: keep the pipes alive until we close the connection. This
      // should be fixed systemically.
      withExtendedLifetime(self) {}
    }
  }

  public func close() {
    clientToServerConnection.close()
    serverToClientConnection.close()
  }
}

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

  public init(allowUnexpectedNotification: Bool = true) {
    client = TestClient(connectionToServer: serverConnection, allowUnexpectedNotification: allowUnexpectedNotification)
    server = TestServer(client: clientConnection)

    clientConnection.start(handler: client)
    serverConnection.start(handler: server)
  }

  public func close() {
    clientConnection.close()
    serverConnection.close()
  }
}

public actor TestClient: MessageHandler {
  /// The connection to the LSP server.
  public let connectionToServer: Connection

  private let messageHandlingQueue = AsyncQueue<Serial>()

  private var oneShotNotificationHandlers: [((Any) -> Void)] = []

  private let allowUnexpectedNotification: Bool

  public init(connectionToServer: Connection, allowUnexpectedNotification: Bool = true) {
    self.connectionToServer = connectionToServer
    self.allowUnexpectedNotification = allowUnexpectedNotification
  }

  public func appendOneShotNotificationHandler<N: NotificationType>(_ handler: @escaping (N) -> Void) {
    oneShotNotificationHandlers.append({ anyNotification in
      guard let notification = anyNotification as? N else {
        fatalError("received notification of the wrong type \(anyNotification); expected \(N.self)")
      }
      handler(notification)
    })
  }

  /// The LSP server sent a notification to the client. Handle it.
  public nonisolated func handle(_ notification: some NotificationType) {
    messageHandlingQueue.async {
      await self.handleNotificationImpl(notification)
    }
  }

  public func handleNotificationImpl(_ notification: some NotificationType) {
    guard !oneShotNotificationHandlers.isEmpty else {
      if allowUnexpectedNotification { return }
      fatalError("unexpected notification \(notification)")
    }
    let handler = oneShotNotificationHandlers.removeFirst()
    handler(notification)
  }

  /// The LSP server sent a request to the client. Handle it.
  public nonisolated func handle<Request: RequestType>(
    _ request: Request,
    id: RequestID,
    reply: @escaping (LSPResult<Request.Response>) -> Void
  ) {
    reply(.failure(.methodNotFound(Request.method)))
  }

  /// Send a notification to the LSP server.
  public nonisolated func send(_ notification: some NotificationType) {
    connectionToServer.send(notification)
  }

  /// Send a request to the LSP server and (asynchronously) receive a reply.
  public nonisolated func send<Request: RequestType>(
    _ request: Request,
    reply: @Sendable @escaping (LSPResult<Request.Response>) -> Void
  ) -> RequestID {
    return connectionToServer.send(request, reply: reply)
  }
}

public final class TestServer: MessageHandler {
  public let client: Connection

  init(client: Connection) {
    self.client = client
  }

  /// The client sent a notification to the server. Handle it.
  public func handle(_ notification: some NotificationType) {
    if notification is EchoNotification {
      self.client.send(notification)
    } else {
      fatalError("Unhandled notification")
    }
  }

  /// The client sent a request to the server. Handle it.
  public func handle<Request: RequestType>(
    _ request: Request,
    id: RequestID,
    reply: @escaping (LSPResult<Request.Response>) -> Void
  ) {
    if let params = request as? EchoRequest {
      reply(.success(params.string as! Request.Response))
    } else if let params = request as? EchoError {
      if let code = params.code {
        reply(.failure(ResponseError(code: code, message: params.message!)))
      } else {
        reply(.success(VoidResponse() as! Request.Response))
      }
    } else {
      fatalError("Unhandled request")
    }
  }
}

// MARK: Test requests

private let testMessageRegistry = MessageRegistry(
  requests: [EchoRequest.self, EchoError.self],
  notifications: [EchoNotification.self, ShowMessageNotification.self]
)

#if compiler(<5.11)
extension String: ResponseType {}
#else
extension String: @retroactive ResponseType {}
#endif

public struct EchoRequest: RequestType {
  public static let method: String = "test_server/echo"
  public typealias Response = String

  public var string: String

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

public struct EchoError: RequestType {
  public static let method: String = "test_server/echo_error"
  public typealias Response = VoidResponse

  public var code: ErrorCode?
  public var message: String?

  public init(code: ErrorCode? = nil, message: String? = nil) {
    self.code = code
    self.message = message
  }
}

public struct EchoNotification: NotificationType {
  public static let method: String = "test_server/echo_note"

  public var string: String

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