Creates a connection to the NATS server.
Ejemplo n.º 1
0
        public void TestClientAutoUnsub()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                long received = 0;
                int max = 10;

                using (ISyncSubscription s = c.SubscribeSync("foo"))
                {
                    s.AutoUnsubscribe(max);

                    for (int i = 0; i < max * 2; i++)
                    {
                        c.Publish("foo", null);
                    }
                    c.Flush();

                    Thread.Sleep(100);

                    try
                    {
                        while (true)
                        {
                            s.NextMessage(0);
                            received++;
                        }
                    }
                    catch (NATSBadSubscriptionException) { /* ignore */ }

                    Assert.IsTrue(received == max);
                    Assert.IsFalse(s.IsValid);
                }
            }
        }
Ejemplo n.º 2
0
        public void TestReconnectDisallowedFlags()
        {
            Options opts = ConnectionFactory.GetDefaultOptions();
            opts.Url = "nats://localhost:22222";
            opts.AllowReconnect = false;

            Object testLock = new Object();

            opts.ClosedEventHandler = (sender, args) =>
            {
                lock(testLock)
                {
                    Monitor.Pulse(testLock);
                }
            };

            using (NATSServer ns = utils.CreateServerOnPort(22222))
            {
                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    lock (testLock)
                    {
                        ns.Shutdown();
                        Assert.IsTrue(Monitor.Wait(testLock, 1000));
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public void TestServerAutoUnsub()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                long received = 0;
                int max = 10;

                using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                {
                    s.MessageHandler += (sender, arg) =>
                    {
                        System.Console.WriteLine("Received msg.");
                        received++;
                    };

                    s.AutoUnsubscribe(max);
                    s.Start();

                    for (int i = 0; i < (max * 2); i++)
                    {
                        c.Publish("foo", Encoding.UTF8.GetBytes("hello"));
                    }
                    c.Flush();

                    Thread.Sleep(500);

                    if (received != max)
                    {
                        Assert.Fail("Recieved ({0}) != max ({1})",
                            received, max);
                    }
                    Assert.IsFalse(s.IsValid);
                }
            }
        }
Ejemplo n.º 4
0
        public void TestServersOption()
        {
            IConnection c = null;
            ConnectionFactory cf = new ConnectionFactory();
            Options o = ConnectionFactory.GetDefaultOptions();

            o.NoRandomize = true;

            UnitTestUtilities.testExpectedException(
                () => { cf.CreateConnection(); },
                typeof(NATSNoServersException));

            o.Servers = testServers;

            UnitTestUtilities.testExpectedException(
                () => { cf.CreateConnection(o); },
                typeof(NATSNoServersException));

            // Make sure we can connect to first server if running
            using (NATSServer ns = utils.CreateServerOnPort(1222))
            {
                c = cf.CreateConnection(o);
                Assert.IsTrue(testServers[0].Equals(c.ConnectedUrl));
                c.Close();
            }

            // make sure we can connect to a non-first server.
            using (NATSServer ns = utils.CreateServerOnPort(1227))
            {
                c = cf.CreateConnection(o);
                Assert.IsTrue(testServers[5].Equals(c.ConnectedUrl));
                c.Close();
            }
        }
Ejemplo n.º 5
0
        public void TestAsyncSubHandlerAPI()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                int received = 0;

                EventHandler<MsgHandlerEventArgs> h = (sender, args) =>
                {
                    Interlocked.Increment(ref received);
                };

                using (IAsyncSubscription s = c.SubscribeAsync("foo", h))
                {
                    c.Publish("foo", null);
                    c.Flush();
                    Thread.Sleep(500);
                }

                using (IAsyncSubscription s = c.SubscribeAsync("foo", "bar", h))
                {
                    c.Publish("foo", null);
                    c.Flush();
                    Thread.Sleep(500);
                }

                if (received != 2)
                {
                    Assert.Fail("Received ({0}) != 2", received);
                }
            }
        }
