Exemplo n.º 1
0
        public static IChannelReader <T> SelectWith <T>(this IChannelReader <T> ext, int timeoutMillis, params IChannelReader <T>[] channels)
        {
            List <IChannelReader <T> > tmp = new List <IChannelReader <T> >(channels);

            tmp.Add(ext);
            return(ChannelReaderSync.Select <T>(timeoutMillis, tmp.ToArray()));
        }
Exemplo n.º 2
0
        public static AbstractShovelThread <S, D> ShovelTo <S, D>(this IChannelReader <S> ext, IChannelWriter <D> destination, Func <S, D> transform, TimeSpan lifeTime, bool closeOnDrain)
        {
            AbstractShovelThread <S, D> th = new FuncShovelThread <S, D>(transform, ext, destination, lifeTime, closeOnDrain);

            th.Start();
            return(th);
        }
Exemplo n.º 3
0
        public static AbstractActiveEnumerator <T> ActiveEnumerate <T>(this IChannelReader <T> ext, Action <T> handle, TimeSpan lifeTime)
        {
            AbstractActiveEnumerator <T> th = new FuncActiveEnumerator <T>(handle, ext, lifeTime);

            th.Start();
            return(th);
        }
Exemplo n.º 4
0
        public static IEnumerable <IChannelReader <T> > BarrierWith <T>(this IChannelReader <T> ext, int timeoutMillis, params IChannelReader <T>[] channels)
        {
            List <IChannelReader <T> > tmp = new List <IChannelReader <T> >(channels);

            tmp.Add(ext);
            return(ChannelReaderSync.Barrier <T>(timeoutMillis, tmp.ToArray()));
        }
Exemplo n.º 5
0
        public virtual void SyncSelect_Timeout()
        {
            int expected = 3;

            using (IChannel <int> c0 = new Channel <int>())
                using (IChannel <int> c1 = new Channel <int>())
                    using (IChannel <int> c2 = new Channel <int>())
                    {
                        Task.Factory.StartNew(() =>
                        {
                            Thread.Sleep(Timeblok);
                            c0.Write(expected);
                        });
                        Task.Factory.StartNew(() =>
                        {
                            Thread.Sleep(2 * Timeblok);
                            c1.Write(expected);
                        });
                        Task.Factory.StartNew(() =>
                        {
                            Thread.Sleep(3 * Timeblok);
                            c2.Write(expected);
                        });

                        IChannelReader <int> res = c0.SelectWith(Timeblok * 5, c1, c2);
                        Assert.AreEqual(c0, res);
                        Assert.AreEqual(expected, res.Read());

                        Assert.IsNull(c1.SelectWith(Timeblok / 2, c2));
                    }
        }
Exemplo n.º 6
0
        public virtual void SerializeObjects()
        {
            string         name = "test-SerializeObjects" + Salt;
            Queue <string> rq   = new Queue <string>(new string[] { "aaa", "aab", "abb", "bbb", "bbc", "bcc", "ccc" });
            Queue <string> wq   = new Queue <string>(new string[] { "aaa", "aab", "abb", "bbb", "bbc", "bcc", "ccc" });

            AbstractChannelsFactory fc = new RabbitMQChannelsFactory();

            Task tr = Task.Factory.StartNew(() => {
                using (IChannelReader <SerializeObjectsData> ch = fc.GetSubscribableChannel <SerializeObjectsData>(name).Subscribe())
                {
                    foreach (SerializeObjectsData item in ch.Enumerate())
                    {
                        Assert.AreEqual(item.OpId, rq.Dequeue());
                    }
                    Assert.IsTrue(ch.Drained);
                }
            });

            Task tw = Task.Factory.StartNew(() => {
                using (IChannelWriter <SerializeObjectsData> ch = fc.GetSubscribableChannel <SerializeObjectsData>(name))
                {
                    while (wq.Count > 0)
                    {
                        ch.Write(new SerializeObjectsData()
                        {
                            OpId = wq.Dequeue(), Status = "test", Message = "/messaggio/lungo/con/sbarre"
                        });
                    }
                    ch.Close();
                }
            });

            Task.WaitAll(tr, tw);
        }
 private void ProbeUntilConsumed(Func <bool> reading, IChannelReader reader)
 {
     do
     {
         reader.ProbeChannel();
     } while (reading());
 }
