/
ToolsServiceClient.cs
250 lines (209 loc) · 9.38 KB
/
ToolsServiceClient.cs
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
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DotNet.Interactive.Commands;
using Microsoft.DotNet.Interactive.Events;
using StreamJsonRpc;
namespace Microsoft.DotNet.Interactive.SqlServer;
public class ToolsServiceClient : IDisposable
{
private Process _process;
private JsonRpc _rpc;
private bool _initialized = false;
private readonly string _serviceExePath;
private readonly string _arguments;
public const string SqlToolsServiceEnvironmentVariableName = "DOTNET_SQLTOOLSSERVICE";
public ToolsServiceClient(string serviceExePath = null, string arguments = null)
{
_serviceExePath = serviceExePath;
_arguments = arguments;
if (string.IsNullOrWhiteSpace(_serviceExePath))
{
_serviceExePath = Environment.GetEnvironmentVariable(SqlToolsServiceEnvironmentVariableName);
}
if (string.IsNullOrWhiteSpace(_serviceExePath))
{
throw new ArgumentException("Path to SQL Tools Service executable was not provided.", nameof(serviceExePath));
}
}
public void Initialize()
{
if (!_initialized)
{
StartSqlToolsService();
_initialized = true;
}
}
private void StartSqlToolsService()
{
var startInfo = new ProcessStartInfo(_serviceExePath)
{
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = false,
Arguments = _arguments
};
_process = new Process
{
StartInfo = startInfo
};
_process.Start();
StartRpc(_process.StandardInput.BaseStream, _process.StandardOutput.BaseStream);
}
private void StartRpc(Stream stdIn, Stream stdOut)
{
_rpc = new JsonRpc(stdIn, stdOut);
AddLocalRpcMethod(nameof(HandleConnectionCompletion), "connection/complete");
AddLocalRpcMethod(nameof(HandleQueryCompletion), "query/complete");
AddLocalRpcMethod(nameof(HandleQueryMessage), "query/message");
AddLocalRpcMethod(nameof(HandleIntellisenseReady), "textDocument/intelliSenseReady");
_rpc.StartListening();
}
internal void StartTracing(Action<string> trace)
{
_rpc.TraceSource.Switch.Level = SourceLevels.Verbose;
_rpc.TraceSource.Listeners.Add(new AnonymousTraceListener(trace));
}
internal class AnonymousTraceListener : TraceListener
{
private readonly Action<string> _trace;
public AnonymousTraceListener(Action<string> trace) => _trace = trace;
public override void Write(string message) => _trace(message);
public override void WriteLine(string message) => _trace(message);
}
private void AddLocalRpcMethod(string localMethodName, string rpcMethodName)
{
_rpc.AddLocalRpcMethod(
handler: GetType().GetMethod(localMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic),
target: this,
methodRpcSettings: new JsonRpcMethodAttribute(rpcMethodName)
{
UseSingleObjectParameterDeserialization = true
});
}
public event EventHandler<ConnectionCompleteParams> OnConnectionComplete;
public event EventHandler<QueryCompleteParams> OnQueryComplete;
public event EventHandler<IntelliSenseReadyParams> OnIntellisenseReady;
public event EventHandler<MessageParams> OnQueryMessage;
public async Task<bool> ConnectAsync(ConnectParams connectParams)
{
try
{
return await _rpc.InvokeWithParameterObjectAsync<bool>("connection/connect", connectParams);
}
catch (ConnectionLostException ex)
{
if (_process.HasExited)
{
throw new InvalidOperationException($"{_serviceExePath} failed to start properly. Exit code: {_process.ExitCode}.", ex);
}
else
{
throw;
}
}
}
public async Task<bool> DisconnectAsync(Uri ownerUri)
{
var disconnectParams = new DisconnectParams() { OwnerUri = ownerUri.AbsolutePath };
return await _rpc.InvokeWithParameterObjectAsync<bool>("connection/disconnect", disconnectParams);
}
public async Task<IEnumerable<CompletionItem>> ProvideCompletionItemsAsync(Uri fileUri, RequestCompletions command)
{
await UpdateFileContentsAsync(fileUri, command.Code);
TextDocumentIdentifier docId = new TextDocumentIdentifier() { Uri = fileUri.AbsolutePath };
Position position = new Position() { Line = command.LinePosition.Line, Character = command.LinePosition.Character };
CompletionContext context = new CompletionContext() { TriggerKind = (int)CompletionTriggerKind.Invoked };
var completionParams = new CompletionParams() { TextDocument = docId, Position = position, Context = context };
var sqlCompletionItems = await _rpc.InvokeWithParameterObjectAsync<SqlCompletionItem[]>("textDocument/completion", completionParams);
return sqlCompletionItems.Select(item =>
{
return new CompletionItem(
displayText: item.Label,
kind: item.Kind is not null ? Enum.GetName(typeof(SqlCompletionItemKind), item.Kind) : string.Empty,
filterText: item.FilterText,
sortText: item.SortText,
insertText: item.InsertText,
documentation: item.Documentation);
});
}
/// <summary>
/// Updates the contents of the file at the provided path with the provided string.
/// If the file contents have changed, then a text change notification is also sent
/// to the tools service.
/// </summary>
private async Task UpdateFileContentsAsync(Uri fileUri, string newContents)
{
string oldFileContents = await File.ReadAllTextAsync(fileUri.LocalPath);
if (!oldFileContents.Equals(newContents))
{
await File.WriteAllTextAsync(fileUri.LocalPath, newContents);
await SendTextChangeNotificationAsync(fileUri, newContents, oldFileContents);
}
}
public async Task<QueryExecuteResult> ExecuteQueryStringAsync(Uri ownerUri, string queryString,
CancellationToken contextCancellationToken)
{
var queryParams = new QueryExecuteStringParams() { Query = queryString, OwnerUri = ownerUri.AbsolutePath };
return await _rpc.InvokeWithParameterObjectAsync<QueryExecuteResult>("query/executeString", queryParams, contextCancellationToken);
}
public async Task<QueryExecuteSubsetResult> ExecuteQueryExecuteSubsetAsync(QueryExecuteSubsetParams subsetParams,
CancellationToken cancellationToken)
{
return await _rpc.InvokeWithParameterObjectAsync<QueryExecuteSubsetResult>("query/subset", subsetParams, cancellationToken);
}
public async Task<QueryCancelResult> CancelQueryExecutionAsync(Uri ownerUri)
{
var cancelParams = new QueryCancelParams() { OwnerUri = ownerUri.AbsolutePath };
return await _rpc.InvokeWithParameterObjectAsync<QueryCancelResult>("query/cancel", cancelParams);
}
public async Task SendTextChangeNotificationAsync(Uri ownerUri, string newText, string oldText)
{
var textChangeParams = GetDocumentChangeForText(ownerUri, newText, oldText);
await _rpc.NotifyWithParameterObjectAsync("textDocument/didChange", textChangeParams);
}
public static DidChangeTextDocumentParams GetDocumentChangeForText(Uri ownerUri, string newText, string oldText)
{
var oldTextLines = oldText.Split('\n').Select(text => text.EndsWith('\r') ? text[0..^1] : text).ToArray();
var lastLineNum = Math.Max(0, oldTextLines.Length - 1);
var lastLine = oldTextLines.Length > 0 ? oldTextLines[lastLineNum] : string.Empty;
var lastCharacterNum = lastLine.Length;
var startPosition = new Position() { Line = 0, Character = 0 };
var endPosition = new Position() { Line = lastLineNum, Character = lastCharacterNum };
var textDoc = new VersionedTextDocumentIdentifier() { Uri = ownerUri.AbsolutePath, Version = 1 };
var changeRange = new Range() { Start = startPosition, End = endPosition };
var docChange = new TextDocumentChangeEvent() { Text = newText, Range = changeRange };
var changes = new TextDocumentChangeEvent[] { docChange };
return new DidChangeTextDocumentParams() { TextDocument = textDoc, ContentChanges = changes };
}
public void HandleConnectionCompletion(ConnectionCompleteParams connParams)
{
OnConnectionComplete(this, connParams);
}
public void HandleQueryCompletion(QueryCompleteParams queryParams)
{
OnQueryComplete(this, queryParams);
}
public void HandleQueryMessage(MessageParams messageParams)
{
OnQueryMessage(this, messageParams);
}
public void HandleIntellisenseReady(IntelliSenseReadyParams readyParams)
{
OnIntellisenseReady(this, readyParams);
}
public void Dispose()
{
_rpc.Dispose();
_process.Kill(true);
_process.Dispose();
}
}