Exemplo n.º 1
0
        private static bool SendMessage(Publication pub, UnsafeBuffer buffer, string text)
        {
            Log?.WriteLine($"send: [session 0x{pub.SessionId}] {text}");

            var value = Encoding.UTF8.GetBytes(text);

            buffer.PutBytes(0, value);

            long result = 0;

            for (int ix = 0; ix < 5; ++ix)
            {
                result = pub.Offer(buffer, 0, text.Length);
                if (result < 0)
                {
                    try
                    {
                        Thread.Sleep(100);
                    }
                    catch (ThreadInterruptedException)
                    {
                        Thread.CurrentThread.Interrupt();
                    }
                    continue;
                }
                return(true);
            }

            Log?.WriteLine($"could not send: {result}");
            return(false);
        }
Exemplo n.º 2
0
        public long AppendUnfragmentedMessage(HeaderWriter header, UnsafeBuffer srcBuffer, int srcOffset, int length, ReservedValueSupplier reservedValueSupplier)
#endif
        {
            int  frameLength   = length + DataHeaderFlyweight.HEADER_LENGTH;
            int  alignedLength = BitUtil.Align(frameLength, FrameDescriptor.FRAME_ALIGNMENT);
            long rawTail       = GetAndAddRawTail(alignedLength);
            long termOffset    = rawTail & 0xFFFFFFFFL;

            UnsafeBuffer termBuffer = _termBuffer;
            int          termLength = termBuffer.Capacity;

            long resultingOffset = termOffset + alignedLength;

            if (resultingOffset > termLength)
            {
                resultingOffset = HandleEndOfLogCondition(termBuffer, termOffset, header, termLength, LogBufferDescriptor.TermId(rawTail));
            }
            else
            {
                int offset = (int)termOffset;
                header.Write(termBuffer, offset, frameLength, LogBufferDescriptor.TermId(rawTail));
                termBuffer.PutBytes(offset + DataHeaderFlyweight.HEADER_LENGTH, srcBuffer, srcOffset, length);

                if (null != reservedValueSupplier)
                {
                    long reservedValue = reservedValueSupplier(termBuffer, offset, frameLength);
                    termBuffer.PutLong(offset + DataHeaderFlyweight.RESERVED_VALUE_OFFSET, reservedValue);
                }

                FrameDescriptor.FrameLengthOrdered(termBuffer, offset, frameLength);
            }

            return(resultingOffset);
        }