Ejemplo n.º 6
0
        void IReqRepImpl.SetupConnection(ClientContextBase ctx)
        {
            Original.Options opts = ConnectionUtils.GetDefaultOptions();
            var cf = new Original.ConnectionFactory();

            ctx.Connection = cf.CreateConnection(opts);
        }
Ejemplo n.º 7
0
 public void TestConnectionStatus()
 {
     IConnection c = new ConnectionFactory().CreateConnection();
     Assert.AreEqual(ConnState.CONNECTED, c.State);
     c.Close();
     Assert.AreEqual(ConnState.CLOSED, c.State);
 }
Ejemplo n.º 8
0
        public void TestCustomObjectSerialization()
        {
            using (IEncodedConnection c = new ConnectionFactory().CreateEncodedConnection())
            {
                Object mu = new Object();
                SerializationTestObj origObj = new SerializationTestObj();

                EventHandler<EncodedMessageEventArgs> eh = (sender, args) =>
                {
                    // Ensure we blow up in the cast
                    SerializationTestObj so = (SerializationTestObj)args.ReceivedObject;
                    Assert.IsTrue(so.Equals(origObj));

                    lock (mu)
                    {
                        Monitor.Pulse(mu);
                    }
                };

                using (IAsyncSubscription s = c.SubscribeAsync("foo", eh))
                {
                    lock (mu)
                    {
                        c.Publish("foo", new SerializationTestObj());
                        c.Flush();

                        Monitor.Wait(mu, 1000);
                    }
                }
            }
        }
Ejemplo n.º 9
0
 public void TestSimplePublish()
 {
     using (IConnection c = new ConnectionFactory().CreateConnection())
     {
         c.Publish("foo", Encoding.UTF8.GetBytes("Hello World!"));
     }
 }
Ejemplo n.º 10
0
        public void Run(string[] args)
        {
            Stopwatch sw = null;

            parseArgs(args);
            banner();

            Options opts = ConnectionFactory.GetDefaultOptions();
            opts.Url = url;

            using (IConnection c = new ConnectionFactory().CreateConnection(opts))
            {
                sw = Stopwatch.StartNew();

                for (int i = 0; i < count; i++)
                {
                    c.Request(subject, payload);
                }
                c.Flush();

                sw.Stop();

                System.Console.Write("Completed {0} requests in {1} seconds ", count, sw.Elapsed.TotalSeconds);
                System.Console.WriteLine("({0} requests/second).",
                    (int)(count / sw.Elapsed.TotalSeconds));
                printStats(c);

            }
        }
Ejemplo n.º 11
0
        public void Run(string[] args)
        {
            parseArgs(args);
            banner();

            Options opts = ConnectionFactory.GetDefaultOptions();
            opts.Url = url;

            using (IConnection c = new ConnectionFactory().CreateConnection(opts))
            {
                TimeSpan elapsed;

                if (sync)
                {
                    elapsed = receiveSyncSubscriber(c);
                }
                else
                {
                    elapsed = receiveAsyncSubscriber(c);
                }

                System.Console.Write("Received {0} msgs in {1} seconds ", count, elapsed.TotalSeconds);
                System.Console.WriteLine("({0} msgs/second).",
                    (int)(count / elapsed.TotalSeconds));
                printStats(c);

            }
        }
Ejemplo n.º 12
0
        private void connectAndFail(String url)
        {
            try
            {
                System.Console.WriteLine("Trying: " + url);

                hitDisconnect = 0;
                Options opts = ConnectionFactory.GetDefaultOptions();
                opts.Url = url;
                opts.DisconnectedEventHandler += handleDisconnect;
                IConnection c = new ConnectionFactory().CreateConnection(url);

                Assert.Fail("Expected a failure; did not receive one");
                
                c.Close();
            }
            catch (Exception e)
            {
                if (e.Message.Contains("Authorization"))
                {
                    System.Console.WriteLine("Success with expected failure: " + e.Message);
                }
                else
                {
                    Assert.Fail("Unexpected exception thrown: " + e);
                }
            }
            finally
            {
                if (hitDisconnect > 0)
                    Assert.Fail("The disconnect event handler was incorrectly invoked.");
            }
        }
