Esempio n. 1
0
        public void GetRequest_With_Timestamp_Generator_Empty_Value_With_Statement_Timestamp()
        {
            var statement         = new SimpleStatement("STATEMENT WITH TIMESTAMP");
            var expectedTimestamp = new DateTimeOffset(2010, 04, 29, 1, 2, 3, 4, TimeSpan.Zero).AddTicks(20);

            statement.SetTimestamp(expectedTimestamp);
            var policies = new Cassandra.Policies(
                Cassandra.Policies.DefaultLoadBalancingPolicy, Cassandra.Policies.DefaultReconnectionPolicy,
                Cassandra.Policies.DefaultRetryPolicy, Cassandra.Policies.DefaultSpeculativeExecutionPolicy,
                new NoTimestampGenerator());
            var config = RequestHandlerTests.GetConfig(new QueryOptions(), policies, PoolingOptions.Create());

            var request    = RequestHandler.GetRequest(statement, Serializer, config.DefaultRequestOptions);
            var bodyBuffer = GetBodyBuffer(request);

            // The query request is composed by:
            // <query><consistency><flags><result_page_size><paging_state><serial_consistency><timestamp>
            var queryBuffer = BeConverter.GetBytes(statement.QueryString.Length)
                              .Concat(Encoding.UTF8.GetBytes(statement.QueryString))
                              .ToArray();

            CollectionAssert.AreEqual(queryBuffer, bodyBuffer.Take(queryBuffer.Length));
            // Skip the query and consistency (2)
            var offset = queryBuffer.Length + 2;
            var flags  = GetQueryFlags(bodyBuffer, ref offset);

            Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
            Assert.True(flags.HasFlag(QueryFlags.PageSize));
            // Skip result_page_size (4) + serial_consistency (2)
            offset += 6;
            var timestamp = BeConverter.ToInt64(bodyBuffer, offset);

            Assert.AreEqual(TypeSerializer.SinceUnixEpoch(expectedTimestamp).Ticks / 10, timestamp);
        }
