Esempio n. 1
0
        public void StartsElectionAfterElectionTimeout()
        {
            // arrange
            var resetEvent = new ManualResetEvent(false);
            var timeout = TimeSpan.FromMilliseconds(100);
            var configMock = new Mock<IServerConfiguration>();
            configMock.Setup(mocked => mocked.ElectionTimeout).Returns(timeout);
            var config = configMock.Object;
            var scheduler = new EventLoop();
            var serverMock = new Mock<IConsensusServerStateApi>();
            serverMock.Setup(mocked => mocked.StartElection()).Callback(() => resetEvent.Set());
            serverMock.Setup(mocked => mocked.Configuration).Returns(config);
            serverMock.Setup(mocked => mocked.Scheduler).Returns(scheduler);
            var server = serverMock.Object;
            var state = new Follower(server);

            // act
            state.Start();
            var changedToCandidate = resetEvent.WaitOne(timeout + timeout);

            // assert
            Assert.That(changedToCandidate, Is.True, "An election timout should have occurred and the state should be changed to candidate");

            // cleanup
            scheduler.Dispose();
            resetEvent.Dispose();
        }
Esempio n. 2
0
        private static void Main(string[] args)
        {
            // create the event loop
            var loop = new EventLoop();

            // start it with a callback
            loop.Start(() => Console.WriteLine("Event loop has started"));

            // start a timer
            loop.SetTimeout(() => Console.WriteLine("Hello, I am a timeout happening after 1 second"), TimeSpan.FromSeconds(1));
            loop.SetInterval(() => Console.WriteLine("Hello, I am an interval happening every 2 seconds"), TimeSpan.FromSeconds(2));

            // read the app.config
            var appConfigFile = new FileInfo("NLoop.TestApp.exe.config");
            var promise = appConfigFile.ReadAllBytes(loop);
            promise.Then(content => Console.WriteLine("Success!! read {0} bytes from app.config", content.Length), reason => Console.WriteLine("Dread!! got an error: {0}", reason));

            // send a web request
            var httpClient = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com/");
            var httpPromise = httpClient.Send(loop, request);
            httpPromise.Then(content => Console.WriteLine("Success!! read {0} from google.com", content.StatusCode), reason => Console.WriteLine("Dread!! got an error: {0}", reason));
            //httpPromise.Cancel();

            // wait
            Console.WriteLine("Event loop is processing, press any key to exit");
            Console.Read();

            // we are done, dispose the loop so resources will be cleaned up
            loop.Dispose();
        }
        public void SetIntervalParameterChecking()
        {
            // arrange
            var loop = new EventLoop();
            loop.Start(() => { });
            var callback = new Action(() => { });
            var timeout = TimeSpan.FromMilliseconds(100);

            // assert
            Assert.That(() => ((EventLoop) null).SetInterval(callback, timeout), Throws.InstanceOf<ArgumentNullException>());
            Assert.That(() => loop.SetInterval(null, timeout), Throws.InstanceOf<ArgumentNullException>());

            // cleanup
            loop.Dispose();
        }
        /// <summary>
        /// Sends a <paramref name="request"/> using the given <paramref name="client"/>.
        /// </summary>
        /// <param name="client">The <see cref="HttpClient"/> on which to execute the request.</param>
        /// <param name="eventLoop">The <see cref="EventLoop"/> on which to execute callbacks.</param>
        /// <param name="request">The <see cref="HttpResponseMessage"/> which to send.</param>
        /// <returns>Returns a <see cref="Promise{HttpResponseMessage}"/> resolving to <see cref="HttpResponseMessage"/>.</returns>
        /// <exception cref="ArgumentNullException">Thrown if one of the arguments is null.</exception>
        public static CancelablePromise<HttpResponseMessage> Send(this HttpClient client, EventLoop eventLoop, HttpRequestMessage request)
        {
            // validate arguments
            if (client == null)
                throw new ArgumentNullException("client");
            if (eventLoop == null)
                throw new ArgumentNullException("eventLoop");
            if (request == null)
                throw new ArgumentNullException("request");

            // create the cancellation token
            var cts = new CancellationTokenSource();
            var token = cts.Token;

            // create the deferred
            var deferred = eventLoop.Defer<HttpResponseMessage>(cts.Cancel);

            // create a resource managed by the event loop
            eventLoop.TrackResource(token, Task.Run(() => {
                try
                {
                    // send the request and retrieve the response
                    var response = client.SendAsync(request, token).Result;

                    // resolve the deferred if not cancelled
                    if (!token.IsCancellationRequested)
                        deferred.Resolve(response);
                }
                catch (Exception ex)
                {
                    // something bad happened, reject the deferred if not cancelled
                    if (!token.IsCancellationRequested)
                        deferred.Reject(ex);
                }

                // dispose the used resources
                request.Dispose();
                cts.Dispose();
            }));

            // return the promise
            return deferred.Promise;
        }
        public void SetInterval()
        {
            // arrange
            var loop = new EventLoop();
            loop.Start(() => { });
            var counter = new CountdownEvent(2);
            var callback = new Action(() => counter.Signal());
            var timeout = TimeSpan.FromMilliseconds(100);

            // act
            loop.SetInterval(callback, timeout);

            // assert
            Assert.That(counter.Wait(timeout + timeout + timeout), Is.True);

            // cleanup
            loop.Dispose();
            counter.Dispose();
        }
        public void SetTimeout()
        {
            // arrange
            var loop = new EventLoop();
            loop.Start(() => { });
            var callbackinvoked = new ManualResetEvent(false);
            var callback = new Action(() => callbackinvoked.Set());
            var timeout = TimeSpan.FromMilliseconds(100);

            // act
            var cancelTimeout = loop.SetTimeout(callback, timeout);

            // assert
            Assert.That(cancelTimeout, Is.Not.Null);
            Assert.That(callbackinvoked.WaitOne(timeout + timeout), Is.True);

            // cleanup
            loop.Dispose();
            callbackinvoked.Dispose();
        }
        public void DisposesLogAndProtocol()
        {
            // arrange
            var configuration = new Mock<IServerConfiguration>().Object;
            var scheduler = new EventLoop();
            var logMock = new Mock<ILog>();
            var log = logMock.Object;
            var protocolMock = new Mock<IProtocol>();
            var protocol = protocolMock.Object;
            var server = new ConsensusServer(configuration, log, protocol, scheduler);

            // act
            server.Dispose();

            // assert
            logMock.Verify(x => x.Dispose(), Times.Once());
            protocolMock.Verify(x => x.Dispose(), Times.Once());

            // cleanup
            scheduler.Dispose();
        }