Ejemplo n.º 13
0
        public void TestBasicReconnectFunctionality()
        {
            Options opts = utils.DefaultTestOptions;
            opts.Url = "nats://localhost:22222";
            opts.MaxReconnect = 2;
            opts.ReconnectWait = 1000;

            Object testLock = new Object();
            Object msgLock = new Object();

            opts.DisconnectedEventHandler = (sender, args) =>
            {
                lock (testLock)
                {
                    Monitor.Pulse(testLock);
                }
            };

            opts.ReconnectedEventHandler = (sender, args) =>
            {
                // NOOP
            };

            NATSServer ns = utils.CreateServerOnPort(22222);

            using (IConnection c = new ConnectionFactory().CreateConnection(opts))
            {
                IAsyncSubscription s = c.SubscribeAsync("foo");
                s.MessageHandler += (sender, args) =>
                {
                    lock (msgLock)
                    {
                        Monitor.Pulse(msgLock);
                    }
                };

                s.Start();
                c.Flush();

                lock (testLock)
                {
                    ns.Shutdown();
                    Assert.True(Monitor.Wait(testLock, 100000));
                }

                c.Publish("foo", Encoding.UTF8.GetBytes("Hello"));

                // restart the server.
                using (ns = utils.CreateServerOnPort(22222))
                {
                    lock (msgLock)
                    {
                        c.Flush(50000);
                        Assert.True(Monitor.Wait(msgLock, 10000));
                    }

                    Assert.True(c.Stats.Reconnects == 1);
                }
            }
        }
Ejemplo n.º 14
0
        public void Run(string[] args)
        {
            parseArgs(args);
            banner();

            Options opts = ConnectionFactory.GetDefaultOptions();
            opts.Url = url;

            replyMsg.Data = Encoding.UTF8.GetBytes("reply");

            using (IConnection c = new ConnectionFactory().CreateConnection(opts))
            {
                TimeSpan elapsed;

                if (sync)
                {
                    elapsed = receiveSyncSubscriber(c);
                }
                else
                {
                    elapsed = receiveAsyncSubscriber(c);
                }

                System.Console.Write("Replied to {0} msgs in {1} seconds ", received, elapsed.TotalSeconds);
                System.Console.WriteLine("({0} replies/second).",
                    (int)(received / elapsed.TotalSeconds));
                printStats(c);

            }
        }
Ejemplo n.º 15
0
        public void TestAuthServers()
        {
            string[] plainServers = new string[] {
                "nats://*****:*****@localhost:1224"};

                opts.Servers = authServers;

                using (IConnection c = new ConnectionFactory().CreateConnection(opts))
                {
                    Assert.Equal(authServers[1], c.ConnectedUrl);
                }
            }
        }
Ejemplo n.º 16
0
        private static void NatsSubscribeMethod()
        {
            using (var c = new NC.ConnectionFactory().CreateEncodedConnection($"http://{Config.DOCKER_MACHINE_IP}:4222"))
            {
                c.OnDeserialize = Serializer.ProtobufDeserializer <User>;

                EventHandler <NC.EncodedMessageEventArgs> eh = (sender, args) =>
                {
                    var user      = (User)args.ReceivedObject;
                    var redisUser = GetUserFromRedis(user.Id.ToString());

                    Console.WriteLine(new string('*', 10));
                    Console.WriteLine($"User from NATS: {user}");
                    Console.WriteLine($"User from REDIS: {redisUser}");
                    Console.WriteLine($"Are users equal: {user.Equals(redisUser)}");
                };

                using (var s = c.SubscribeAsync("users", eh))
                {
                    Console.WriteLine("Waiting for a message..");
                    Console.WriteLine();

                    while (!string.IsNullOrEmpty(Console.ReadLine()))
                    {
                        Thread.Sleep(100);
                    }
                }
            }
        }
