CompilerServerApiTest.cs 16.7 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
2 3 4 5 6 7 8 9 10

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Roslyn.Test.Utilities;
using Xunit;
11
using System.IO.Pipes;
12

A
Andy Gocke 已提交
13
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
14 15 16 17 18
{
    public class CompilerServerApiTest : TestBase
    {
        private sealed class TestableClientConnection : IClientConnection
        {
19
            internal readonly string LoggingIdentifier = string.Empty;
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
            internal Task<BuildRequest> ReadBuildRequestTask = TaskFromException<BuildRequest>(new Exception());
            internal Task WriteBuildResponseTask = TaskFromException(new Exception());
            internal Task MonitorTask = TaskFromException(new Exception());
            internal Action CloseAction = delegate { };

            string IClientConnection.LoggingIdentifier
            {
                get { return LoggingIdentifier; }
            }

            Task<BuildRequest> IClientConnection.ReadBuildRequest(CancellationToken cancellationToken)
            {
                return ReadBuildRequestTask;
            }

            Task IClientConnection.WriteBuildResponse(BuildResponse response, CancellationToken cancellationToken)
            {
                return WriteBuildResponseTask;
            }

            Task IClientConnection.CreateMonitorDisconnectTask(CancellationToken cancellationToken)
            {
                return MonitorTask;
            }

            void IClientConnection.Close()
            {
                CloseAction();
            }
        }

51 52
        private sealed class TestableDiagnosticListener : IDiagnosticListener
        {
53
            public int ProcessedCount;
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
            public DateTime? LastProcessedTime;
            public TimeSpan? KeepAlive;

            public void ConnectionProcessed(int count)
            {
                ProcessedCount += count;
                LastProcessedTime = DateTime.Now;
            }

            public void UpdateKeepAlive(TimeSpan timeSpan)
            {
                KeepAlive = timeSpan;
            }
        }

69
        private static readonly BuildRequest s_emptyCSharpBuildRequest = new BuildRequest(
70 71 72 73
            1,
            BuildProtocolConstants.RequestLanguage.CSharpCompile,
            ImmutableArray<BuildRequest.Argument>.Empty);

74
        private static readonly BuildResponse s_emptyBuildResponse = new CompletedBuildResponse(
75 76 77 78 79
            returnCode: 0,
            utf8output: false,
            output: string.Empty,
            errorOutput: string.Empty);

80 81 82 83 84 85 86 87 88 89
        private const string HelloWorldSourceText = @"
using System;
class Hello
{
    static void Main()
    {
        Console.WriteLine(""Hello, world.""); 
    }
}";

90 91 92 93 94 95 96 97 98 99 100 101
        private static Task TaskFromException(Exception e)
        {
            return TaskFromException<bool>(e);
        }

        private static Task<T> TaskFromException<T>(Exception e)
        {
            var source = new TaskCompletionSource<T>();
            source.SetException(e);
            return source.Task;
        }

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
        private async Task<BuildRequest> CreateBuildRequest(string sourceText, TimeSpan? keepAlive = null)
        {
            var directory = Temp.CreateDirectory();
            var file = directory.CreateFile("temp.cs");
            await file.WriteAllTextAsync(sourceText).ConfigureAwait(false);

            var builder = ImmutableArray.CreateBuilder<BuildRequest.Argument>();
            if (keepAlive.HasValue)
            {
                builder.Add(new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.KeepAlive, argumentIndex: 0, value: keepAlive.Value.TotalSeconds.ToString()));
            }

            builder.Add(new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CurrentDirectory, argumentIndex: 0, value: directory.Path));
            builder.Add(new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CommandLineArgument, argumentIndex: 0, value: file.Path));

            return new BuildRequest(
                BuildProtocolConstants.ProtocolVersion,
                BuildProtocolConstants.RequestLanguage.CSharpCompile,
                builder.ToImmutable());
        }

        /// <summary>
        /// Run a C# compilation against the given source text using the provided named pipe name.
        /// </summary>
        private async Task<BuildResponse> RunCSharpCompile(string pipeName, string sourceText, TimeSpan? keepAlive = null)
        {
            using (var namedPipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut))
            {
                var buildRequest = await CreateBuildRequest(sourceText, keepAlive).ConfigureAwait(false);
131
                namedPipe.Connect(Timeout.Infinite);
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
                await buildRequest.WriteAsync(namedPipe, default(CancellationToken)).ConfigureAwait(false);
                return await BuildResponse.ReadAsync(namedPipe, default(CancellationToken)).ConfigureAwait(false);
            }
        }

        /// <summary>
        /// This returns an <see cref="IRequestHandler"/> that always returns <see cref="CompletedBuildResponse"/> without
        /// doing any work.
        /// </summary>
        private static Mock<IRequestHandler> CreateNopRequestHandler()
        {
            var requestHandler = new Mock<IRequestHandler>();
            requestHandler
                .Setup(x => x.HandleRequest(It.IsAny<BuildRequest>(), It.IsAny<CancellationToken>()))
                .Returns(new CompletedBuildResponse(0, utf8output: false, output: string.Empty, errorOutput: string.Empty));
            return requestHandler;
        }

