-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
LtexWorkspaceService.kt
216 lines (188 loc) · 7.97 KB
/
LtexWorkspaceService.kt
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
/* Copyright (C) 2019-2023 Julian Valentin, LTeX Development Community
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package org.bsplines.ltexls.server
import com.google.gson.JsonObject
import com.sun.management.OperatingSystemMXBean
import org.bsplines.ltexls.tools.FileIo
import org.bsplines.ltexls.tools.I18n
import org.bsplines.ltexls.tools.Logging
import org.bsplines.ltexls.tools.Tools
import org.eclipse.lsp4j.DidChangeConfigurationParams
import org.eclipse.lsp4j.DidChangeWatchedFilesParams
import org.eclipse.lsp4j.ExecuteCommandParams
import org.eclipse.lsp4j.Position
import org.eclipse.lsp4j.Range
import org.eclipse.lsp4j.jsonrpc.CancelChecker
import org.eclipse.lsp4j.jsonrpc.CompletableFutures
import org.eclipse.lsp4j.services.WorkspaceService
import java.lang.management.ManagementFactory
import java.net.URI
import java.net.URISyntaxException
import java.nio.file.Path
import java.nio.file.Paths
import java.time.Duration
import java.time.Instant
import java.util.concurrent.Callable
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
class LtexWorkspaceService(
val languageServer: LtexLanguageServer,
) : WorkspaceService {
override fun didChangeConfiguration(params: DidChangeConfigurationParams) {
this.languageServer.ltexTextDocumentService.executeFunctionForEachDocument {
document: LtexTextDocumentItem ->
if (document.beingChecked) document.cancelCheck()
this.languageServer.singleThreadExecutorService.execute {
var exception: Exception? = null
try {
document.checkAndPublishDiagnosticsWithoutCache()
document.raiseExceptionIfCanceled()
} catch (e: ExecutionException) {
exception = e
} catch (e: InterruptedException) {
exception = e
}
if (exception != null) {
Tools.rethrowCancellationException(exception)
Logging.LOGGER.warning(I18n.format(exception))
}
}
}
}
override fun didChangeWatchedFiles(params: DidChangeWatchedFilesParams) {
}
override fun executeCommand(params: ExecuteCommandParams): CompletableFuture<Any> {
return when (params.command) {
CHECK_DOCUMENT_COMMAND_NAME -> executeCheckDocumentCommand(params.arguments[0] as JsonObject)
GET_SERVER_STATUS_COMMAND_NAME -> executeGetServerStatusCommand()
else -> failCommand(I18n.format("unknownCommand", params.command))
}
}
fun executeCheckDocumentCommand(arguments: JsonObject): CompletableFuture<Any> {
val uriStr: String = arguments.get("uri").asString
var codeLanguageId: String? = arguments.get("codeLanguageId")?.asString
var text: String? = arguments.get("text")?.asString
if ((codeLanguageId == null) || (text == null)) {
val path: Path = try {
Paths.get(URI(uriStr))
} catch (e: IllegalArgumentException) {
return failCommand(I18n.format("couldNotParseDocumentUri", e))
} catch (e: URISyntaxException) {
return failCommand(I18n.format("couldNotParseDocumentUri", e))
}
if (text == null) {
text = FileIo.readFile(path)
if (text == null) return failCommand(I18n.format("couldNotReadFile", path.toString()))
}
codeLanguageId = codeLanguageId ?: FileIo.getCodeLanguageIdFromPath(path)
codeLanguageId = codeLanguageId ?: "plaintext"
}
val document = LtexTextDocumentItem(this.languageServer, uriStr, codeLanguageId, 1, text)
val range: Range? = if (arguments.has("range")) {
val jsonRange: JsonObject = arguments.getAsJsonObject("range")
val jsonStart: JsonObject = jsonRange.getAsJsonObject("start")
val jsonEnd: JsonObject = jsonRange.getAsJsonObject("end")
Range(
Position(jsonStart.get("line").asInt, jsonStart.get("character").asInt),
Position(jsonEnd.get("line").asInt, jsonEnd.get("character").asInt),
)
} else {
null
}
if (document.beingChecked) document.cancelCheck()
return CompletableFutures.computeAsync(this.languageServer.singleThreadExecutorService) {
lspCancelChecker: CancelChecker ->
document.lspCancelChecker = lspCancelChecker
try {
val success: Boolean = document.checkAndPublishDiagnosticsWithoutCache(range)
val jsonObject = JsonObject()
jsonObject.addProperty("success", success)
document.raiseExceptionIfCanceled()
jsonObject
} catch (e: ExecutionException) {
Tools.rethrowCancellationException(e)
Logging.LOGGER.warning(I18n.format(e))
emptyList<Any>()
} catch (e: InterruptedException) {
Tools.rethrowCancellationException(e)
Logging.LOGGER.warning(I18n.format(e))
emptyList<Any>()
}
}
}
@Suppress("SwallowedException")
fun executeGetServerStatusCommand(): CompletableFuture<Any> {
val processId: Long = ProcessHandle.current().pid()
val wallClockDuration: Double = Duration.between(
this.languageServer.startupInstant,
Instant.now(),
).toMillis() / MILLISECONDS_PER_SECOND
val cpuDuration: Double?
var cpuUsage: Double?
val totalMemory: Double = Runtime.getRuntime().totalMemory().toDouble()
val usedMemory: Double = totalMemory - Runtime.getRuntime().freeMemory()
if (ManagementFactory.getOperatingSystemMXBean() is OperatingSystemMXBean) {
val operatingSystemMxBean: OperatingSystemMXBean =
ManagementFactory.getOperatingSystemMXBean() as OperatingSystemMXBean
cpuUsage = operatingSystemMxBean.processCpuLoad
if (cpuUsage == -1.0) cpuUsage = null
val cpuDurationLong: Long = operatingSystemMxBean.processCpuTime
cpuDuration = if (cpuDurationLong != -1L) (cpuDurationLong / NANOSECONDS_PER_SECOND) else null
} else {
cpuDuration = null
cpuUsage = null
}
val singleThreadTestFuture: Future<Boolean> =
this.languageServer.singleThreadExecutorService.submit(Callable { true })
val isChecking: Boolean = try {
!singleThreadTestFuture.get(CHECK_CHECKING_STATUS_MILLISECONDS, TimeUnit.MILLISECONDS)
} catch (e: ExecutionException) {
true
} catch (e: InterruptedException) {
true
} catch (e: TimeoutException) {
true
}
val documentUriBeingChecked: String? = if (isChecking) {
languageServer.documentChecker.lastCheckedDocument?.uri
} else {
null
}
val jsonObject = JsonObject()
jsonObject.addProperty("success", true)
jsonObject.addProperty("processId", processId)
jsonObject.addProperty("wallClockDuration", wallClockDuration)
if (cpuUsage != null) jsonObject.addProperty("cpuUsage", cpuUsage)
if (cpuDuration != null) jsonObject.addProperty("cpuDuration", cpuDuration)
jsonObject.addProperty("usedMemory", usedMemory)
jsonObject.addProperty("totalMemory", totalMemory)
jsonObject.addProperty("isChecking", isChecking)
if (documentUriBeingChecked != null) {
jsonObject.addProperty("documentUriBeingChecked", documentUriBeingChecked)
}
return CompletableFuture.completedFuture(jsonObject)
}
companion object {
private const val CHECK_DOCUMENT_COMMAND_NAME = "_ltex.checkDocument"
private const val GET_SERVER_STATUS_COMMAND_NAME = "_ltex.getServerStatus"
private const val CHECK_CHECKING_STATUS_MILLISECONDS = 10L
private const val MILLISECONDS_PER_SECOND = 1e3
private const val NANOSECONDS_PER_SECOND = 1e9
private fun failCommand(errorMessage: String): CompletableFuture<Any> {
val jsonObject = JsonObject()
jsonObject.addProperty("success", false)
jsonObject.addProperty("errorMessage", errorMessage)
return CompletableFuture.completedFuture(jsonObject)
}
fun getCommandNames(): List<String> {
return listOf(CHECK_DOCUMENT_COMMAND_NAME, GET_SERVER_STATUS_COMMAND_NAME)
}
}
}