Exemplo n.º 8
0
        public virtual void CloseTest()
        {
            int count = 100;

            int[]      expected  = Enumerable.Range(0, count).ToArray();
            List <int> actualInt = new List <int>();
            Dictionary <string, string> testString = new Dictionary <string, string>()
            {
                { "val", "test" }
            };
            string queueName = "test-CloseTest" + Salt;

            using (ISubscribableChannel <Dictionary <string, string> > w = new mq.SubscribableChannel <Dictionary <string, string> >(queueName))
                using (IChannel <Dictionary <string, string> > c = new mq.Channel <Dictionary <string, string> >(queueName))
                {
                    IChannelReader <Dictionary <string, string> > t = w.Subscribe();

                    c.Close();

                    w.Write(testString);

                    Dictionary <string, string> result = t.Read();
                    Assert.IsTrue(result.ContainsKey("val"));
                    Assert.AreEqual(testString["val"], result["val"]);
                }
        }
Exemplo n.º 9
0
 public HermesConsumer(
     IChannelReader channelReader,
     IMessageAdapter messageAdapter)
 {
     _channelReader  = channelReader;
     _messageAdapter = messageAdapter;
 }
Exemplo n.º 10
0
        public virtual void SyncSelect()
        {
            int expected = 3;

            using (IChannel <int> c0 = new mq.Channel <int>("test-SyncSelect1" + Salt))
                using (IChannel <int> c1 = new mq.Channel <int>("test-SyncSelect2" + Salt))
                    using (IChannel <int> c2 = new mq.Channel <int>("test-SyncSelect3" + Salt))
                    {
                        Task.Factory.StartNew(() =>
                        {
                            Thread.Sleep(Timeblok);
                            c0.Write(expected);
                        });
                        Task.Factory.StartNew(() =>
                        {
                            Thread.Sleep(2 * Timeblok);
                            c1.Write(expected);
                        });
                        Task.Factory.StartNew(() =>
                        {
                            Thread.Sleep(3 * Timeblok);
                            c2.Write(expected);
                        });

                        IChannelReader <int> res = c0.SelectWith(c1, c2);
                        Assert.AreEqual(c0, res);
                        Assert.AreEqual(expected, res.Read());
                    }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Tries to propagate completion from the reader to the writer.
        /// </summary>
        /// <typeparam name="T">The type of the items in the reader and writer.</typeparam>
        /// <param name="reader">The reader.</param>
        /// <param name="writer">The writer.</param>
        /// <param name="passthroughError"><see langword="true"/> - passthrough error, <see langword="false"/> - mute error.</param>
        /// <returns>true, if completion was propagated, false otherwise.</returns>
        public static bool TryPropagateCompletion <T>(
            this IChannelReader <T> reader,
            IChannelWriter <T> writer,
            bool passthroughError = true)
        {
            VxArgs.NotNull(reader, nameof(reader));
            VxArgs.NotNull(writer, nameof(writer));

            if (reader.Completion.IsCompleted)
            {
                Exception error = null;
                try
                {
                    reader.Completion.GetAwaiter().GetResult();
                }
                catch (Exception ex)
                {
                    if (passthroughError)
                    {
                        error = ex;
                    }
                }

                return(writer.TryComplete(error));
            }

            return(false);
        }
Exemplo n.º 12
0
    private void ProbeUntilConsumed(Func <bool> reading, IChannelReader reader, int maxSeconds)
    {
        var sw = new Stopwatch();

        sw.Start();
        do
        {
            reader.ProbeChannel();
        } while (reading() || sw.Elapsed.TotalSeconds >= maxSeconds);
        sw.Stop();
    }
Exemplo n.º 13
0
        public AbstractActiveEnumerator(IChannelReader <S> source, TimeSpan lifeTime)
        {
            if (source == null)
            {
                throw new ArgumentNullException("'source' cannot be null.");
            }
            _source   = source;
            _lifeTime = lifeTime;

            _th = new Thread(Run);
        }
Exemplo n.º 14
0
 public InboundStreamActor(
     IInboundStreamInterest interest,
     AddressType addressType,
     IChannelReader reader,
     long probeInterval)
 {
     _interest      = interest;
     _addressType   = addressType;
     _reader        = reader;
     _probeInterval = probeInterval;
 }
Exemplo n.º 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ChannelRawVideoStreamReaderAdapter"/> class.
        /// </summary>
        /// <param name="innerReader">The BCL channel reader.</param>
        /// <param name="videoFormat">The format of the video stream.</param>
        /// <param name="firstFrameInstant">Binding of the video stream to the real world.</param>
        public ChannelRawVideoStreamReaderAdapter(
            IChannelReader <IRawVideoFrame> innerReader,
            RawVideoStreamFormat videoFormat,
            Instant?firstFrameInstant)
        {
            VxArgs.NotNull(innerReader, nameof(innerReader));
            VxArgs.NotNull(videoFormat, nameof(videoFormat));

            InnerReader       = innerReader;
            VideoFormat       = videoFormat;
            FirstFrameInstant = firstFrameInstant;
        }
        public SocketChannelWriterTest(ITestOutputHelper output)
        {
            var converter = new Converter(output);

            Console.SetOut(converter);

            var node   = Node.With(Id.Of(2), Name.Of("node2"), Host.Of("localhost"), 37377, 37378);
            var logger = ConsoleLogger.TestInstance();

            _channelWriter = new SocketChannelWriter(node.OperationalAddress, logger);
            _channelReader = new SocketChannelInboundReader(node.OperationalAddress.Port, "test-reader", 1024, logger);
        }
Exemplo n.º 17
0
 internal static void RemoveNamedReader <T>(string name, IChannelReader <T> reader)
 {
     if (_namedChannels.ContainsKey(name))
     {
         RemoveReader <T>(reader);
         _namedChannels[name].Item1.Remove(reader);
         if (_namedChannels[name].Item1.Count == 0 && _namedChannels[name].Item2.Count == 0)
         {
             _namedChannels.Remove(name);
         }
     }
 }
Exemplo n.º 18
0
        public InboundSocketChannelTest(ITestOutputHelper output)
        {
            var converter = new Converter(output);

            Console.SetOut(converter);
            var node   = Node.With(Id.Of(2), Name.Of("node2"), Host.Of("localhost"), _testPort, _testPort + 1);
            var logger = ConsoleLogger.TestInstance();

            _opChannel  = new ManagedOutboundSocketChannel(node, node.OperationalAddress, logger);
            _appChannel = new ManagedOutboundSocketChannel(node, node.ApplicationAddress, logger);
            _opReader   = new SocketChannelInboundReader(node.OperationalAddress.Port, "test-op", 1024, logger);
            _appReader  = new SocketChannelInboundReader(node.ApplicationAddress.Port, "test-app", 1024, logger);
            ++_testPort;
        }
Exemplo n.º 19
0
        public AbstractShovelThread(IChannelReader <S> source, IChannelWriter <D> destination, TimeSpan lifeTime, bool closeOnDrain)
            : base(source, lifeTime)
        {
            if (destination == null)
            {
                throw new ArgumentNullException("'destination' cannot be null.");
            }
            _destination  = destination;
            _closeOnDrain = closeOnDrain;

            _th = new Thread(Run);

            StoppedEvent += ChannelDrainedHandling;
        }
Exemplo n.º 20
0
 internal PersistentChannelReader(IChannelReader <T> reader, bool singleReader)
 {
     this.reader = reader;
     if (singleReader)
     {
         readLock = default;
         buffer   = new SingleReaderBuffer();
     }
     else
     {
         readLock = AsyncLock.Exclusive();
         buffer   = new MultipleReadersBuffer();
     }
     fileOptions = new FileCreationOptions(FileMode.Open, FileAccess.Read, FileShare.ReadWrite, FileOptions.Asynchronous | FileOptions.SequentialScan);
     cursor      = new ChannelCursor(reader.Location, StateFileName);
 }
Exemplo n.º 21
0
        public virtual void UntypedTypesTest2()
        {
            int count = 100;

            int[]      expected  = Enumerable.Range(0, count).ToArray();
            List <int> actualInt = new List <int>();
            Dictionary <string, string> testString = new Dictionary <string, string>()
            {
                { "val", "test" }
            };
            string queueName = "test-UntypedTypesTest2" + Salt;

            using (ISubscribableChannel <Dictionary <string, string> > w = new mq.SubscribableChannel <Dictionary <string, string> >(queueName))
            {
                IChannelReader <Dictionary <string, string> > t = w.Subscribe();

                #region bare rabbitmq
                ConnectionFactory fc = new ConnectionFactory()
                {
                    HostName = "code.test.aliaslab.net", Port = 5672, VirtualHost = "channels-lib", UserName = "******", Password = "******"
                };
                IConnection connection = fc.CreateConnection();
                IModel      _channel   = connection.CreateModel();

                _channel.BasicQos(0, 1, true);

                _channel.ExchangeDeclare(queueName, ExchangeType.Fanout, true, true, null);
                IBasicProperties prop = _channel.CreateBasicProperties();
                prop.ContentEncoding = "utf-8";
                prop.ContentType     = "application/json";
                prop.Persistent      = true;
                prop.Headers         = new Dictionary <string, object>();

                byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { name = "piero", age = 13 }));
                _channel.BasicPublish(queueName, "test", prop, data);

                _channel.BasicPublish("channels-subscribableChannelCollectorExchange", $"{queueName}", prop, data);

                #endregion

                w.Write(testString);

                Dictionary <string, string> result = t.Read();
                Assert.IsTrue(result.ContainsKey("name"));
                Assert.AreEqual("piero", result["name"]);
            }
        }