150 151 152 153 154
        [Fact]
        public void NotifyCallBackOnRequestHandlerException()
        {
            var clientConnection = new TestableClientConnection();
            clientConnection.MonitorTask = Task.Delay(-1);
155
            clientConnection.ReadBuildRequestTask = Task.FromResult(s_emptyCSharpBuildRequest);
156 157 158 159 160 161 162 163

            var ex = new Exception();
            var handler = new Mock<IRequestHandler>();
            handler
                .Setup(x => x.HandleRequest(It.IsAny<BuildRequest>(), It.IsAny<CancellationToken>()))
                .Throws(ex);

            var invoked = false;
164
            FatalError.OverwriteHandler((providedEx) =>
165 166 167
            {
                Assert.Same(ex, providedEx);
                invoked = true;
168
            });
169 170
            var client = new ServerDispatcher.Connection(clientConnection, handler.Object);

171
            Assert.Throws(typeof(AggregateException), () => client.ServeConnection().Wait());
172 173 174 175 176 177 178
            Assert.True(invoked);
        }

        [Fact]
        public void ClientDisconnectCancelBuildAndReturnsFailure()
        {
            var clientConnection = new TestableClientConnection();
179
            clientConnection.ReadBuildRequestTask = Task.FromResult(s_emptyCSharpBuildRequest);
180 181 182 183 184 185 186 187 188 189 190 191 192 193

            var monitorTaskSource = new TaskCompletionSource<bool>();
            clientConnection.MonitorTask = monitorTaskSource.Task;

            var handler = new Mock<IRequestHandler>();
            var handlerTaskSource = new TaskCompletionSource<CancellationToken>();
            var releaseHandlerSource = new TaskCompletionSource<bool>();
            handler
                .Setup(x => x.HandleRequest(It.IsAny<BuildRequest>(), It.IsAny<CancellationToken>()))
                .Callback<BuildRequest, CancellationToken>((_, t) =>
                {
                    handlerTaskSource.SetResult(t);
                    releaseHandlerSource.Task.Wait();
                })
194
                .Returns(s_emptyBuildResponse);
195 196

            var client = new ServerDispatcher.Connection(clientConnection, handler.Object);
J
Jared Parsons 已提交
197
            var serveTask = client.ServeConnection();
198 199 200 201 202 203 204

            // Once this returns we know the Connection object has kicked off a compilation and 
            // started monitoring the disconnect task.  Can now initiate a disconnect in a known
            // state.
            var cancellationToken = handlerTaskSource.Task.Result;
            monitorTaskSource.SetResult(true);

J
Jared Parsons 已提交
205
            Assert.Equal(ServerDispatcher.CompletionReason.ClientDisconnect, serveTask.Result.CompletionReason);
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
            Assert.True(cancellationToken.IsCancellationRequested);

            // Now that the asserts are done unblock the "build" long running task.  Have to do this
            // last to simulate a build which is still running when the client disconnects.
            releaseHandlerSource.SetResult(true);
        }

        [Fact]
        public void ReadError()
        {
            var handler = new Mock<IRequestHandler>(MockBehavior.Strict);
            var ex = new Exception("Simulated read error.");
            var clientConnection = new TestableClientConnection();
            var calledClose = false;
            clientConnection.ReadBuildRequestTask = TaskFromException<BuildRequest>(ex);
            clientConnection.CloseAction = delegate { calledClose = true; };

            var client = new ServerDispatcher.Connection(clientConnection, handler.Object);
J
Jared Parsons 已提交
224
            Assert.Equal(ServerDispatcher.CompletionReason.CompilationNotStarted, client.ServeConnection().Result.CompletionReason);
225 226 227 228 229 230 231 232 233 234 235 236
            Assert.True(calledClose);
        }

        /// <summary>
        /// A failure to write the results to the client is considered a client disconnection.  Any error
        /// from when the build starts to when the write completes should be handled this way. 
        /// </summary>
        [Fact]
        public void WriteError()
        {
            var clientConnection = new TestableClientConnection();
            clientConnection.MonitorTask = Task.Delay(-1);
237
            clientConnection.ReadBuildRequestTask = Task.FromResult(s_emptyCSharpBuildRequest);
238 239 240 241
            clientConnection.WriteBuildResponseTask = TaskFromException(new Exception());
            var handler = new Mock<IRequestHandler>();
            handler
                .Setup(x => x.HandleRequest(It.IsAny<BuildRequest>(), It.IsAny<CancellationToken>()))
242
                .Returns(s_emptyBuildResponse);
243 244

            var client = new ServerDispatcher.Connection(clientConnection, handler.Object);
J
Jared Parsons 已提交
245
            Assert.Equal(ServerDispatcher.CompletionReason.ClientDisconnect, client.ServeConnection().Result.CompletionReason);
246 247 248 249 250 251 252 253 254 255
        }

        [Fact]
        public void KeepAliveNoConnections()
        {
            var keepAlive = TimeSpan.FromSeconds(3);
            var pipeName = Guid.NewGuid().ToString();
            var requestHandler = new Mock<IRequestHandler>(MockBehavior.Strict);
            var dispatcher = new ServerDispatcher(requestHandler.Object, new EmptyDiagnosticListener());
            var startTime = DateTime.Now;
256
            dispatcher.ListenAndDispatchConnections(pipeName, keepAlive);
257 258 259 260

            Assert.True((DateTime.Now - startTime) > keepAlive);
        }

