-
-
Notifications
You must be signed in to change notification settings - Fork 960
/
services.ts
584 lines (545 loc) · 19.3 KB
/
services.ts
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
'use strict'
import { SpawnOptions } from 'child_process'
import type { DocumentSelector } from 'vscode-languageserver-protocol'
import type { TextDocument } from 'vscode-languageserver-textdocument'
import type { WorkspaceFolder } from 'vscode-languageserver-types'
import { URI } from 'vscode-uri'
import events from './events'
import { Executable, ForkOptions, LanguageClient, LanguageClientOptions, RevealOutputChannelOn, ServerOptions, State, Transport, TransportKind } from './language-client'
import { createLogger } from './logger'
import { disposeAll, wait } from './util'
import { toArray } from './util/array'
import { fs, net, path } from './util/node'
import { toObject } from './util/object'
import { CancellationToken, Disposable, Emitter, Event } from './util/protocol'
import window from './window'
import workspace from './workspace'
import { parseExtensionName } from './util/extensionRegistry'
const logger = createLogger('services')
export enum ServiceStat {
Initial,
Starting,
StartFailed,
Running,
Stopping,
Stopped,
}
interface ServiceInfo {
id: string
state: string
languageIds: string[]
}
export interface LanguageServerConfig {
module?: string
command?: string
transport?: string
transportPort?: number
maxRestartCount?: number
disableSnippetCompletion?: boolean
disableDynamicRegister?: boolean
disabledFeatures?: string[]
formatterPriority?: number
filetypes: string[]
additionalSchemes?: string[]
enable?: boolean
args?: string[]
cwd?: string
env?: any
// socket port
port?: number
host?: string
detached?: boolean
shell?: boolean
execArgv?: string[]
rootPatterns?: string[]
requireRootPattern?: boolean
ignoredRootPaths?: string[]
initializationOptions?: any
progressOnInitialization?: boolean
revealOutputChannelOn?: string
configSection?: string
stdioEncoding?: string
runtime?: string
}
export interface IServiceProvider {
// unique service id
id: string
name: string
client?: LanguageClient
selector: DocumentSelector
// current state
state: ServiceStat
start(): Promise<void> | void
dispose(): void
stop(): Promise<void> | void
restart(): Promise<void> | void
onServiceReady: Event<void>
}
export interface NotificationItem {
id: string
method: string
}
class ServiceManager implements Disposable {
private readonly registered: Map<string, IServiceProvider> = new Map()
private disposables: Disposable[] = []
private pendingNotifications: Map<string, NotificationItem[]> = new Map()
/**
* @deprecated
*/
public regist
/**
* @deprecated
*/
public registLanguageClient
constructor() {
this.registLanguageClient = this.registerLanguageClient.bind(this)
this.regist = this.register.bind(this)
}
public init(): void {
workspace.onDidOpenTextDocument(document => {
void this.start(document)
}, null, this.disposables)
const iterate = (folders: Iterable<WorkspaceFolder>) => {
for (let folder of folders) {
this.registerClientsFromFolder(folder)
}
}
workspace.onDidChangeWorkspaceFolders(e => {
iterate(e.added)
}, null, this.disposables)
// `languageserver.${name}`
// Global configured languageserver
let lspConfig = workspace.initialConfiguration.get<{ key: LanguageServerConfig }>('languageserver', {} as any)
this.registerClientsByConfig(lspConfig)
iterate(workspace.workspaceFolders)
workspace.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('languageserver')) {
let lspConfig = workspace.getConfiguration('languageserver', null)
this.registerClientsByConfig(lspConfig)
}
}, null, this.disposables)
}
private registerClientsFromFolder(workspaceFolder: WorkspaceFolder): void {
let uri = URI.parse(workspaceFolder.uri)
let lspConfig = workspace.getConfiguration(undefined, uri)
let config = lspConfig.inspect('languageserver').workspaceFolderValue
this.registerClientsByConfig(config as { [key: string]: LanguageServerConfig }, uri)
}
public register(service: IServiceProvider): Disposable {
let { id } = service
if (this.registered.get(id)) return
this.registered.set(id, service)
this.tryStartService(service)
service.onServiceReady(() => {
logger.info(`service ${id} started`)
}, null, this.disposables)
return Disposable.create(() => {
if (!this.registered.has(id)) return
service.dispose()
this.registered.delete(id)
})
}
public tryStartService(service: IServiceProvider): void {
if (!events.ready) {
let disposable = events.on('ready', () => {
disposable.dispose()
if (this.shouldStart(service)) {
void service.start()
}
})
} else if (this.shouldStart(service)) {
void service.start()
}
}
public getService(id: string): IServiceProvider {
let service = this.registered.get(id)
if (!service) service = this.registered.get(`languageserver.${id}`)
return service
}
private shouldStart(service: IServiceProvider): boolean {
if (service.state != ServiceStat.Initial) return false
let selector = service.selector
for (let doc of workspace.documents) {
if (workspace.match(selector, doc.textDocument)) {
return true
}
}
return false
}
public async start(document: TextDocument): Promise<void> {
let services: IServiceProvider[] = []
for (let service of this.registered.values()) {
if (service.state == ServiceStat.Initial && workspace.match(service.selector, document) > 0) {
services.push(service)
}
}
await Promise.allSettled(services.map(service => {
return service.start()
}))
}
public stop(id: string): Promise<void> {
let service = this.registered.get(id)
if (service) return Promise.resolve(service.stop())
}
public async toggle(id: string): Promise<void> {
let service = this.registered.get(id)
if (!service) throw new Error(`Service ${id} not found`)
let { state } = service
if (state == ServiceStat.Running) {
await Promise.resolve(service.stop())
} else if (state == ServiceStat.Initial || state == ServiceStat.StartFailed) {
await service.start()
} else if (state == ServiceStat.Stopped) {
await service.restart()
}
}
public getServiceStats(): ServiceInfo[] {
let res: ServiceInfo[] = []
for (let [id, service] of this.registered) {
res.push({
id,
languageIds: documentSelectorToLanguageIds(service.selector),
state: getStateName(service.state)
})
}
return res
}
private registerClientsByConfig(lspConfig: { [key: string]: LanguageServerConfig }, folder?: URI): void {
for (let key of Object.keys(toObject(lspConfig))) {
let config: LanguageServerConfig = lspConfig[key]
if (!isValidServerConfig(key, config)) {
continue
}
this.registerLanguageClient(key, config, folder)
}
}
private async getLanguageClient(id: string): Promise<LanguageClient> {
let service = this.getService(id)
// wait for extension activate
if (!service) await wait(100)
service = this.getService(id)
if (!service || !service.client) {
throw new Error(`Language server ${id} not found`)
}
return service.client
}
public async sendNotification(id: string, method: string, params?: any): Promise<void> {
let client = await this.getLanguageClient(id)
await Promise.resolve(client.sendNotification(method, params))
}
public async sendRequest(id: string, method: string, params?: any, token?: CancellationToken): Promise<any> {
let client = await this.getLanguageClient(id)
token = token ?? CancellationToken.None
return await Promise.resolve(client.sendRequest(method, params, token))
}
public registerNotification(id: string, method: string): void {
let service = this.getService(id)
if (service && service.client) {
service.client.onNotification(method, async result => {
this.sendNotificationVim(id, method, result)
})
}
let arr = this.pendingNotifications.get(id) ?? []
arr.push({ id, method })
this.pendingNotifications.set(id, arr)
}
private getRegisteredNotifications(id: string): NotificationItem[] {
id = id.startsWith('languageserver') ? id.slice('languageserver.'.length) : id
return this.pendingNotifications.get(id) ?? []
}
private sendNotificationVim(id: string, method: string, result: any): void {
workspace.nvim.call('coc#do_notify', [id, method, result], true)
}
public registerLanguageClient(client: LanguageClient): Disposable
public registerLanguageClient(name: string, config: LanguageServerConfig, folder?: URI): Disposable
public registerLanguageClient(name: string | LanguageClient, config?: LanguageServerConfig, folder?: URI): Disposable {
const registeredExtensionName = parseExtensionName(Error().stack)
let id = typeof name === 'string' ? `languageserver.${name}` : name.id
let disposables: Disposable[] = []
let onDidServiceReady = new Emitter<void>()
let client: LanguageClient | null = typeof name === 'string' ? null : name
if (this.registered.has(id)) return Disposable.create(() => {})
if (client && typeof client.dispose === 'function') disposables.push(client)
if (client) client.registeredExtensionName = registeredExtensionName
let created = false
let service: IServiceProvider = {
id,
client,
name: typeof name === 'string' ? name : name.name,
selector: typeof name === 'string' ? getDocumentSelector(config.filetypes, config.additionalSchemes) : name.clientOptions.documentSelector,
state: client && client.state === State.Running ? ServiceStat.Running : ServiceStat.Initial,
onServiceReady: onDidServiceReady.event,
start: async (): Promise<void> => {
if (!created) {
if (typeof name == 'string' && !client) {
let config: LanguageServerConfig = workspace.getConfiguration(undefined, folder).get(`languageserver.${name}`, {} as any)
let opts = getLanguageServerOptions(id, name, config, folder)
if (!opts || config.enable === false) return
client = new LanguageClient(id, name, opts[1], opts[0])
client.registeredExtensionName = registeredExtensionName
service.selector = opts[0].documentSelector
service.client = client
disposables.push(client)
}
created = true
for (let item of this.getRegisteredNotifications(id)) {
service.client.onNotification(item.method, async result => {
this.sendNotificationVim(item.id, item.method, result)
})
}
client.onDidChangeState(changeEvent => {
let { oldState, newState } = changeEvent
service.state = convertState(newState)
let oldStr = stateString(oldState)
let newStr = stateString(newState)
logger.info(`LanguageClient ${client.name} state change: ${oldStr} => ${newStr}`)
}, null, disposables)
}
try {
if (!client.needsStart()) {
service.state = convertState(client.state)
} else {
service.state = ServiceStat.Starting
logger.debug(`starting service: ${id}`)
await client.start()
onDidServiceReady.fire(void 0)
}
} catch (e) {
void window.showErrorMessage(`Server ${id} failed to start: ${e}`)
logger.error(`Server ${id} failed to start:`, e)
service.state = ServiceStat.StartFailed
}
},
dispose: async () => {
onDidServiceReady.dispose()
disposeAll(disposables)
},
stop: async (): Promise<void> => {
if (!client || !client.needsStop()) return
await Promise.resolve(client.stop())
},
restart: async (): Promise<void> => {
if (client) {
service.state = ServiceStat.Starting
await client.restart()
} else {
await service.start()
}
},
}
return this.register(service)
}
public dispose(): void {
disposeAll(this.disposables)
for (let service of this.registered.values()) {
service.dispose()
}
this.registered.clear()
}
}
export function documentSelectorToLanguageIds(documentSelector: DocumentSelector): string[] {
let res = documentSelector.map(filter => {
if (typeof filter == 'string') {
return filter
}
return filter.language
})
res = res.filter(s => typeof s == 'string')
return Array.from(new Set(res))
}
// convert config to options
export function getLanguageServerOptions(id: string, name: string, config: Readonly<LanguageServerConfig>, folder?: URI): [LanguageClientOptions, ServerOptions] {
let { command, module, port, args, filetypes } = config
args = args || []
if (!filetypes) {
void window.showErrorMessage(`Wrong configuration of LS "${name}", filetypes not found`)
return null
}
if (!command && !module && !port) {
void window.showErrorMessage(`Wrong configuration of LS "${name}", no command or module specified.`)
return null
}
let serverOptions: ServerOptions
if (module) {
module = workspace.expand(module)
if (!fs.existsSync(module)) {
void window.showErrorMessage(`Module file "${module}" not found for LS "${name}"`)
return null
}
serverOptions = {
module,
runtime: config.runtime ?? process.execPath,
args,
transport: getTransportKind(config),
options: getForkOptions(config)
}
} else if (command) {
serverOptions = {
command,
args,
options: getSpawnOptions(config)
} as Executable
} else {
serverOptions = () => new Promise((resolve, reject) => {
let client = new net.Socket()
let host = config.host ?? '127.0.0.1'
logger.info(`languageserver "${id}" connecting to ${host}:${port}`)
client.connect(port, host, () => {
resolve({
reader: client,
writer: client
})
})
client.on('error', e => {
reject(new Error(`Connection error for ${id}: ${e.message}`))
})
})
}
// compatible
let disabledFeatures: string[] = Array.from(config.disabledFeatures || [])
for (let key of ['disableWorkspaceFolders', 'disableCompletion', 'disableDiagnostics']) {
if (config[key] === true) {
logger.warn(`Language server config "${key}" is deprecated, use "disabledFeatures" instead.`)
let s = key.slice(7)
disabledFeatures.push(s[0].toLowerCase() + s.slice(1))
}
}
let disableSnippetCompletion = !!config.disableSnippetCompletion
let ignoredRootPaths = toArray(config.ignoredRootPaths)
let clientOptions: LanguageClientOptions = {
workspaceFolder: folder == null ? undefined : { name: path.basename(folder.fsPath), uri: folder.toString() },
rootPatterns: config.rootPatterns,
requireRootPattern: config.requireRootPattern,
ignoredRootPaths: ignoredRootPaths.map(s => workspace.expand(s)),
disableSnippetCompletion,
disableDynamicRegister: !!config.disableDynamicRegister,
disabledFeatures,
formatterPriority: config.formatterPriority,
documentSelector: getDocumentSelector(config.filetypes, config.additionalSchemes),
revealOutputChannelOn: getRevealOutputChannelOn(config.revealOutputChannelOn),
synchronize: {
configurationSection: `${id}.settings`
},
diagnosticCollectionName: name,
outputChannelName: id,
stdioEncoding: config.stdioEncoding,
progressOnInitialization: config.progressOnInitialization === true,
initializationOptions: config.initializationOptions ?? {}
}
if (config.maxRestartCount) {
clientOptions.connectionOptions = { maxRestartCount: config.maxRestartCount }
}
return [clientOptions, serverOptions]
}
export function isValidServerConfig(key: string, config: Partial<LanguageServerConfig>): boolean {
let errors: string[] = []
let fields = ['module', 'command', 'transport']
for (let field of fields) {
let val = config[field]
if (val && typeof val !== 'string') {
errors.push(`"${field}" field of languageserver ${key} should be string`)
}
}
if (config.transportPort != null && typeof config.transportPort !== 'number') {
errors.push(`"transportPort" field of languageserver ${key} should be number`)
}
if (!Array.isArray(config.filetypes) || !config.filetypes.every(s => typeof s === 'string')) {
errors.push(`"filetypes" field of languageserver ${key} should be array of string`)
}
if (config.additionalSchemes && (!Array.isArray(config.additionalSchemes) || config.additionalSchemes.some(s => typeof s !== 'string'))) {
errors.push(`"additionalSchemes" field of languageserver ${key} should be array of string`)
}
if (errors.length) {
logger.error(`Invalid language server configuration for ${key}`, errors.join('\n'))
return false
}
return true
}
export function getRevealOutputChannelOn(revealOn: string | undefined): RevealOutputChannelOn {
switch (revealOn) {
case 'info':
return RevealOutputChannelOn.Info
case 'warn':
return RevealOutputChannelOn.Warn
case 'error':
return RevealOutputChannelOn.Error
case 'never':
return RevealOutputChannelOn.Never
default:
return RevealOutputChannelOn.Never
}
}
export function getDocumentSelector(filetypes: string[] | undefined, additionalSchemes?: string[]): DocumentSelector {
let documentSelector: DocumentSelector = []
let schemes = ['file', 'untitled'].concat(additionalSchemes || [])
if (!filetypes) return schemes.map(s => ({ scheme: s }))
filetypes.forEach(filetype => {
documentSelector.push(...schemes.map(scheme => ({ language: filetype, scheme })))
})
return documentSelector
}
export function getTransportKind(config: LanguageServerConfig): Transport {
let { transport, transportPort } = config
if (!transport || transport == 'ipc') return TransportKind.ipc
if (transport == 'stdio') return TransportKind.stdio
if (transport == 'pipe') return TransportKind.pipe
return { kind: TransportKind.socket, port: transportPort }
}
export function getForkOptions(config: LanguageServerConfig): ForkOptions {
return {
cwd: config.cwd,
execArgv: config.execArgv ?? [],
env: config.env ?? undefined
}
}
export function getSpawnOptions(config: LanguageServerConfig): SpawnOptions {
return {
cwd: config.cwd,
detached: !!config.detached,
shell: !!config.shell,
env: config.env ?? undefined
}
}
export function convertState(state: State): ServiceStat {
switch (state) {
case State.Running:
return ServiceStat.Running
case State.Starting:
return ServiceStat.Starting
case State.Stopped:
return ServiceStat.Stopped
default:
return undefined
}
}
export function stateString(state: State): string {
switch (state) {
case State.Running:
return 'running'
case State.Starting:
return 'starting'
case State.Stopped:
return 'stopped'
default:
return 'unknown'
}
}
export function getStateName(state: ServiceStat): string {
switch (state) {
case ServiceStat.Initial:
return 'init'
case ServiceStat.Running:
return 'running'
case ServiceStat.Starting:
return 'starting'
case ServiceStat.StartFailed:
return 'startFailed'
case ServiceStat.Stopping:
return 'stopping'
case ServiceStat.Stopped:
return 'stopped'
default:
return 'unknown'
}
}
export default new ServiceManager()