Exemplo n.º 22
0
 internal static Queue <T> AddReader <T>(IChannelReader <T> reader, Queue <T> queue)
 {
     if (_readers.ContainsKey(reader))
     {
         if (_readers[reader] != queue)
         {
             throw new InvalidOperationException("Impossible to associate a different queue to the already created channel end.");
         }
         return((Queue <T>)_readers[reader]);
     }
     else
     {
         Queue <T> qu = queue == null ? new Queue <T>() : queue;
         _readers.Add(reader, qu);
         return(qu);
     }
 }
Exemplo n.º 23
0
        internal static Queue <T> AddNamedReader <T>(string name, IChannelReader <T> reader, Queue <T> queue)
        {
            queue = AddReader <T>(reader, queue);

            if (!_namedChannels.ContainsKey(name))
            {
                _namedChannels.Add(name, new Tuple <List <object>, List <object> >(null, null));
            }
            if (_namedChannels[name].Item1.Contains(reader))
            {
                throw new Exception("Cannot attach mutiple times the same channel");
            }
            else
            {
                _namedChannels[name].Item1.Add(reader);
            }

            return(queue);
        }
Exemplo n.º 24
0
        public virtual void DifferentTypesTest()
        {
            int count = 100;

            int[]      expected   = Enumerable.Range(0, count).ToArray();
            List <int> actualInt  = new List <int>();
            string     testString = "test";
            string     queueName  = "test-DifferentTypesTest" + Salt;

            using (ISubscribableChannel <int> c = new mq.SubscribableChannel <int>(queueName))
                using (ISubscribableChannel <string> w = new mq.SubscribableChannel <string>(queueName))
                {
                    IChannelReader <string> t = w.Subscribe();
                    IChannelReader <int>    x = c.Subscribe();
                    Task.Factory.StartNew(() =>
                    {
                        for (int i = 0; i < count; i++)
                        {
                            if (i == 2)
                            {
                                w.Write(testString);
                            }
                            c.Write(i);
                        }

                        c.Close();
                    });

                    string val = t.Read();
                    foreach (int item in x.Enumerate())
                    {
                        actualInt.Add(item);
                    }
                    w.Write(testString + "1");
                    val = t.Read();

                    Assert.AreEqual(val, testString + "1");
                    Assert.IsFalse(t.Drained);
                    Assert.IsTrue(x.Drained);
                }
        }