J
Jared Parsons 已提交
261
        [Fact]
C
Charles Stoner 已提交
262
        public async Task FailedConnectionShouldCreateFailedConnectionData()
J
Jared Parsons 已提交
263 264 265 266 267 268 269
        {
            var tcs = new TaskCompletionSource<NamedPipeServerStream>();
            var handler = new Mock<IRequestHandler>(MockBehavior.Strict);
            var connectionDataTask = ServerDispatcher.CreateHandleConnectionTask(tcs.Task, handler.Object, CancellationToken.None);

            tcs.SetException(new Exception());
            var connectionData = await connectionDataTask.ConfigureAwait(false);
270
            Assert.Equal(ServerDispatcher.CompletionReason.CompilationNotStarted, connectionData.CompletionReason);
J
Jared Parsons 已提交
271 272 273
            Assert.Null(connectionData.KeepAlive);
        }

274 275 276
        /// <summary>
        /// Ensure server respects keep alive and shuts down after processing a single connection.
        /// </summary>
J
Jared Parsons 已提交
277
        [Fact(Skip = "https://github.com/dotnet/roslyn/issues/4301")]
278 279 280 281 282 283 284 285
        public async Task KeepAliveAfterSingleConnection()
        {
            var keepAlive = TimeSpan.FromSeconds(1);
            var listener = new TestableDiagnosticListener();
            var pipeName = Guid.NewGuid().ToString();
            var dispatcherTask = Task.Run(() =>
            {
                var dispatcher = new ServerDispatcher(CreateNopRequestHandler().Object, listener);
286
                dispatcher.ListenAndDispatchConnections(pipeName, keepAlive);
287 288 289 290 291 292 293 294 295 296 297 298 299
            });

            await RunCSharpCompile(pipeName, HelloWorldSourceText).ConfigureAwait(false);
            await dispatcherTask.ConfigureAwait(false);

            Assert.Equal(1, listener.ProcessedCount);
            Assert.True(listener.LastProcessedTime.HasValue);
            Assert.True((DateTime.Now - listener.LastProcessedTime.Value) > keepAlive);
        }

        /// <summary>
        /// Ensure server respects keep alive and shuts down after processing multiple connections.
        /// </summary>