Exemplo n.º 3
0
        public int AppendFragmentedMessage(HeaderWriter header, IDirectBuffer srcBuffer, int srcOffset, int length,
                                           int maxPayloadLength, ReservedValueSupplier reservedValueSupplier, int activeTermId)
        {
            int          numMaxPayloads   = length / maxPayloadLength;
            int          remainingPayload = length % maxPayloadLength;
            int          lastFrameLength  = remainingPayload > 0 ? BitUtil.Align(remainingPayload + DataHeaderFlyweight.HEADER_LENGTH, FrameDescriptor.FRAME_ALIGNMENT) : 0;
            int          requiredLength   = (numMaxPayloads * (maxPayloadLength + DataHeaderFlyweight.HEADER_LENGTH)) + lastFrameLength;
            long         rawTail          = GetAndAddRawTail(requiredLength);
            int          termId           = LogBufferDescriptor.TermId(rawTail);
            long         termOffset       = rawTail & 0xFFFFFFFFL;
            UnsafeBuffer termBuffer       = _termBuffer;
            int          termLength       = termBuffer.Capacity;

            CheckTerm(activeTermId, termId);

            long resultingOffset = termOffset + requiredLength;

            if (resultingOffset > termLength)
            {
                resultingOffset = HandleEndOfLogCondition(termBuffer, termOffset, header, termLength, termId);
            }
            else
            {
                int  frameOffset = (int)termOffset;
                byte flags       = FrameDescriptor.BEGIN_FRAG_FLAG;
                int  remaining   = length;

                do
                {
                    int bytesToWrite  = Math.Min(remaining, maxPayloadLength);
                    int frameLength   = bytesToWrite + DataHeaderFlyweight.HEADER_LENGTH;
                    int alignedLength = BitUtil.Align(frameLength, FrameDescriptor.FRAME_ALIGNMENT);

                    header.Write(termBuffer, frameOffset, frameLength, termId);
                    termBuffer.PutBytes(frameOffset + DataHeaderFlyweight.HEADER_LENGTH, srcBuffer,
                                        srcOffset + (length - remaining), bytesToWrite);

                    if (remaining <= maxPayloadLength)
                    {
                        flags |= FrameDescriptor.END_FRAG_FLAG;
                    }

                    FrameDescriptor.FrameFlags(termBuffer, frameOffset, flags);

                    if (null != reservedValueSupplier)
                    {
                        long reservedValue = reservedValueSupplier(termBuffer, frameOffset, frameLength);
                        termBuffer.PutLong(frameOffset + DataHeaderFlyweight.RESERVED_VALUE_OFFSET, reservedValue, ByteOrder.LittleEndian);
                    }

                    FrameDescriptor.FrameLengthOrdered(termBuffer, frameOffset, frameLength);

                    flags        = 0;
                    frameOffset += alignedLength;
                    remaining   -= bytesToWrite;
                } while (remaining > 0);
            }

            return((int)resultingOffset);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Receive one message from the broadcast buffer.
        /// </summary>
        /// <param name="handler"> to be called for each message received. </param>
        /// <returns> the number of messages that have been received. </returns>
        public int Receive(MessageHandler handler)
        {
            var messagesReceived    = 0;
            var receiver            = _receiver;
            var lastSeenLappedCount = receiver.LappedCount();

            if (receiver.ReceiveNext())
            {
                if (lastSeenLappedCount != receiver.LappedCount())
                {
                    throw new InvalidOperationException("Unable to keep up with broadcast buffer");
                }

                var length   = receiver.Length();
                var capacity = _scratchBuffer.Capacity;
                if (length > capacity)
                {
                    throw new InvalidOperationException($"Buffer required length of {length:D} but only has {capacity:D}");
                }

                var msgTypeId = receiver.TypeId();
                _scratchBuffer.PutBytes(0, receiver.Buffer(), receiver.Offset(), length);

                if (!receiver.Validate())
                {
                    throw new InvalidOperationException("Unable to keep up with broadcast buffer");
                }

                handler(msgTypeId, _scratchBuffer, 0, length);

                messagesReceived = 1;
            }

            return(messagesReceived);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Append an unfragmented message to the the term buffer.
        /// </summary>
        /// <param name="header">                for writing the default header. </param>
        /// <param name="bufferOne">             containing the first part of the message. </param>
        /// <param name="offsetOne">             at which the first part of the message begins. </param>
        /// <param name="lengthOne">             of the first part of the message. </param>
        /// <param name="bufferTwo">             containing the second part of the message. </param>
        /// <param name="offsetTwo">             at which the second part of the message begins. </param>
        /// <param name="lengthTwo">             of the second part of the message. </param>
        /// <param name="reservedValueSupplier"> <seealso cref="ReservedValueSupplier"/> for the frame. </param>
        /// <param name="activeTermId">          used for flow control. </param>
        /// <returns> the resulting offset of the term after the append on success otherwise <seealso cref="FAILED"/> </returns>
        public int AppendUnfragmentedMessage(
            HeaderWriter header,
            IDirectBuffer bufferOne,
            int offsetOne,
            int lengthOne,
            IDirectBuffer bufferTwo,
            int offsetTwo,
            int lengthTwo,
            ReservedValueSupplier reservedValueSupplier,
            int activeTermId)
        {
            int          frameLength   = lengthOne + lengthTwo + DataHeaderFlyweight.HEADER_LENGTH;
            int          alignedLength = BitUtil.Align(frameLength, FrameDescriptor.FRAME_ALIGNMENT);
            UnsafeBuffer termBuffer    = _termBuffer;
            int          termLength    = termBuffer.Capacity;

            long rawTail    = GetAndAddRawTail(alignedLength);
            int  termId     = LogBufferDescriptor.TermId(rawTail);
            long termOffset = rawTail & 0xFFFF_FFFFL;

            CheckTerm(activeTermId, termId);

            long resultingOffset = termOffset + alignedLength;

            if (resultingOffset > termLength)
            {
                resultingOffset = HandleEndOfLogCondition(termBuffer, termOffset, header, termLength, termId);
            }
            else
            {
                int frameOffset = (int)termOffset;
                header.Write(termBuffer, frameOffset, frameLength, termId);
                termBuffer.PutBytes(frameOffset + DataHeaderFlyweight.HEADER_LENGTH, bufferOne, offsetOne, lengthOne);
                termBuffer.PutBytes(frameOffset + DataHeaderFlyweight.HEADER_LENGTH + lengthOne, bufferTwo, offsetTwo, lengthTwo);

                if (null != reservedValueSupplier)
                {
                    long reservedValue = reservedValueSupplier(termBuffer, frameOffset, frameLength);
                    termBuffer.PutLong(frameOffset + DataHeaderFlyweight.RESERVED_VALUE_OFFSET, reservedValue, ByteOrder.LittleEndian);
                }

                FrameDescriptor.FrameLengthOrdered(termBuffer, frameOffset, frameLength);
            }

            return((int)resultingOffset);
        }
Exemplo n.º 6
0
        private void InsertDataFrame(int activeTermId, int termOffset)
        {
            DataHeader.TermId(INITIAL_TERM_ID).StreamId(STREAM_ID).SessionId(SESSION_ID).TermOffset(termOffset).FrameLength(DATA.Length + DataHeaderFlyweight.HEADER_LENGTH).HeaderType(HeaderFlyweight.HDR_TYPE_DATA).Flags(DataHeaderFlyweight.BEGIN_AND_END_FLAGS).Version(HeaderFlyweight.CURRENT_VERSION);

            RcvBuffer.PutBytes(DataHeader.DataOffset(), DATA);

            var activeIndex = LogBufferDescriptor.IndexByTerm(INITIAL_TERM_ID, activeTermId);

            TermRebuilder.Insert(TermBuffers[activeIndex], termOffset, RcvBuffer, ALIGNED_FRAME_LENGTH);
        }
Exemplo n.º 7
0
        public void ShouldAppendFrameToEmptyLog()
        {
            int          headerLength       = _defaultHeader.Capacity;
            UnsafeBuffer buffer             = new UnsafeBuffer(new byte[128]);
            const int    msgLength          = 20;
            int          frameLength        = msgLength + headerLength;
            int          alignedFrameLength = BitUtil.Align(frameLength, FrameDescriptor.FRAME_ALIGNMENT);
            const int    tail = 0;

            _logMetaDataBuffer.PutLong(TermTailCounterOffset, LogBufferDescriptor.PackTail(TermID, tail));

            Assert.That(_termAppender.AppendUnfragmentedMessage(_headerWriter, buffer, 0, msgLength, RVS), Is.EqualTo((long)alignedFrameLength));

            Assert.AreEqual(LogBufferDescriptor.RawTailVolatile(_logMetaDataBuffer, PartionIndex), LogBufferDescriptor.PackTail(TermID, tail + alignedFrameLength));

            A.CallTo(() => _headerWriter.Write(_termBuffer, tail, frameLength, TermID)).MustHaveHappened()
            .Then(A.CallTo(() => _termBuffer.PutBytes(headerLength, buffer, 0, msgLength)).MustHaveHappened())
            .Then(A.CallTo(() => _termBuffer.PutLong(tail + DataHeaderFlyweight.RESERVED_VALUE_OFFSET, RV)).MustHaveHappened())
            .Then(A.CallTo(() => _termBuffer.PutIntOrdered(tail, frameLength)).MustHaveHappened());
        }
Exemplo n.º 8
0
        /// <summary>
        /// Store the default frame header to the log meta data buffer.
        /// </summary>
        /// <param name="logMetaDataBuffer"> into which the default headers should be stored. </param>
        /// <param name="defaultHeader">     to be stored. </param>
        /// <exception cref="ArgumentException"> if the default header is larger than <seealso cref="LOG_DEFAULT_FRAME_HEADER_MAX_LENGTH"/> </exception>
        public static void StoreDefaultFrameHeader(UnsafeBuffer logMetaDataBuffer, IDirectBuffer defaultHeader)
        {
            if (defaultHeader.Capacity != DataHeaderFlyweight.HEADER_LENGTH)
            {
                throw new ArgumentException(
                          $"Default header of {defaultHeader.Capacity:D} not equal to {DataHeaderFlyweight.HEADER_LENGTH:D}");
            }

            logMetaDataBuffer.PutInt(LOG_DEFAULT_FRAME_HEADER_LENGTH_OFFSET, DataHeaderFlyweight.HEADER_LENGTH);
            logMetaDataBuffer.PutBytes(LOG_DEFAULT_FRAME_HEADER_OFFSET, defaultHeader, 0, DataHeaderFlyweight.HEADER_LENGTH);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Append pre-formatted block of message fragments into the term buffer.
        /// <para>
        /// <em>WARNING: This is internal API used by {@code ExclusivePublication#offerBlock} method.</em>
        /// </para>
        /// </summary>
        /// <param name="termId">     for the current term. </param>
        /// <param name="termOffset"> in the term at which to append. </param>
        /// <param name="buffer">     which contains block of messages. </param>
        /// <param name="offset">     within the buffer at which the block begins. </param>
        /// <param name="length">     of the block in bytes (always aligned). </param>
        /// <returns> the resulting offset of the term after success otherwise <seealso cref="FAILED"/>. </returns>
        public int AppendBlock(int termId, int termOffset, IMutableDirectBuffer buffer, int offset, int length)
        {
            int resultingOffset    = termOffset + length;
            int lengthOfFirstFrame = buffer.GetInt(offset, ByteOrder.LittleEndian);

            buffer.PutInt(offset, 0, ByteOrder.LittleEndian);
            _termBuffer.PutBytes(termOffset, buffer, offset, length);
            FrameDescriptor.FrameLengthOrdered(_termBuffer, termOffset, lengthOfFirstFrame);
            PutRawTailOrdered(termId, resultingOffset);

            return(resultingOffset);
        }
Exemplo n.º 10
0
        public static void StoreDefaultFrameHeader(UnsafeBuffer metaDataBuffer, IDirectBuffer defaultHeader)
        {
            if (defaultHeader.Capacity != DataHeaderFlyweight.HEADER_LENGTH)
            {
                ThrowHelper.ThrowArgumentException(
                    $"Default header length not equal to HEADER_LENGTH: length={defaultHeader.Capacity:D}");
                return;
            }

            metaDataBuffer.PutInt(LOG_DEFAULT_FRAME_HEADER_LENGTH_OFFSET, DataHeaderFlyweight.HEADER_LENGTH);
            metaDataBuffer.PutBytes(LOG_DEFAULT_FRAME_HEADER_OFFSET, defaultHeader, 0,
                                    DataHeaderFlyweight.HEADER_LENGTH);
        }
Exemplo n.º 11
0
        public void ShouldAppendOneBufferWithoutResizing()
        {
            var srcBuffer = new UnsafeBuffer(new byte[BufferBuilder.INITIAL_CAPACITY]);
            var bytes     = Encoding.UTF8.GetBytes("Hello World");

            srcBuffer.PutBytes(0, bytes, 0, bytes.Length);

            _bufferBuilder.Append(srcBuffer, 0, bytes.Length);

            byte[] temp = new byte[bytes.Length];
            _bufferBuilder.Buffer().GetBytes(0, temp, 0, bytes.Length);

            Assert.That(_bufferBuilder.Limit(), Is.EqualTo(bytes.Length));
            Assert.That(_bufferBuilder.Capacity(), Is.EqualTo(BufferBuilder.INITIAL_CAPACITY));
            Assert.That(temp, Is.EqualTo(bytes));
        }
Exemplo n.º 12
0
        public void ShouldAppendOneBufferWithoutResizing()
        {
            var srcBuffer = new UnsafeBuffer(new byte[BufferBuilderUtil.MIN_ALLOCATED_CAPACITY]);
            var bytes     = Encoding.UTF8.GetBytes("Hello World");

            srcBuffer.PutBytes(0, bytes, 0, bytes.Length);

            _bufferBuilder.Append(srcBuffer, 0, bytes.Length);

            byte[] temp = new byte[bytes.Length];
            _bufferBuilder.Buffer().GetBytes(0, temp, 0, bytes.Length);

            Assert.AreEqual(bytes.Length, _bufferBuilder.Limit());
            Assert.AreEqual(BufferBuilderUtil.MIN_ALLOCATED_CAPACITY, _bufferBuilder.Capacity());
            Assert.AreEqual(bytes, temp);
        }
Exemplo n.º 13
0
        public void ShouldAppendTwoBuffersWithoutResizing()
        {
            UnsafeBuffer srcBuffer = new UnsafeBuffer(new byte[BufferBuilderUtil.MIN_ALLOCATED_CAPACITY]);

            byte[] bytes = Encoding.UTF8.GetBytes("1111111122222222");
            srcBuffer.PutBytes(0, bytes, 0, bytes.Length);

            _bufferBuilder.Append(srcBuffer, 0, bytes.Length / 2);
            _bufferBuilder.Append(srcBuffer, bytes.Length / 2, bytes.Length / 2);

            byte[] temp = new byte[bytes.Length];
            _bufferBuilder.Buffer().GetBytes(0, temp, 0, bytes.Length);

            Assert.That(_bufferBuilder.Limit(), Is.EqualTo(bytes.Length));
            Assert.That(_bufferBuilder.Capacity(), Is.EqualTo(BufferBuilderUtil.MIN_ALLOCATED_CAPACITY));
            Assert.That(temp, Is.EqualTo(bytes));
        }
Exemplo n.º 14
0
        public int AppendUnfragmentedMessage(
            int termId,
            int termOffset,
            HeaderWriter header,
            DirectBufferVector[] vectors,
            int length,
            ReservedValueSupplier reservedValueSupplier)
#endif
        {
            int          frameLength   = length + DataHeaderFlyweight.HEADER_LENGTH;
            int          alignedLength = BitUtil.Align(frameLength, FrameDescriptor.FRAME_ALIGNMENT);
            UnsafeBuffer termBuffer    = _termBuffer;
            int          termLength    = termBuffer.Capacity;

            int resultingOffset = termOffset + alignedLength;

            PutRawTailOrdered(termId, resultingOffset);

            if (resultingOffset > termLength)
            {
                resultingOffset = HandleEndOfLogCondition(termBuffer, termOffset, header, termLength, termId);
            }
            else
            {
                header.Write(termBuffer, termOffset, frameLength, termId);

                var offset = termOffset + DataHeaderFlyweight.HEADER_LENGTH;

                foreach (var vector in vectors)
                {
                    termBuffer.PutBytes(offset, vector.buffer, vector.offset, vector.length);
                    offset += vector.length;
                }

                if (null != reservedValueSupplier)
                {
                    long reservedValue = reservedValueSupplier(termBuffer, termOffset, frameLength);
                    termBuffer.PutLong(termOffset + DataHeaderFlyweight.RESERVED_VALUE_OFFSET, reservedValue, ByteOrder.LittleEndian);
                }

                FrameDescriptor.FrameLengthOrdered(termBuffer, termOffset, frameLength);
            }

            return(resultingOffset);
        }
Exemplo n.º 15
0
        public int AppendUnfragmentedMessage(HeaderWriter header, DirectBufferVector[] vectors, int length, ReservedValueSupplier reservedValueSupplier, int activeTermId)
#endif
        {
            int          frameLength   = length + DataHeaderFlyweight.HEADER_LENGTH;
            int          alignedLength = BitUtil.Align(frameLength, FrameDescriptor.FRAME_ALIGNMENT);
            long         rawTail       = GetAndAddRawTail(alignedLength);
            int          termId        = LogBufferDescriptor.TermId(rawTail);
            long         termOffset    = rawTail & 0xFFFFFFFFL;
            UnsafeBuffer termBuffer    = _termBuffer;
            int          termLength    = termBuffer.Capacity;

            CheckTerm(activeTermId, termId);

            long resultingOffset = termOffset + alignedLength;

            if (resultingOffset > termLength)
            {
                resultingOffset = HandleEndOfLogCondition(termBuffer, termOffset, header, termLength, termId);
            }
            else
            {
                int frameOffset = (int)termOffset;
                header.Write(termBuffer, frameOffset, frameLength, LogBufferDescriptor.TermId(rawTail));

                int offset = frameOffset + DataHeaderFlyweight.HEADER_LENGTH;

                foreach (var vector in vectors)
                {
                    termBuffer.PutBytes(offset, vector.buffer, vector.offset, vector.length);
                    offset += vector.length;
                }

                if (null != reservedValueSupplier)
                {
                    long reservedValue = reservedValueSupplier(termBuffer, frameOffset, frameLength);
                    termBuffer.PutLong(frameOffset + DataHeaderFlyweight.RESERVED_VALUE_OFFSET, reservedValue, ByteOrder.LittleEndian);
                }

                FrameDescriptor.FrameLengthOrdered(termBuffer, frameOffset, frameLength);
            }

            return((int)resultingOffset);
        }
Exemplo n.º 16
0
        public static void Main()
        {
            // Allocate enough buffer size to hold maximum message length
            // The UnsafeBuffer class is part of the Agrona library and is used for efficient buffer management
            var buffer = new UnsafeBuffer(BufferUtil.AllocateDirectAligned(512, BitUtil.CACHE_LINE_LENGTH));

            // The channel (an endpoint identifier) to send the message to
            const string channel = "aeron:udp?endpoint=localhost:40123";

            // A unique identifier for a stream within a channel. Stream ID 0 is reserved
            // for internal use and should not be used by applications.
            const int streamId = 10;

            Console.WriteLine("Publishing to " + channel + " on stream Id " + streamId);

            // Create a context, needed for client connection to media driver
            // A separate media driver process needs to be running prior to starting this application
            var ctx = new Aeron.Context();

            // Create an Aeron instance with client-provided context configuration and connect to the
            // media driver, and create a Publication.  The Aeron and Publication classes implement
            // AutoCloseable, and will automatically clean up resources when this try block is finished.
            using (var aeron = Aeron.Connect(ctx))
                using (var publication = aeron.AddPublication(channel, streamId))
                {
                    Thread.Sleep(100);

                    const string message      = "Hello World! ";
                    var          messageBytes = Encoding.UTF8.GetBytes(message);
                    buffer.PutBytes(0, messageBytes);

                    // Try to publish the buffer. 'offer' is a non-blocking call.
                    // If it returns less than 0, the message was not sent, and the offer should be retried.
                    var result = publication.Offer(buffer, 0, messageBytes.Length);

                    if (result < 0L)
                    {
                        switch (result)
                        {
                        case Publication.BACK_PRESSURED:
                            Console.WriteLine(" Offer failed due to back pressure");
                            break;

                        case Publication.NOT_CONNECTED:
                            Console.WriteLine(" Offer failed because publisher is not connected to subscriber");
                            break;

                        case Publication.ADMIN_ACTION:
                            Console.WriteLine("Offer failed because of an administration action in the system");
                            break;

                        case Publication.CLOSED:
                            Console.WriteLine("Offer failed publication is closed");
                            break;

                        default:
                            Console.WriteLine(" Offer failed due to unknown reason");
                            break;
                        }
                    }
                    else
                    {
                        Console.WriteLine(" yay !!");
                    }

                    Console.WriteLine("Done sending.");
                    Console.WriteLine("Press any key...");
                    Console.ReadLine();
                }
        }
Exemplo n.º 17
0
 /// <summary>
 /// Put bytes into the claimed buffer space for a message. To write multiple parts then use <seealso cref="Buffer()"/>
 /// and <seealso cref="Offset()"/>.
 /// </summary>
 /// <param name="srcBuffer"> to copy into the claimed space. </param>
 /// <param name="srcIndex">  in the source buffer from which to copy. </param>
 /// <param name="length">    of the source buffer to copy. </param>
 /// <returns> this for a fluent API. </returns>
 public BufferClaim PutBytes(IDirectBuffer srcBuffer, int srcIndex, int length)
 {
     _buffer.PutBytes(DataHeaderFlyweight.HEADER_LENGTH, srcBuffer, srcIndex, length);
     return(this);
 }
Exemplo n.º 18
0
 public static void ApplyDefaultHeader(UnsafeBuffer metaDataBuffer, UnsafeBuffer termBuffer, int termOffset)
 {
     termBuffer.PutBytes(termOffset, metaDataBuffer, LOG_DEFAULT_FRAME_HEADER_OFFSET,
                         DataHeaderFlyweight.HEADER_LENGTH);
 }
Exemplo n.º 19
0
        static async Task Main(string[] args)
        {
            var listenPort = ushort.Parse(args[0]);

            var seeds  = args.Skip(1).Select(Utils.IPEndPointFromString).ToArray();
            var logger = Utils.CreateLogger <Program>();

            var loadbalancer = CreateLoadBalancer();
            var gossiper     = await StartGossiper(listenPort, seeds, new IMemberListener[] { loadbalancer }, logger);

            // Allocate enough buffer size to hold maximum message length
            // The UnsafeBuffer class is part of the Agrona library and is used for efficient buffer management
            var buffer = new UnsafeBuffer(BufferUtil.AllocateDirectAligned(512, BitUtil.CACHE_LINE_LENGTH));

            var stopwatch = new Stopwatch();

            while (true)
            {
                try
                {
                    Console.Write("Please enter your name: ");
                    string message = Console.ReadLine();

                    stopwatch.Restart();
                    var messageBytes = Encoding.UTF8.GetBytes(message);
                    buffer.PutBytes(0, messageBytes);

                    var client = loadbalancer.GetServiceClient <AeronServiceClient>(4);

                    // Try to publish the buffer. 'offer' is a non-blocking call.
                    // If it returns less than 0, the message was not sent, and the offer should be retried.
                    var result = client.Publication.Offer(buffer, 0, messageBytes.Length);

                    if (result < 0L)
                    {
                        switch (result)
                        {
                        case Publication.BACK_PRESSURED:
                            Console.WriteLine(" Offer failed due to back pressure");
                            break;

                        case Publication.NOT_CONNECTED:
                            Console.WriteLine(" Offer failed because publisher is not connected to subscriber");
                            break;

                        case Publication.ADMIN_ACTION:
                            Console.WriteLine("Offer failed because of an administration action in the system");
                            break;

                        case Publication.CLOSED:
                            Console.WriteLine("Offer failed publication is closed");
                            break;

                        default:
                            Console.WriteLine(" Offer failed due to unknown reason");
                            break;
                        }
                    }
                    else
                    {
                        stopwatch.Stop();
                        Console.WriteLine($"Message Sent TimeTaken: {stopwatch.Elapsed.TotalMilliseconds}ms");
                    }
                }

                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
Exemplo n.º 20
0
        public int AppendFragmentedMessage(
            int termId,
            int termOffset,
            HeaderWriter header,
            DirectBufferVector[] vectors,
            int length,
            int maxPayloadLength,
            ReservedValueSupplier reservedValueSupplier)
        {
            int numMaxPayloads   = length / maxPayloadLength;
            int remainingPayload = length % maxPayloadLength;
            int lastFrameLength  = remainingPayload > 0
                ? BitUtil.Align(remainingPayload + DataHeaderFlyweight.HEADER_LENGTH, FrameDescriptor.FRAME_ALIGNMENT)
                : 0;
            int requiredLength = (numMaxPayloads * (maxPayloadLength + DataHeaderFlyweight.HEADER_LENGTH)) +
                                 lastFrameLength;
            UnsafeBuffer termBuffer = _termBuffer;
            int          termLength = termBuffer.Capacity;

            int resultingOffset = termOffset + requiredLength;

            PutRawTailOrdered(termId, resultingOffset);

            if (resultingOffset > termLength)
            {
                resultingOffset = HandleEndOfLogCondition(termBuffer, termOffset, header, termLength, termId);
            }
            else
            {
                int  frameOffset  = termOffset;
                byte flags        = FrameDescriptor.BEGIN_FRAG_FLAG;
                int  remaining    = length;
                int  vectorIndex  = 0;
                int  vectorOffset = 0;

                do
                {
                    int bytesToWrite  = Math.Min(remaining, maxPayloadLength);
                    int frameLength   = bytesToWrite + DataHeaderFlyweight.HEADER_LENGTH;
                    int alignedLength = BitUtil.Align(frameLength, FrameDescriptor.FRAME_ALIGNMENT);

                    header.Write(termBuffer, frameOffset, frameLength, termId);

                    int bytesWritten  = 0;
                    int payloadOffset = frameOffset + DataHeaderFlyweight.HEADER_LENGTH;

                    do
                    {
                        var vector          = vectors[vectorIndex];
                        int vectorRemaining = vector.length - vectorOffset;
                        int numBytes        = Math.Min(bytesToWrite - bytesWritten, vectorRemaining);

                        termBuffer.PutBytes(payloadOffset, vector.buffer, vector.offset + vectorOffset, numBytes);

                        bytesWritten  += numBytes;
                        payloadOffset += numBytes;
                        vectorOffset  += numBytes;

                        if (vectorRemaining <= numBytes)
                        {
                            vectorIndex++;
                            vectorOffset = 0;
                        }
                    } while (bytesWritten < bytesToWrite);

                    if (remaining <= maxPayloadLength)
                    {
                        flags |= FrameDescriptor.END_FRAG_FLAG;
                    }

                    FrameDescriptor.FrameFlags(termBuffer, frameOffset, flags);

                    if (null != reservedValueSupplier)
                    {
                        long reservedValue = reservedValueSupplier(termBuffer, frameOffset, frameLength);
                        termBuffer.PutLong(frameOffset + DataHeaderFlyweight.RESERVED_VALUE_OFFSET, reservedValue, ByteOrder.LittleEndian);
                    }

                    FrameDescriptor.FrameLengthOrdered(termBuffer, frameOffset, frameLength);

                    flags        = 0;
                    frameOffset += alignedLength;
                    remaining   -= bytesToWrite;
                } while (remaining > 0);
            }

            return(resultingOffset);
        }
Exemplo n.º 21
0
 public long Send(IDirectBuffer source, int startIndex, int length)
 {
     _buffer.PutBytes(0, source, startIndex, length);
     return(Offer(length));
 }