Ejemplo n.º 17
0
        public void TestCloseDisconnectedHandler()
        {
            bool disconnected = false;
            Object mu = new Object();

            Options o = ConnectionFactory.GetDefaultOptions();
            o.AllowReconnect = false;
            o.DisconnectedEventHandler += (sender, args) => {
                lock (mu)
                {
                    disconnected = true;
                    Monitor.Pulse(mu);
                }
            };

            IConnection c = new ConnectionFactory().CreateConnection(o);
            lock (mu)
            {
                c.Close();
                Monitor.Wait(mu, 20000);
            }
            Assert.IsTrue(disconnected);

            // now test using.
            disconnected = false;
            lock (mu)
            {
                using (c = new ConnectionFactory().CreateConnection(o)) { };
                Monitor.Wait(mu);
            }
            Assert.IsTrue(disconnected);
        }
Ejemplo n.º 18
0
        public FlowmakerConnection(string natsServerUrl = null)
        {
            var factorty = new NC.ConnectionFactory();

            _natsOptions     = NC.ConnectionFactory.GetDefaultOptions();
            _natsOptions.Url = natsServerUrl == null ? "demo.nats.io:4222" : natsServerUrl;
            _connection      = factorty.CreateConnection(_natsOptions);
        }
Ejemplo n.º 19
0
 public void TestAuthSuccess()
 {
     using (NATSServer s = util.CreateServerWithConfig(TestContext, "auth_1222.conf"))
     {
         IConnection c = new ConnectionFactory().CreateConnection("nats://*****:*****@localhost:1222");
         c.Close();
     }
 }
Ejemplo n.º 20
0
        private static void NatsPublishMethod(User user)
        {
            using (var c = new NC.ConnectionFactory().CreateEncodedConnection($"http://{Config.DOCKER_MACHINE_IP}:4222"))
            {
                c.OnSerialize = PCTestCommon.Serializer.ProtobufSerializer;

                c.Publish("users", user);
            }
        }
Ejemplo n.º 21
0
        private void ProducingWorker(object state)
        {
            var ctx = (MyWorkerContext)state;

            Original.Options opts = ConnectionUtils.GetDefaultOptions();
            var cf = new Original.ConnectionFactory();

            using (Original.IConnection conn = cf.CreateConnection(opts))
            {
                Workers.RunPublisher(conn, ctx);
            }
        }
Ejemplo n.º 22
0
        public void TestClosedConnections()
        {
            IConnection c = new ConnectionFactory().CreateConnection();
            ISyncSubscription s = c.SubscribeSync("foo");

            c.Close();

            // While we can annotate all the exceptions in the test framework,
            // just do it manually.
            UnitTestUtilities.testExpectedException(
                () => { c.Publish("foo", null); },
                typeof(NATSConnectionClosedException));

            UnitTestUtilities.testExpectedException(
                () => { c.Publish(new Msg("foo")); },
                typeof(NATSConnectionClosedException));

            UnitTestUtilities.testExpectedException(
                () => { c.SubscribeAsync("foo"); },
                typeof(NATSConnectionClosedException));

            UnitTestUtilities.testExpectedException(
                () => { c.SubscribeSync("foo"); },
                typeof(NATSConnectionClosedException));

            UnitTestUtilities.testExpectedException(
                () => { c.SubscribeAsync("foo", "bar"); },
                typeof(NATSConnectionClosedException));

            UnitTestUtilities.testExpectedException(
                () => { c.SubscribeSync("foo", "bar"); },
                typeof(NATSConnectionClosedException));

            UnitTestUtilities.testExpectedException(
                () => { c.Request("foo", null); },
                typeof(NATSConnectionClosedException));

            UnitTestUtilities.testExpectedException(
                () => { s.NextMessage(); },
                typeof(NATSConnectionClosedException));

            UnitTestUtilities.testExpectedException(
                () => { s.NextMessage(100); },
                typeof(NATSConnectionClosedException));

            UnitTestUtilities.testExpectedException(
                () => { s.Unsubscribe(); },
                typeof(NATSConnectionClosedException));

            UnitTestUtilities.testExpectedException(
                () => { s.AutoUnsubscribe(1); },
                typeof(NATSConnectionClosedException));
        }
