forked from scalameta/metals
/
DebugProxy.scala
359 lines (332 loc) Β· 12.4 KB
/
DebugProxy.scala
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package scala.meta.internal.metals.debug
import java.net.Socket
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import scala.collection.concurrent.TrieMap
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.concurrent.Promise
import scala.util.Failure
import scala.util.Success
import scala.util.Try
import scala.util.control.NonFatal
import scala.meta.internal.metals.Cancelable
import scala.meta.internal.metals.Compilations
import scala.meta.internal.metals.Compilers
import scala.meta.internal.metals.EmptyCancelToken
import scala.meta.internal.metals.JsonParser._
import scala.meta.internal.metals.MetalsEnrichments._
import scala.meta.internal.metals.SourceMapper
import scala.meta.internal.metals.StacktraceAnalyzer
import scala.meta.internal.metals.StatusBar
import scala.meta.internal.metals.Trace
import scala.meta.internal.metals.debug.DebugProtocol.CompletionRequest
import scala.meta.internal.metals.debug.DebugProtocol.DisconnectRequest
import scala.meta.internal.metals.debug.DebugProtocol.ErrorOutputNotification
import scala.meta.internal.metals.debug.DebugProtocol.HotCodeReplace
import scala.meta.internal.metals.debug.DebugProtocol.InitializeRequest
import scala.meta.internal.metals.debug.DebugProtocol.LaunchRequest
import scala.meta.internal.metals.debug.DebugProtocol.OutputNotification
import scala.meta.internal.metals.debug.DebugProtocol.SetBreakpointRequest
import scala.meta.internal.metals.debug.DebugProxy._
import scala.meta.io.AbsolutePath
import ch.epfl.scala.bsp4j.BuildTargetIdentifier
import org.eclipse.lsp4j.Position
import org.eclipse.lsp4j.debug.Breakpoint
import org.eclipse.lsp4j.debug.CompletionsResponse
import org.eclipse.lsp4j.debug.SetBreakpointsResponse
import org.eclipse.lsp4j.debug.Source
import org.eclipse.lsp4j.debug.StackFrame
import org.eclipse.lsp4j.jsonrpc.MessageConsumer
import org.eclipse.lsp4j.jsonrpc.debug.messages.DebugResponseMessage
import org.eclipse.lsp4j.jsonrpc.messages.Message
import org.eclipse.lsp4j.jsonrpc.messages.ResponseError
import org.eclipse.lsp4j.jsonrpc.messages.ResponseErrorCode
private[debug] final class DebugProxy(
sessionName: String,
client: RemoteEndpoint,
server: ServerAdapter,
debugAdapter: MetalsDebugAdapter,
stackTraceAnalyzer: StacktraceAnalyzer,
compilers: Compilers,
stripColor: Boolean,
statusBar: StatusBar,
sourceMapper: SourceMapper,
compilations: Compilations,
targets: Seq[BuildTargetIdentifier],
)(implicit ec: ExecutionContext) {
private val exitStatus = Promise[ExitStatus]()
@volatile private var outputTerminated = false
@volatile private var debugMode: DebugMode = DebugMode.Enabled
private val cancelled = new AtomicBoolean()
@volatile private var clientAdapter =
ClientConfigurationAdapter.default(sourceMapper)
private val frameIdToFrame: TrieMap[Int, StackFrame] = TrieMap.empty
lazy val listen: Future[ExitStatus] = {
scribe.info(s"Starting debug proxy for [$sessionName]")
listenToServer()
listenToClient()
exitStatus.future
}
private def listenToClient(): Unit = {
Future(client.listen(handleClientMessage)).andThen { case _ => cancel() }
}
private def listenToServer(): Unit = {
Future(server.onReceived(handleServerMessage))
.andThen { case _ => cancel() }
}
private val initialized = Promise[Unit]()
private val handleClientMessage: MessageConsumer = {
case null =>
() // ignore
case _ if cancelled.get() =>
() // ignore
case request @ InitializeRequest(args) =>
statusBar.trackFuture(
"Initializing debugger",
initialized.future,
)
clientAdapter = ClientConfigurationAdapter.initialize(args, sourceMapper)
server.send(request)
case request @ LaunchRequest(debugMode) =>
this.debugMode = debugMode
server.send(request)
case request @ DisconnectRequest(args) if args.getRestart() =>
initialized.trySuccess(())
// set the status first, since the server can kill the connection
exitStatus.trySuccess(Restarted)
outputTerminated = true
server.send(request)
case request @ SetBreakpointRequest(_) if debugMode == DebugMode.Disabled =>
// ignore breakpoints when not debugging
val response = new SetBreakpointsResponse
response.setBreakpoints(Array.empty)
client.consume(DebugProtocol.syntheticResponse(request, response))
case request @ SetBreakpointRequest(args) =>
val originalSource = DebugProtocol.copy(args.getSource)
Try(clientAdapter.toMetalsPath(originalSource.getPath)) match {
case Success(metalsSourcePath) =>
args.getBreakpoints.foreach { breakpoint =>
val line = clientAdapter.normalizeLineForServer(
metalsSourcePath,
breakpoint.getLine,
)
breakpoint.setLine(line)
}
val requests =
debugAdapter.adaptSetBreakpointsRequest(metalsSourcePath, args)
server
.sendPartitioned(requests.map(DebugProtocol.syntheticRequest))
.map(_.map(DebugProtocol.parseResponse[SetBreakpointsResponse]))
.map(_.flatMap(_.toList))
.map(assembleResponse(_, originalSource, metalsSourcePath))
.map(DebugProtocol.syntheticResponse(request, _))
.foreach(client.consume)
case Failure(_) =>
scribe.warn(
s"Cannot adapt SetBreakpointRequest because of invalid path: ${originalSource.getPath}"
)
val breakpoints = args.getBreakpoints.map { sourceBreakpoint =>
val breakpoint = new Breakpoint
breakpoint.setLine(sourceBreakpoint.getLine)
breakpoint.setColumn(sourceBreakpoint.getColumn)
breakpoint.setSource(originalSource)
breakpoint.setVerified(false)
breakpoint.setMessage(s"Invalid path: ${originalSource.getPath}")
breakpoint
}
val response = new SetBreakpointsResponse
response.setBreakpoints(breakpoints)
client.consume(DebugProtocol.syntheticResponse(request, response))
}
case request @ CompletionRequest(args) =>
if (args.getLine == null) {
args.setLine(1)
}
val completions = for {
frame <- frameIdToFrame.get(args.getFrameId())
} yield {
val originalSource = frame.getSource()
val sourceUri = clientAdapter.toMetalsPath(originalSource.getPath)
compilers.debugCompletions(
sourceUri,
new Position(frame.getLine() - 1, 0),
EmptyCancelToken,
args,
isZeroBased = !clientAdapter.linesStartAt1,
)
}
completions
.getOrElse(Future.failed(new Exception("No source data available")))
.recover { case NonFatal(t) =>
scribe.error("Could not find any completions for the debugger", t)
Nil
}
.map { items =>
val responseArgs = new CompletionsResponse()
responseArgs.setTargets(items.toArray)
val response = new DebugResponseMessage
response.setId(request.getId)
response.setMethod(request.getMethod)
response.setResult(responseArgs.toJson)
client.consume(response)
}
.withTimeout(5, TimeUnit.SECONDS)
case HotCodeReplace(req) =>
scribe.info("Hot code replace triggered")
compilations
.compileTargets(targets)
.onComplete {
case _: Success[?] => server.send(req)
case Failure(e) =>
val res = new DebugResponseMessage
res.setId(req.getId)
res.setMethod(req.getMethod)
res.setError(
new ResponseError(
ResponseErrorCode.InternalError,
s"Failed to compile ${e.getLocalizedMessage()}",
null,
)
)
client.consume(res)
}
case message => server.send(message)
}
private def assembleResponse(
responses: Iterable[SetBreakpointsResponse],
originalSource: Source,
metalsSourcePath: AbsolutePath,
): SetBreakpointsResponse = {
val breakpoints = for {
response <- responses
breakpoint <- response.getBreakpoints
} yield {
val line =
clientAdapter.adaptLineForClient(metalsSourcePath, breakpoint.getLine)
breakpoint.setSource(originalSource)
breakpoint.setLine(line)
breakpoint
}
val response = new SetBreakpointsResponse
response.setBreakpoints(breakpoints.toArray)
response
}
private val handleServerMessage: Message => Unit = {
case null => () // ignore
case _ if cancelled.get() => () // ignore
case OutputNotification(_) if outputTerminated => ()
// ignore. When restarting, the output keeps getting printed for a short while after the
// output window gets refreshed resulting in stale messages being printed on top, before
// any actual logs from the restarted process
case response @ DebugProtocol.StackTraceResponse(args) =>
import DapJsonParser._
for {
stackFrame <- args.getStackFrames
frameSource <- Option(stackFrame.getSource)
frameSourcePath <- Option(frameSource.getPath)
_ = stackFrame.setLine(
clientAdapter.adaptLineForClient(
clientAdapter.toMetalsPath(frameSourcePath),
stackFrame.getLine,
)
)
mappedSourcePath = clientAdapter
.toMetalsPath(frameSourcePath, mappedFrom = true)
metalsSource <- debugAdapter.adaptStackFrameSource(
mappedSourcePath
)
} frameSource.setPath(clientAdapter.adaptPathForClient(metalsSource))
val result = clientAdapter.adaptStackTraceResponse(args.toJsonObject)
response.setResult(result)
for (frame <- args.getStackFrames()) {
frameIdToFrame.put(frame.getId, frame)
}
client.consume(response)
case message @ ErrorOutputNotification(output) =>
initialized.trySuccess(())
val analyzedMessage = stackTraceAnalyzer
.fileLocationFromLine(output.getOutput())
.map(DebugProtocol.stacktraceOutputResponse(output, _))
.getOrElse(message)
client.consume(analyzedMessage)
case message @ OutputNotification(output) if stripColor =>
val raw = output.getOutput()
val msgWithoutColorCodes = filterANSIColorCodes(raw)
output.setOutput(msgWithoutColorCodes)
message.setParams(output)
client.consume(message)
case message =>
initialized.trySuccess(())
client.consume(message)
}
def cancel(): Unit = {
if (cancelled.compareAndSet(false, true)) {
initialized.trySuccess(())
scribe.info(s"Canceling debug proxy for [$sessionName]")
exitStatus.trySuccess(Terminated)
Cancelable.cancelAll(List(client, server))
}
}
}
private[debug] object DebugProxy {
sealed trait ExitStatus
case object Terminated extends ExitStatus
case object Restarted extends ExitStatus
trait DebugMode
object DebugMode {
case object Enabled extends DebugMode
case object Disabled extends DebugMode
}
def open(
name: String,
awaitClient: () => Future[Socket],
connectToServer: () => Future[Socket],
debugAdapter: MetalsDebugAdapter,
stackTraceAnalyzer: StacktraceAnalyzer,
compilers: Compilers,
workspace: AbsolutePath,
stripColor: Boolean,
status: StatusBar,
sourceMapper: SourceMapper,
compilations: Compilations,
targets: Seq[BuildTargetIdentifier],
)(implicit ec: ExecutionContext): Future[DebugProxy] = {
for {
server <- connectToServer()
.map(new SocketEndpoint(_))
.map(endpoint =>
withLogger(workspace, endpoint, DebugProtocol.serverName)
)
.map(new MessageIdAdapter(_))
.map(new ServerAdapter(_))
client <- awaitClient()
.map(new SocketEndpoint(_))
.map(endpoint =>
withLogger(workspace, endpoint, DebugProtocol.clientName)
)
.map(new MessageIdAdapter(_))
} yield new DebugProxy(
name,
client,
server,
debugAdapter,
stackTraceAnalyzer,
compilers,
stripColor,
status,
sourceMapper,
compilations,
targets,
)
}
private def withLogger(
workspace: AbsolutePath,
endpoint: RemoteEndpoint,
name: String,
): RemoteEndpoint =
Trace.setupTracePrinter(name, workspace) match {
case Some(trace) => new EndpointLogger(endpoint, trace)
case None => endpoint
}
}