Esempio n. 2
0
        public override byte[] Serialize(ushort protocolVersion, BigDecimal value)
        {
            var scaleBuffer = BeConverter.GetBytes(value.Scale);
            var valueBuffer = _bigIntegerSerializer.Serialize(protocolVersion, value.UnscaledValue);

            return(Utils.JoinBuffers(new[] { scaleBuffer, valueBuffer }, scaleBuffer.Length + valueBuffer.Length));
        }
        public void GetRequest_With_Timestamp_Generator_Empty_Value()
        {
            var statement = new SimpleStatement("QUERY");
            var policies  = new Policies(
                Policies.DefaultLoadBalancingPolicy, Policies.DefaultReconnectionPolicy, Policies.DefaultRetryPolicy,
                Policies.DefaultSpeculativeExecutionPolicy, new NoTimestampGenerator());
            var config = new Configuration(
                policies, new ProtocolOptions(), PoolingOptions.Create(), new SocketOptions(), new ClientOptions(),
                NoneAuthProvider.Instance, null, new QueryOptions(), new DefaultAddressTranslator());

            var request    = RequestHandler.GetRequest(statement, Serializer.Default, config);
            var bodyBuffer = GetBodyBuffer(request);

            // The query request is composed by:
            // <query><consistency><flags><result_page_size><paging_state><serial_consistency><timestamp>
            var queryBuffer = BeConverter.GetBytes(statement.QueryString.Length)
                              .Concat(Encoding.UTF8.GetBytes(statement.QueryString))
                              .ToArray();

            CollectionAssert.AreEqual(queryBuffer, bodyBuffer.Take(queryBuffer.Length));
            // Skip the query and consistency (2)
            var offset = queryBuffer.Length + 2;
            var flags  = GetQueryFlags(bodyBuffer, ref offset);

            Assert.False(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
            Assert.True(flags.HasFlag(QueryFlags.PageSize));
            Assert.False(flags.HasFlag(QueryFlags.Values));
            Assert.False(flags.HasFlag(QueryFlags.WithPagingState));
            Assert.False(flags.HasFlag(QueryFlags.SkipMetadata));
            Assert.True(flags.HasFlag(QueryFlags.WithSerialConsistency));
        }
        private static byte[] GetHeaderBuffer(int length, HeaderFlags flags = 0)
        {
            var headerBuffer = new byte[] { 0x80 | (int)Version, (byte)flags, 0, 0, ErrorResponse.OpCode }
            .Concat(BeConverter.GetBytes(length));

            return(headerBuffer.ToArray());
        }
        public void GetRequest_With_Timestamp_Generator()
        {
            // Timestamp generator should be enabled by default
            var statement = new SimpleStatement("QUERY");
            var config    = new Configuration();

            var request    = RequestHandler.GetRequest(statement, Serializer, config);
            var bodyBuffer = GetBodyBuffer(request);

            // The query request is composed by:
            // <query><consistency><flags><result_page_size><paging_state><serial_consistency><timestamp>
            var queryBuffer = BeConverter.GetBytes(statement.QueryString.Length)
                              .Concat(Encoding.UTF8.GetBytes(statement.QueryString))
                              .ToArray();

            CollectionAssert.AreEqual(queryBuffer, bodyBuffer.Take(queryBuffer.Length));
            // Skip the query and consistency (2)
            var offset = queryBuffer.Length + 2;
            var flags  = GetQueryFlags(bodyBuffer, ref offset);

            Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
            Assert.True(flags.HasFlag(QueryFlags.PageSize));
            Assert.False(flags.HasFlag(QueryFlags.Values));
            Assert.False(flags.HasFlag(QueryFlags.WithPagingState));
            Assert.False(flags.HasFlag(QueryFlags.SkipMetadata));
            Assert.True(flags.HasFlag(QueryFlags.WithSerialConsistency));
            // Skip result_page_size (4) + serial_consistency (2)
            offset += 6;
            var timestamp         = BeConverter.ToInt64(bodyBuffer, offset);
            var expectedTimestamp = TypeSerializer.SinceUnixEpoch(DateTimeOffset.Now.Subtract(TimeSpan.FromMilliseconds(100))).Ticks / 10;

            Assert.Greater(timestamp, expectedTimestamp);
        }
 private static byte[] GetErrorBody(int code, string message, IEnumerable <byte> additional = null)
 {
     // error body = [int][string][additional]
     return(BeConverter.GetBytes(code)
            .Concat(GetProtocolString(message))
            .Concat(additional ?? new byte[0])
            .ToArray());
 }
 /// <summary>
 /// Uses 2 or 4 bytes to represent the length in bytes
 /// </summary>
 internal static byte[] EncodeCollectionLength(ushort protocolVersion, int value)
 {
     if (protocolVersion < 3)
     {
         return(BeConverter.GetBytes((short)value));
     }
     return(BeConverter.GetBytes(value));
 }
        public void Should_Parse_ErrorResponse_With_Warnings()
        {
            // Protocol warnings are [string list]: A [short] n, followed by n [string]
            var warningBuffers = BeConverter.GetBytes((ushort)1).Concat(GetProtocolString("Test warning"));
            var body           = warningBuffers.Concat(GetErrorBody(0x2000, "Test syntax error")).ToArray();
            var header         = FrameHeader.ParseResponseHeader(Version, GetHeaderBuffer(body.Length, HeaderFlags.Warning), 0);
            var response       = FrameParser.Parse(new Frame(header, new MemoryStream(body), Serializer.GetCurrentSerializer()));
            var ex             = IsErrorResponse <SyntaxError>(response);

            Assert.AreEqual("Test syntax error", ex.Message);
        }
        public void GetRequest_With_Timestamp_Generator_Empty_Value_With_Statement_Timestamp()
        {
            var statement         = new SimpleStatement("STATEMENT WITH TIMESTAMP");
            var expectedTimestamp = new DateTimeOffset(2010, 04, 29, 1, 2, 3, 4, TimeSpan.Zero).AddTicks(20);

            statement.SetTimestamp(expectedTimestamp);
            var policies = new Policies(
                Policies.DefaultLoadBalancingPolicy, Policies.DefaultReconnectionPolicy, Policies.DefaultRetryPolicy,
                Policies.DefaultSpeculativeExecutionPolicy, new NoTimestampGenerator());
            var config = new Configuration(
                policies,
                new ProtocolOptions(),
                PoolingOptions.Create(),
                new SocketOptions(),
                new ClientOptions(),
                NoneAuthProvider.Instance,
                null,
                new QueryOptions(),
                new DefaultAddressTranslator(),
                Mock.Of <IStartupOptionsFactory>(),
                new SessionFactoryBuilder());

            var request    = RequestHandler.GetRequest(statement, Serializer, config);
            var bodyBuffer = GetBodyBuffer(request);

            // The query request is composed by:
            // <query><consistency><flags><result_page_size><paging_state><serial_consistency><timestamp>
            var queryBuffer = BeConverter.GetBytes(statement.QueryString.Length)
                              .Concat(Encoding.UTF8.GetBytes(statement.QueryString))
                              .ToArray();

            CollectionAssert.AreEqual(queryBuffer, bodyBuffer.Take(queryBuffer.Length));
            // Skip the query and consistency (2)
            var offset = queryBuffer.Length + 2;

            // The remaining length should be = flags (1) + result_page_size (4) + serial_consistency (2) + timestamp (8)
            Assert.AreEqual(15, bodyBuffer.Length - offset);
            var flags = GetQueryFlags(bodyBuffer, ref offset);

            Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
            Assert.True(flags.HasFlag(QueryFlags.PageSize));
            // Skip result_page_size (4) + serial_consistency (2)
            offset += 6;
            var timestamp = BeConverter.ToInt64(bodyBuffer, offset);

            Assert.AreEqual(TypeSerializer.SinceUnixEpoch(expectedTimestamp).Ticks / 10, timestamp);
        }
Esempio n. 10
0
        public void GetRequest_With_Timestamp_Generator_Empty_Value_With_Statement_Timestamp()
        {
            var statement         = new SimpleStatement("STATEMENT WITH TIMESTAMP");
            var expectedTimestamp = new DateTimeOffset(2010, 04, 29, 1, 2, 3, 4, TimeSpan.Zero).AddTicks(20);

            statement.SetTimestamp(expectedTimestamp);
            var policies = new Dse.Policies(
                Dse.Policies.DefaultLoadBalancingPolicy, Dse.Policies.DefaultReconnectionPolicy,
                Dse.Policies.DefaultRetryPolicy, Dse.Policies.DefaultSpeculativeExecutionPolicy,
                new NoTimestampGenerator());
            var config = new Configuration(
                policies, new ProtocolOptions(), PoolingOptions.GetDefault(ProtocolVersion.MaxSupported), new SocketOptions(), new ClientOptions(),
                NoneAuthProvider.Instance, null, new QueryOptions(), new DefaultAddressTranslator());
            var request = RequestHandler <RowSet> .GetRequest(statement, Serializer, config);

            var stream = new MemoryStream();

            request.WriteFrame(1, stream, Serializer);
            var headerSize = FrameHeader.GetSize(ProtocolVersion.MaxSupported);
            var bodyBuffer = new byte[stream.Length - headerSize];

            stream.Position = headerSize;
            stream.Read(bodyBuffer, 0, bodyBuffer.Length);
            // The query request is composed by:
            // <query><consistency><flags><result_page_size><timestamp>
            var queryBuffer = BeConverter.GetBytes(statement.QueryString.Length)
                              .Concat(Encoding.UTF8.GetBytes(statement.QueryString))
                              .ToArray();

            CollectionAssert.AreEqual(queryBuffer, bodyBuffer.Take(queryBuffer.Length));
            // Skip the query and consistency (2)
            var offset = queryBuffer.Length + 2;

            // The remaining length should be 13 = flags (1) + result_page_size (4) + timestamp (8)
            Assert.AreEqual(13, bodyBuffer.Length - offset);
            var flags = (QueryFlags)bodyBuffer[offset];

            Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
            Assert.True(flags.HasFlag(QueryFlags.PageSize));
            // Skip flags (1) + result_page_size (4)
            offset += 5;
            var timestamp = BeConverter.ToInt64(bodyBuffer, offset);

            Assert.AreEqual(TypeSerializer.SinceUnixEpoch(expectedTimestamp).Ticks / 10, timestamp);
        }
Esempio n. 11
0
        public void GetRequest_With_Timestamp_Generator()
        {
            // Timestamp generator should be enabled by default
            var statement = new SimpleStatement("QUERY");
            var config    = new Configuration();
            var request   = RequestHandler <RowSet> .GetRequest(statement, Serializer, config);

            var stream = new MemoryStream();

            request.WriteFrame(1, stream, Serializer);
            var headerSize = FrameHeader.GetSize(ProtocolVersion.MaxSupported);
            var bodyBuffer = new byte[stream.Length - headerSize];

            stream.Position = headerSize;
            stream.Read(bodyBuffer, 0, bodyBuffer.Length);
            // The query request is composed by:
            // <query><consistency><flags><result_page_size><timestamp>
            var queryBuffer = BeConverter.GetBytes(statement.QueryString.Length)
                              .Concat(Encoding.UTF8.GetBytes(statement.QueryString))
                              .ToArray();

            CollectionAssert.AreEqual(queryBuffer, bodyBuffer.Take(queryBuffer.Length));
            // Skip the query and consistency (2)
            var offset = queryBuffer.Length + 2;

            // The remaining length should be 13 = flags (1) + result_page_size (4) + timestamp (8)
            Assert.AreEqual(13, bodyBuffer.Length - offset);
            var flags = (QueryFlags)bodyBuffer[offset];

            Assert.True(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
            Assert.True(flags.HasFlag(QueryFlags.PageSize));
            Assert.False(flags.HasFlag(QueryFlags.Values));
            Assert.False(flags.HasFlag(QueryFlags.WithPagingState));
            Assert.False(flags.HasFlag(QueryFlags.SkipMetadata));
            Assert.False(flags.HasFlag(QueryFlags.WithSerialConsistency));
            // Skip flags (1) + result_page_size (4)
            offset += 5;
            var timestamp         = BeConverter.ToInt64(bodyBuffer, offset);
            var expectedTimestamp = TypeSerializer.SinceUnixEpoch(DateTimeOffset.Now.Subtract(TimeSpan.FromMilliseconds(100))).Ticks / 10;

            Assert.Greater(timestamp, expectedTimestamp);
        }
Esempio n. 12
0
        public void GetRequest_With_Timestamp_Generator_Empty_Value()
        {
            var statement = new SimpleStatement("QUERY");
            var policies  = new Dse.Policies(
                Dse.Policies.DefaultLoadBalancingPolicy, Dse.Policies.DefaultReconnectionPolicy,
                Dse.Policies.DefaultRetryPolicy, Dse.Policies.DefaultSpeculativeExecutionPolicy,
                new NoTimestampGenerator());
            var config = new Configuration(
                policies, new ProtocolOptions(), PoolingOptions.GetDefault(ProtocolVersion.MaxSupported), new SocketOptions(), new ClientOptions(),
                NoneAuthProvider.Instance, null, new QueryOptions(), new DefaultAddressTranslator());
            var request = RequestHandler <RowSet> .GetRequest(statement, Serializer.Default, config);

            var stream = new MemoryStream();

            request.WriteFrame(1, stream, Serializer);
            var headerSize = FrameHeader.GetSize(ProtocolVersion.MaxSupported);
            var bodyBuffer = new byte[stream.Length - headerSize];

            stream.Position = headerSize;
            stream.Read(bodyBuffer, 0, bodyBuffer.Length);
            // The query request is composed by:
            // <query><consistency><flags><result_page_size>
            var queryBuffer = BeConverter.GetBytes(statement.QueryString.Length)
                              .Concat(Encoding.UTF8.GetBytes(statement.QueryString))
                              .ToArray();

            CollectionAssert.AreEqual(queryBuffer, bodyBuffer.Take(queryBuffer.Length));
            // Skip the query and consistency (2)
            var offset = queryBuffer.Length + 2;

            // The remaining length should be 13 = flags (1) + result_page_size (4)
            Assert.AreEqual(5, bodyBuffer.Length - offset);
            var flags = (QueryFlags)bodyBuffer[offset];

            Assert.False(flags.HasFlag(QueryFlags.WithDefaultTimestamp));
            Assert.True(flags.HasFlag(QueryFlags.PageSize));
            Assert.False(flags.HasFlag(QueryFlags.Values));
            Assert.False(flags.HasFlag(QueryFlags.WithPagingState));
            Assert.False(flags.HasFlag(QueryFlags.SkipMetadata));
            Assert.False(flags.HasFlag(QueryFlags.WithSerialConsistency));
        }
        internal static byte[] EncodeBufferList(ICollection <byte[]> bufferList, int bufferLength)
        {
            //Add the necessary bytes length per each [bytes]
            bufferLength += bufferList.Count * 4;
            var result = new byte[bufferLength];
            var index  = 0;

            foreach (var buf in bufferList)
            {
                var bufferItemLength = BeConverter.GetBytes(buf != null ? buf.Length : -1);
                Buffer.BlockCopy(bufferItemLength, 0, result, index, bufferItemLength.Length);
                index += bufferItemLength.Length;
                if (buf == null)
                {
                    continue;
                }
                Buffer.BlockCopy(buf, 0, result, index, buf.Length);
                index += buf.Length;
            }
            return(result);
        }
Esempio n. 14
0
        public override byte[] Serialize(ushort protocolVersion, decimal value)
        {
            int[] bits  = decimal.GetBits(value);
            int   scale = (bits[3] >> 16) & 31;

            byte[] scaleBytes  = BeConverter.GetBytes(scale);
            var    bigintBytes = new byte[13]; // 13th byte is for making sure that the number is positive

            Buffer.BlockCopy(bits, 0, bigintBytes, 0, 12);
            var bigInteger = new BigInteger(bigintBytes);

            if (value < 0)
            {
                bigInteger = -bigInteger;
            }

            bigintBytes = bigInteger.ToByteArray();
            Array.Reverse(bigintBytes);
            var resultBytes = new byte[scaleBytes.Length + bigintBytes.Length];

            Array.Copy(scaleBytes, resultBytes, scaleBytes.Length);
            Array.Copy(bigintBytes, 0, resultBytes, scaleBytes.Length, bigintBytes.Length);
            return(resultBytes);
        }
Esempio n. 15
0
        /// <summary>
        /// Gets a buffer containing 8 bytes for header and 4 bytes for the body.
        /// For result + void response message  (protocol v2)
        /// </summary>
        private static byte[] GetResultBuffer(short streamId, ProtocolVersion version = ProtocolVersion.V2)
        {
            var header = (byte)((int)version | 0x80);

            if (version.Uses2BytesStreamIds())
            {
                var bytes = BeConverter.GetBytes(streamId);
                return(new byte[]
                {
                    //header
                    header, 0, bytes[0], bytes[1], ResultResponse.OpCode, 0, 0, 0, 4,
                    //body
                    0, 0, 0, 1
                });
            }

            return(new byte[]
            {
                //header
                header, 0, (byte)streamId, ResultResponse.OpCode, 0, 0, 0, 4,
                //body
                0, 0, 0, 1
            });
        }
        private static byte[] GetProtocolString(string value)
        {
            var textBuffer = Encoding.UTF8.GetBytes(value);

            return(BeConverter.GetBytes((ushort)textBuffer.Length).Concat(textBuffer).ToArray());
        }
Esempio n. 17
0
 public override byte[] Serialize(ushort protocolVersion, float value)
 {
     return(BeConverter.GetBytes(value));
 }
Esempio n. 18
0
 public override byte[] Serialize(ushort protocolVersion, LocalTime value)
 {
     return(BeConverter.GetBytes(value.TotalNanoseconds));
 }
        internal static byte[] Serialize(DateTimeOffset value)
        {
            var ticks = (value - UnixStart).Ticks;

            return(BeConverter.GetBytes(ticks / TimeSpan.TicksPerMillisecond));
        }
 private static byte[] GetErrorBody(int code, string message)
 {
     // error body = [int] [string]
     return(BeConverter.GetBytes(code).Concat(GetProtocolString(message)).ToArray());
 }
Esempio n. 21
0
 internal static byte[] Serialize(DateTimeOffset value)
 {
     return(BeConverter.GetBytes(Convert.ToInt64(Math.Floor((value - UnixStart).TotalMilliseconds))));
 }