Ejemplo n.º 23
0
 private bool isNatsServerRunning()
 {
     try
     {
         IConnection c = new NATS.Client.ConnectionFactory().CreateConnection();
         c.Close();
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Ejemplo n.º 24
0
        private void ConsumingWorker(object state)
        {
            var ctx = (MyWorkerContext)state;

            Original.Options opts = ConnectionUtils.GetDefaultOptions();
            var cf = new Original.ConnectionFactory();

            using (Original.IConnection conn = cf.CreateConnection(opts))
            {
                Workers.RunParallelPassiveConsumer(conn, ctx, ConsumingAgentCount);
                //Workers.RunParallelReactiveConsumer(conn, ctx, ConsumingAgentCount);
            }
        }
Ejemplo n.º 25
0
        public void TestMultipleClose()
        {
            IConnection c = new ConnectionFactory().CreateConnection();
            
            Task[] tasks = new Task[10];

            for (int i = 0; i < 10; i++)
            {

                tasks[i] = new Task(() => { c.Close(); });
                tasks[i].Start();
            }

            Task.WaitAll(tasks);
        }
Ejemplo n.º 26
0
        public void TestCloseHandler()
        {
            bool closed = false;

            Options o = ConnectionFactory.GetDefaultOptions();
            o.ClosedEventHandler += (sender, args) => { closed = true; };
            IConnection c = new ConnectionFactory().CreateConnection(o);
            c.Close();
            Assert.IsTrue(closed);

            // now test using.
            closed = false;
            using (c = new ConnectionFactory().CreateConnection(o)) { };
            Assert.IsTrue(closed);
        }
Ejemplo n.º 27
0
        public void TestConnectedServer()
        {
            IConnection c = new ConnectionFactory().CreateConnection();
           
            string u = c.ConnectedUrl;
            
            if (string.IsNullOrWhiteSpace(u))
                Assert.Fail("Invalid connected url {0}.", u);
                
            if (!Defaults.Url.Equals(u))
                Assert.Fail("Invalid connected url {0}.", u);

            c.Close();
            u = c.ConnectedUrl;

            if (u != null)
                Assert.Fail("Url is not null after connection is closed.");
        }
Ejemplo n.º 28
0
        public void TestEncodedInvalidObjectSerialization()
        {
            using (IEncodedConnection c = new ConnectionFactory().CreateEncodedConnection())
            {
                String myStr = "value";
                Object mu = new Object();

                bool hitException = false;

                EventHandler<EncodedMessageEventArgs> eh = (sender, args) =>
                {
                    // Ensure we blow up in the cast
                    try
                    {
                        Exception invalid = (Exception)args.ReceivedObject;
                    }
                    catch (Exception e)
                    {
                        hitException = true;
                        System.Console.WriteLine("Expected exception: " + e.Message);
                    }

                    Assert.IsTrue(hitException);

                    lock (mu)
                    {
                        Monitor.Pulse(mu);
                    }
                };

                using (IAsyncSubscription s = c.SubscribeAsync("foo", eh))
                {
                    lock (mu)
                    {
                        c.Publish("foo", myStr);
                        c.Flush();

                        Monitor.Wait(mu, 1000);
                    }
                }
            }
        }
Ejemplo n.º 29
0
 public NATSServer(bool verify)
 {
     createProcessStartInfo();
     p = Process.Start(psInfo);
     if (verify)
     {
         for (int i = 0; i < 10; i++)
         {
             try
             {
                 var c = new ConnectionFactory().CreateConnection();
                 c.Close();
                 break;
             }
             catch
             {
                 Thread.Sleep(i * 250);
             }
         }
     }
 }
Ejemplo n.º 30
0
        public void TestAsyncSubscribe()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                {
                    asyncSub = s;
                    s.MessageHandler += CheckReceivedAndValidHandler;
                    s.Start();

                    lock (mu)
                    {
                        received = false;
                        c.Publish("foo", omsg);
                        c.Flush();
                        Monitor.Wait(mu, 30000);
                    }

                    if (!received)
                        Assert.Fail("Did not receive message.");
                }
            }
        }