Exemplo n.º 25
0
        public virtual void ConcurretSingleQueue()
        {
            string salt = Salt;

            using (IChannel <int> c1 = new mq.Channel <int>("test-ConcurretSingleQueue" + salt))
                using (IChannel <int> c2 = new mq.Channel <int>("test-ConcurretSingleQueue" + salt))
                {
                    c2.Write(1);
                    c1.Write(2);

                    IChannelReader <int> x = c1.SelectWith(c2);

                    Assert.AreEqual(1, x.Read());

                    IChannelReader <int> y = c1.SelectWith(c2);

                    Assert.AreNotEqual(x, y);
                    Assert.AreEqual(2, y.Read());
                    Console.WriteLine();
                }
        }
Exemplo n.º 26
0
 public ChannelReaderEnumerable(IChannelReader <T> ch)
 {
     _ch = ch;
 }
Exemplo n.º 27
0
 public FuncActiveEnumerator(Action <S> handle, IChannelReader <S> source, TimeSpan lifeTime)
     : base(source, lifeTime)
 {
     _func = handle;
 }
Exemplo n.º 28
0
 public DuplexHermesChannel(string channelName, NetworkStream networkStream)
 {
     _inputChannel  = new InputHermesChannel($"input_{channelName}", networkStream);
     _outputChannel = new OutputHermesChannel($"output_{channelName}", networkStream);
     Name           = channelName;
 }
 public FuncChannelOutputAdapter(IChannelReader <S> channel, Func <S, D> transform)
     : base(channel)
 {
     _func = transform;
 }
Exemplo n.º 30
0
 public FuncShovelThread(Func <S, D> transform, IChannelReader <S> source, IChannelWriter <D> destination, TimeSpan lifeTime, bool closeOnDrain)
     : base(source, destination, lifeTime, closeOnDrain)
 {
     _func = transform;
 }