J
Jared Parsons 已提交
300
        [Fact(Skip = "https://github.com/dotnet/roslyn/issues/4301")]
301 302 303 304 305 306 307 308
        public async Task KeepAliveAfterMultipleConnection()
        {
            var keepAlive = TimeSpan.FromSeconds(1);
            var listener = new TestableDiagnosticListener();
            var pipeName = Guid.NewGuid().ToString();
            var dispatcherTask = Task.Run(() =>
            {
                var dispatcher = new ServerDispatcher(new CompilerRequestHandler(Temp.CreateDirectory().Path), listener);
309
                dispatcher.ListenAndDispatchConnections(pipeName, keepAlive);
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
            });

            for (int i = 0; i < 5; i++)
            {
                await RunCSharpCompile(pipeName, HelloWorldSourceText).ConfigureAwait(false);
            }

            await dispatcherTask.ConfigureAwait(false);
            Assert.Equal(5, listener.ProcessedCount);
            Assert.True(listener.LastProcessedTime.HasValue);
            Assert.True((DateTime.Now - listener.LastProcessedTime.Value) > keepAlive);
        }

        /// <summary>
        /// Ensure server respects keep alive and shuts down after processing simultaneous connections.
        /// </summary>
J
Jared Parsons 已提交
326
        [Fact(Skip = "https://github.com/dotnet/roslyn/issues/4301")]
327 328 329 330 331 332 333 334
        public async Task KeepAliveAfterSimultaneousConnection()
        {
            var keepAlive = TimeSpan.FromSeconds(1);
            var listener = new TestableDiagnosticListener();
            var pipeName = Guid.NewGuid().ToString();
            var dispatcherTask = Task.Run(() =>
            {
                var dispatcher = new ServerDispatcher(new CompilerRequestHandler(Temp.CreateDirectory().Path), listener);
335
                dispatcher.ListenAndDispatchConnections(pipeName, keepAlive);
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
            });

            var list = new List<Task>();
            for (int i = 0; i < 5; i++)
            {
                var task = Task.Run(() => RunCSharpCompile(pipeName, HelloWorldSourceText));
                list.Add(task);
            }

            foreach (var current in list)
            {
                await current.ConfigureAwait(false);
            }

            await dispatcherTask.ConfigureAwait(false);
            Assert.Equal(5, listener.ProcessedCount);
            Assert.True(listener.LastProcessedTime.HasValue);
            Assert.True((DateTime.Now - listener.LastProcessedTime.Value) > keepAlive);
        }

J
Jared Parsons 已提交
356
        [Fact(Skip = "https://github.com/dotnet/roslyn/issues/4301")]
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
        public async Task FirstClientCanOverrideDefaultTimeout()
        {
            var cts = new CancellationTokenSource();
            var listener = new TestableDiagnosticListener();
            TimeSpan? newTimeSpan = null;
            var connectionSource = new TaskCompletionSource<int>();
            var diagnosticListener = new Mock<IDiagnosticListener>();
            diagnosticListener
                .Setup(x => x.UpdateKeepAlive(It.IsAny<TimeSpan>()))
                .Callback<TimeSpan>(ts => { newTimeSpan = ts; });
            diagnosticListener
                .Setup(x => x.ConnectionProcessed(It.IsAny<int>()))
                .Callback<int>(count => connectionSource.SetResult(count));

            var pipeName = Guid.NewGuid().ToString();
            var dispatcherTask = Task.Run(() =>
            {
                var dispatcher = new ServerDispatcher(CreateNopRequestHandler().Object, diagnosticListener.Object);
375
                dispatcher.ListenAndDispatchConnections(pipeName, TimeSpan.FromSeconds(1), cancellationToken: cts.Token);
376 377 378 379 380 381 382 383 384 385 386
            });

            var seconds = 10;
            var response = await RunCSharpCompile(pipeName, HelloWorldSourceText, TimeSpan.FromSeconds(seconds)).ConfigureAwait(false);
            Assert.Equal(BuildResponse.ResponseType.Completed, response.Type);
            Assert.Equal(1, await connectionSource.Task.ConfigureAwait(false));
            Assert.True(newTimeSpan.HasValue);
            Assert.Equal(seconds, newTimeSpan.Value.TotalSeconds);

            cts.Cancel();
            await dispatcherTask.ConfigureAwait(false);
387 388 389
        }
    }
}