Ejemplo n.º 31
0
        public void TestAsyncSubscribersOnClose()
        {
            /// basically tests if the subscriber sub channel gets
            /// cleared on a close.
            Object waitCond = new Object();
            int callbacks = 0;

            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                {
                    s.MessageHandler += (sender, args) =>
                    {
                        callbacks++;
                        lock (waitCond)
                        {
                            Monitor.Wait(waitCond);
                        }
                    };

                    s.Start();

                    for (int i = 0; i < 10; i++)
                    {
                        c.Publish("foo", null);
                    }
                    c.Flush();

                    Thread.Sleep(500);
                    c.Close();

                    lock (waitCond)
                    {
                        Monitor.Pulse(waitCond);
                    }

                    Thread.Sleep(500);

                    Assert.IsTrue(callbacks == 1);
                }
            }
        }
Ejemplo n.º 32
0
        public void TestAsyncSubscriberStarvation()
        {
            Object waitCond = new Object();

            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (IAsyncSubscription helper = c.SubscribeAsync("helper"),
                                          start = c.SubscribeAsync("start"))
                {
                    helper.MessageHandler += (sender, arg) =>
                    {
                        System.Console.WriteLine("Helper");
                        c.Publish(arg.Message.Reply,
                            Encoding.UTF8.GetBytes("Hello"));
                    };
                    helper.Start();

                    start.MessageHandler += (sender, arg) =>
                    {
                        System.Console.WriteLine("Responsder");
		                string responseIB = c.NewInbox();
                        IAsyncSubscription ia = c.SubscribeAsync(responseIB);

                        ia.MessageHandler += (iSender, iArgs) =>
                        {
                            System.Console.WriteLine("Internal subscriber.");
                            lock (waitCond) { Monitor.Pulse(waitCond); }
                        };
                        ia.Start();
 
		                c.Publish("helper", responseIB,
                            Encoding.UTF8.GetBytes("Help me!"));
                    };

                    start.Start();
                     
                    c.Publish("start", Encoding.UTF8.GetBytes("Begin"));
                    c.Flush();

                    lock (waitCond) 
                    { 
                        Assert.IsTrue(Monitor.Wait(waitCond, 2000));
                    }
                }
            }
        }
Ejemplo n.º 33
0
        public void TestAsyncErrHandler()
        {
            Object subLock = new Object();
            object testLock = new Object();
            IAsyncSubscription s;


            Options opts = ConnectionFactory.GetDefaultOptions();
            opts.SubChannelLength = 10;

            bool handledError = false;

            using (IConnection c = new ConnectionFactory().CreateConnection(opts))
            {
                using (s = c.SubscribeAsync("foo"))
                {
                    opts.AsyncErrorEventHandler = (sender, args) =>
                    {
                        lock (subLock)
                        {
                            if (handledError)
                                return;

                            handledError = true;

                            Assert.IsTrue(args.Subscription == s);

                            System.Console.WriteLine("Expected Error: " + args.Error);
                            Assert.IsTrue(args.Error.Contains("Slow"));

                            // release the subscriber
                            Monitor.Pulse(subLock);
                        }

                        // release the test
                        lock (testLock) { Monitor.Pulse(testLock); }
                    };

                    bool blockedOnSubscriber = false;
                    s.MessageHandler += (sender, args) =>
                    {
                        lock (subLock)
                        {
                            if (blockedOnSubscriber)
                                return;

                            Console.WriteLine("Subscriber Waiting....");
                            Assert.IsTrue(Monitor.Wait(subLock, 10000));
                            Console.WriteLine("Subscriber done.");
                            blockedOnSubscriber = true;
                        }
                    };

                    s.Start();

                    lock(testLock)
                    {

                        for (int i = 0; i < (opts.SubChannelLength + 100); i++)
                        {
                            c.Publish("foo", null);
                        }
                        c.Flush(1000);

                        Assert.IsTrue(Monitor.Wait(testLock, 1000));
                    }
                }
            }
        }
Ejemplo n.º 34
0
        public void TestSlowAsyncSubscriber()
        {
            Options opts = ConnectionFactory.GetDefaultOptions();
            opts.SubChannelLength = 10;

            using (IConnection c = new ConnectionFactory().CreateConnection(opts))
            {
                using (IAsyncSubscription s = c.SubscribeAsync("foo"))
                {
                    Object mu = new Object();

                    s.MessageHandler += (sender, args) =>
                    {
                        lock (mu)
                        {
                            Console.WriteLine("Subscriber Waiting....");
                            Assert.IsTrue(Monitor.Wait(mu, 20000));
                            Console.WriteLine("Subscriber done.");
                        }
                    };

                    s.Start();

                    for (int i = 0; i < (opts.SubChannelLength + 100); i++)
                    {
                        c.Publish("foo", null);
                    }

                    int flushTimeout = 1000;

                    Stopwatch sw = new Stopwatch();
                    sw.Start();

                    bool flushFailed = false;
                    try
                    {
                        c.Flush(flushTimeout);
                    }
                    catch (Exception)
                    {
                        flushFailed = true;
                    }

                    sw.Stop();

                    lock (mu)
                    {
                        Monitor.Pulse(mu);
                    }

                    if (sw.ElapsedMilliseconds < flushTimeout)
                    {
                        Assert.Fail("elapsed ({0}) < timeout ({1})",
                            sw.ElapsedMilliseconds, flushTimeout);
                    }
                    
                    Assert.IsTrue(flushFailed);
                }
            }
        }
Ejemplo n.º 35
0
        // TODO [TestMethod]
        public void TestSlowSubscriber()
        {
            Options opts = ConnectionFactory.GetDefaultOptions();
            opts.SubChannelLength = 10;

            using (IConnection c = new ConnectionFactory().CreateConnection(opts))
            {
                using (ISyncSubscription s = c.SubscribeSync("foo"))
                {
                    for (int i =0; i < (opts.SubChannelLength+100); i++)
                    {
                        c.Publish("foo", null);
                    }

                    try
                    {
                        c.Flush();
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine(ex);
                        if (ex.InnerException != null)
                            System.Console.WriteLine(ex.InnerException);

                        throw ex;
                    }

                    try 
                    {
                        s.NextMessage();
                    }
                    catch (NATSSlowConsumerException)
                    {
                        return;
                    }
                    Assert.Fail("Did not receive an exception.");
                }
            } 
        }
Ejemplo n.º 36
0
        public void TestValidSubscriber()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (ISyncSubscription s = c.SubscribeSync("foo"))
                {
                    Assert.IsTrue(s.IsValid);

                    try { s.NextMessage(100); }
                    catch (NATSTimeoutException) { }

                    Assert.IsTrue(s.IsValid);

                    s.Unsubscribe();

                    Assert.IsFalse(s.IsValid);

                    try { s.NextMessage(100); }
                    catch (NATSBadSubscriptionException) { }
                }
            }
        }
Ejemplo n.º 37
0
        public void TestCloseSubRelease()
        {
            using (IConnection c = new ConnectionFactory().CreateConnection())
            {
                using (ISyncSubscription s = c.SubscribeSync("foo"))
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    try
                    {
                        new Task(() => { Thread.Sleep(100); c.Close(); }).Start();
                         s.NextMessage(10000);
                    }
                    catch (Exception) { /* ignore */ }

                    sw.Stop();

                    Assert.IsTrue(sw.ElapsedMilliseconds < 10000);
                }
            }
        }