Ejemplo n.º 1
0
        protected override IEnumerable <bool> ReadFrame(IFrameReader frameReader)
        {
            Stream       stream       = frameReader.ReadOnlyStream;
            ResultOpcode resultOpcode = (ResultOpcode)stream.ReadInt();

            yield return(resultOpcode == ResultOpcode.Prepared);
        }
Ejemplo n.º 2
0
        protected static IColumnSpec[] ReadResultMetadata(IFrameReader frameReader)
        {
            Stream        stream   = frameReader.ReadOnlyStream;
            MetadataFlags flags    = (MetadataFlags)stream.ReadInt();
            int           colCount = stream.ReadInt();

            bool globalTablesSpec = 0 != (flags & MetadataFlags.GlobalTablesSpec);
            bool hasMorePages     = 0 != (flags & MetadataFlags.HasMorePages);
            bool noMetadata       = 0 != (flags & MetadataFlags.NoMetadata);

            string keyspace = null;
            string table    = null;

            if (globalTablesSpec && !noMetadata)
            {
                keyspace = stream.ReadString();
                table    = stream.ReadString();
            }

            if (hasMorePages)
            {
                var pagingState = stream.ReadBytesArray();
            }

            if (noMetadata)
            {
                return(null);
            }

            var columnSpecs = ReadColumnSpecs(colCount, keyspace, table, globalTablesSpec, stream);

            return(columnSpecs);
        }
Ejemplo n.º 3
0
        ReadNameValuePairsAsync(
            this IFrameReader frameReader,
            CancellationToken cancellationToken)
        {
            var length = await frameReader.ReadInt32Async(cancellationToken)
                         .ConfigureAwait(false);

            var nameValuePairs = new (string Name, string[] Values)[length];
Ejemplo n.º 4
0
 public FrameFilter(IFrameReader aReader, IFrameErrorHandler aError)
 {
     iReader = aReader;
     if (aError == null)
     {
         aError = new FrameErrorHandlerDummy();
     }
     iError = aError;
 }
Ejemplo n.º 5
0
        protected static IColumnSpec[] ReadColumnSpec(IFrameReader frameReader)
        {
            Stream        stream           = frameReader.ReadOnlyStream;
            MetadataFlags flags            = (MetadataFlags)stream.ReadInt();
            bool          globalTablesSpec = 0 != (flags & MetadataFlags.GlobalTablesSpec);

            int colCount = stream.ReadInt();

            string keyspace = null;
            string table    = null;

            if (globalTablesSpec)
            {
                keyspace = stream.ReadString();
                table    = stream.ReadString();
            }

            IColumnSpec[] columnSpecs = new IColumnSpec[colCount];
            for (int colIdx = 0; colIdx < colCount; ++colIdx)
            {
                string colKeyspace = keyspace;
                string colTable    = table;
                if (!globalTablesSpec)
                {
                    colKeyspace = stream.ReadString();
                    colTable    = stream.ReadString();
                }
                string     colName      = stream.ReadString();
                ColumnType colType      = (ColumnType)stream.ReadUShort();
                string     colCustom    = null;
                ColumnType colKeyType   = ColumnType.Custom;
                ColumnType colValueType = ColumnType.Custom;
                switch (colType)
                {
                case ColumnType.Custom:
                    colCustom = stream.ReadString();
                    break;

                case ColumnType.List:
                case ColumnType.Set:
                    colValueType = (ColumnType)stream.ReadUShort();
                    break;

                case ColumnType.Map:
                    colKeyType   = (ColumnType)stream.ReadUShort();
                    colValueType = (ColumnType)stream.ReadUShort();
                    break;
                }

                columnSpecs[colIdx] = new ColumnSpec(colIdx, colKeyspace, colTable, colName, colType, colCustom, colKeyType, colValueType);
            }

            return(columnSpecs);
        }
Ejemplo n.º 6
0
        private static IEnumerable <T> ReadRows(IFrameReader frameReader, IColumnSpec[] columnSpecs, IDataMapper mapperFactory)
        {
            Stream stream   = frameReader.ReadOnlyStream;
            int    rowCount = stream.ReadInt();

            for (int rowIdx = 0; rowIdx < rowCount; ++rowIdx)
            {
                var rowData = columnSpecs.Select(spec => new ColumnData(spec, stream.ReadByteArray()));
                yield return((T)mapperFactory.MapToObject(rowData));
            }
        }
Ejemplo n.º 7
0
        protected override IEnumerable <Dictionary <string, string[]> > ReadFrame(IFrameReader frameReader)
        {
            if (frameReader.MessageOpcode != MessageOpcodes.Supported)
            {
                throw new UnknownResponseException(frameReader.MessageOpcode);
            }

            Stream stream = frameReader.ReadOnlyStream;
            Dictionary <string, string[]> res = stream.ReadStringMultimap();

            yield return(res);
        }
Ejemplo n.º 8
0
        internal new static async ValueTask <ReadResult <Control> > TryReadAsync(
            IFrameReader frameReader,
            CancellationToken cancellation = default)
        {
            var version =
                (ushort)(await frameReader.ReadUShortAsync(cancellation)
                         .ConfigureAwait(false) & 0x7FFF);

            if (version != Version)
            {
                // todo: What stream id should be specified here?
                return(ReadResult <Control> .Error(RstStream.UnsupportedVersion(UInt31.From(0))));
            }

            var type = await frameReader.ReadUShortAsync(cancellation)
                       .ConfigureAwait(false);

            var flags = await frameReader.ReadByteAsync(cancellation)
                        .ConfigureAwait(false);

            var length = await frameReader.ReadUInt24Async(cancellation)
                         .ConfigureAwait(false);

            return(type switch
            {
                SynStream.Type => (await SynStream.TryReadAsync(
                                       flags, length, frameReader, cancellation)
                                   .ConfigureAwait(false)).AsControl(),
                SynReply.Type => (await SynReply.TryReadAsync(
                                      flags, length, frameReader, cancellation)
                                  .ConfigureAwait(false)).AsControl(),
                RstStream.Type => (await RstStream.TryReadAsync(
                                       flags, length, frameReader, cancellation)
                                   .ConfigureAwait(false)).AsControl(),
                Settings.Type => (await Settings.TryReadAsync(
                                      flags, length, frameReader, cancellation)
                                  .ConfigureAwait(false)).AsControl(),
                Ping.Type => (await Ping.TryReadAsync(
                                  flags, length, frameReader, cancellation)
                              .ConfigureAwait(false)).AsControl(),
                GoAway.Type => (await GoAway.TryReadAsync(
                                    flags, length, frameReader, cancellation)
                                .ConfigureAwait(false)).AsControl(),
                Headers.Type => (await Headers.TryReadAsync(
                                     flags, length, frameReader, cancellation)
                                 .ConfigureAwait(false)).AsControl(),
                WindowUpdate.Type => (await WindowUpdate.TryReadAsync(
                                          flags, length, frameReader, cancellation)
                                      .ConfigureAwait(false)).AsControl(),
                _ => throw new ArgumentOutOfRangeException(
                    nameof(type), $"Unknown control frame type {type} received")
            });
        private QueryInfo GetAndReleaseQueryInfo(IFrameReader frameReader)
        {
            if (_isClosed == 1)
            {
                throw new OperationCanceledException();
            }

            QueryInfo queryInfo;
            byte      streamId = frameReader.StreamId;

            queryInfo                     = _queryInfos[streamId];
            _queryInfos[streamId]         = null;
            _availableStreamIds[streamId] = 0; // free the streamId
            Interlocked.Increment(ref _availableStreamIdCount);
            return(queryInfo);
        }
Ejemplo n.º 10
0
        private void PushResult(QueryInfo queryInfo, IFrameReader frameReader, bool isAsync)
        {
            try
            {
                _instrumentation.ClientTrace(queryInfo.Token, EventType.BeginRead);
                try
                {
                    if (null != frameReader.ResponseException)
                    {
                        throw frameReader.ResponseException;
                    }

                    queryInfo.Push(frameReader);
                }
                catch (Exception ex)
                {
                    queryInfo.NotifyError(ex);

                    if (IsStreamInBadState(ex))
                    {
                        throw;
                    }
                }

                _instrumentation.ClientTrace(queryInfo.Token, EventType.EndRead);

                InstrumentationToken token = queryInfo.Token;
                if (0 != (token.ExecutionFlags & ExecutionFlags.ServerTracing))
                {
                    _instrumentation.ServerTrace(token, frameReader.TraceId);
                }
            }
            catch (Exception ex)
            {
                if (isAsync)
                {
                    HandleError(ex);
                }
            }
            finally
            {
                if (isAsync)
                {
                    frameReader.SafeDispose();
                }
            }
        }
Ejemplo n.º 11
0
        public ZlibReader(
            IFrameReader frameReader,
            byte[] dictionary,
            int length)
        {
            if (length <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length), $"{length} is an invalid length of a Zlib stream");
            }

            _frameReader  = frameReader;
            _headerReader = new FrameReader(_pipe.Reader);
            _dictionary   = dictionary;
            _length       = length;

            _backgroundTask = RunZlibDecompress();
        }
Ejemplo n.º 12
0
        private QueryInfo GetAndReleaseQueryInfo(IFrameReader frameReader)
        {
            QueryInfo queryInfo;
            ushort    streamId = frameReader.StreamId;

            lock (_lock)
            {
                Monitor.Pulse(_lock);
                if (_isClosed)
                {
                    throw new OperationCanceledException();
                }

                queryInfo             = _queryInfos[streamId];
                _queryInfos[streamId] = null;
                _availableStreamIds.Push(streamId);
            }

            return(queryInfo);
        }
Ejemplo n.º 13
0
Archivo: Data.cs Proyecto: lulzzz/Port
        internal new static async ValueTask <ReadResult <Data> > TryReadAsync(
            IFrameReader frameReader,
            CancellationToken cancellation = default)
        {
            // Since bit 31 is the control bit which is 0 for data frames,
            // there is no need to blank it out
            var streamId = UInt31.From(
                await frameReader.ReadUInt32Async(cancellation)
                .ConfigureAwait(false));
            var flags = await frameReader.ReadByteAsync(cancellation)
                        .ConfigureAwait(false);

            var length = await frameReader.ReadUInt24Async(cancellation)
                         .ConfigureAwait(false);

            var payload = await frameReader.ReadBytesAsync(
                (int)length.Value, cancellation)
                          .ConfigureAwait(false);

            return(ReadResult.Ok(new Data(streamId, flags.ToEnum <Options>(), payload)));
        }
Ejemplo n.º 14
0
        private void ReadResponse()
        {
            while (true)
            {
                IFrameReader frameReader = null;
                try
                {
                    frameReader = _config.ReceiveBuffering
                                          ? new BufferingFrameReader(_socket)
                                          : new StreamingFrameReader(_socket);

                    QueryInfo queryInfo = GetAndReleaseQueryInfo(frameReader);

                    _pushResult(queryInfo, frameReader, _config.ReceiveBuffering);
                }
                catch (Exception ex)
                {
                    frameReader.SafeDispose();
                    throw;
                }
            }
        }
Ejemplo n.º 15
0
        private static IEnumerable <T> ReadRowSet(IFrameReader frameReader, IDataMapper mapperFactory)
        {
            if (MessageOpcodes.Result != frameReader.MessageOpcode)
            {
                throw new ArgumentException("Unknown server response");
            }

            if (null == mapperFactory)
            {
                yield break;
            }

            Stream       stream       = frameReader.ReadOnlyStream;
            ResultOpcode resultOpcode = (ResultOpcode)stream.ReadInt();

            switch (resultOpcode)
            {
            case ResultOpcode.Void:
                yield break;

            case ResultOpcode.Rows:
                IColumnSpec[] columnSpecs = ReadColumnSpec(frameReader);
                foreach (T row in ReadRows(frameReader, columnSpecs, mapperFactory))
                {
                    yield return(row);
                }
                break;

            case ResultOpcode.SetKeyspace:
                yield break;

            case ResultOpcode.SchemaChange:
                yield break;

            default:
                throw new ArgumentException("Unexpected ResultOpcode");
            }
        }
Ejemplo n.º 16
0
        protected override IEnumerable <Tuple <byte[], IColumnSpec[]> > ReadFrame(IFrameReader frameReader)
        {
            if (MessageOpcodes.Result != frameReader.MessageOpcode)
            {
                throw new ArgumentException("Unknown server response");
            }

            Stream       stream       = frameReader.ReadOnlyStream;
            ResultOpcode resultOpcode = (ResultOpcode)stream.ReadInt();

            switch (resultOpcode)
            {
            case ResultOpcode.Prepared:
                byte[]        queryId     = stream.ReadShortBytes();
                IColumnSpec[] columnSpecs = ReadColumnSpec(frameReader);
                yield return(Tuple.Create(queryId, columnSpecs));

                break;

            default:
                throw new ArgumentException("Unexpected ResultOpcode");
            }
        }
Ejemplo n.º 17
0
        internal static async ValueTask <ReadResult <Frame> > TryReadAsync(
            IFrameReader frameReader,
            CancellationToken cancellation = default)
        {
            try
            {
                var firstByte = await frameReader.PeekByteAsync(cancellation)
                                .ConfigureAwait(false);

                var isControlFrame = (firstByte & 0x80) != 0;
                if (isControlFrame)
                {
                    return(await Control.TryReadAsync(frameReader, cancellation)
                           .ConfigureAwait(false));
                }

                return(await Data.TryReadAsync(frameReader, cancellation)
                       .ConfigureAwait(false));
            }
            catch when(cancellation.IsCancellationRequested)
            {
                throw;
            }
        private void ReadResponse()
        {
            var token = running.Token;

            while (token.IsCancellationRequested == false)
            {
                IFrameReader frameReader = null;
                try
                {
                    frameReader = _config.ReceiveBuffering
                                          ? new BufferingFrameReader(_socket)
                                          : new StreamingFrameReader(_socket);

                    QueryInfo queryInfo = GetAndReleaseQueryInfo(frameReader);

                    _pushResult(queryInfo, frameReader, _config.ReceiveBuffering);
                }
                catch (Exception)
                {
                    frameReader.SafeDispose();
                    throw;
                }
            }
        }
        private static IEnumerable<object> ReadOptions(IFrameReader frameReader)
        {
            if (frameReader.MessageOpcode != MessageOpcodes.Supported)
            {
                throw new UnknownResponseException(frameReader.MessageOpcode);
            }

            Stream stream = frameReader.ReadOnlyStream;
            Dictionary<string, string[]> res = stream.ReadStringMultimap();
            yield return res;
        }
Ejemplo n.º 20
0
 protected override IEnumerable <T> ReadFrame(IFrameReader frameReader)
 {
     return(ReadRowSet(frameReader, _mapperOut));
 }
Ejemplo n.º 21
0
        protected override IEnumerable <bool> ReadFrame(IFrameReader frameReader)
        {
            bool res = frameReader.MessageOpcode == MessageOpcodes.Ready;

            yield return(res);
        }
Ejemplo n.º 22
0
        private void HandleFrameTerminaison(Exception ex, IFrameReader frameReader, byte streamId)
        {
            if (null != ex)
            {
                _logger.Debug("HandleFrameTerminaison notified with exception {0}", ex);
            }

            bool isFatal = ex is IOException
                           || ex is SocketException
                           || ex is OperationCanceledException
                           || null == frameReader;
            if (! isFatal)
            {
                InstrumentationToken token = _queryInfos[streamId].InstrumentationToken;

                // release streamId now
                lock (_globalLock)
                {
                    _queryInfos[streamId] = new QueryInfo();

                    // release stream id (since result streaming has started)
                    _availableStreamIds.Push(streamId);
                    Monitor.Pulse(_globalLock);
                }

                _instrumentation.ClientTrace(token, EventType.EndRead);

                frameReader.SafeDispose();

                if (_streaming)
                {
                    Task.Factory.StartNew(ReadNextFrameHeader, _cancellation.Token);
                }

                if (0 != (token.ExecutionFlags & ExecutionFlags.ServerTracing) && frameReader.TraceId.HasValue)
                {
                    TracingSession tracingSession = this.GetTracingSession(frameReader.TraceId.Value);
                    _instrumentation.ServerTrace(token, tracingSession);
                }
                return;
            }

            lock (_globalLock)
            {
                _logger.Error("Connection to {0} is broken", Endpoint);

                if (null != OnFailure)
                {
                    FailureEventArgs failureEventArgs = new FailureEventArgs(ex);
                    OnFailure(this, failureEventArgs);
                }
            }
        }
Ejemplo n.º 23
0
 public FrameFilter(IFrameReader aReader)
     : this(aReader, null)
 {
 }
        private static IEnumerable<object> ReadRowSet(IFrameReader frameReader, IDataMapperFactory mapperFactory)
        {
            if (MessageOpcodes.Result != frameReader.MessageOpcode)
            {
                throw new ArgumentException("Unknown server response");
            }

            if (null == mapperFactory)
            {
                yield break;
            }

            Stream stream = frameReader.ReadOnlyStream;
            ResultOpcode resultOpcode = (ResultOpcode) stream.ReadInt();
            switch (resultOpcode)
            {
                case ResultOpcode.Void:
                    yield break;

                case ResultOpcode.Rows:
                    IColumnSpec[] columnSpecs = ReadColumnSpec(frameReader);
                    foreach (object row in ReadRows(frameReader, columnSpecs, mapperFactory))
                    {
                        yield return row;
                    }
                    break;

                case ResultOpcode.SetKeyspace:
                    yield break;

                case ResultOpcode.SchemaChange:
                    yield break;

                default:
                    throw new ArgumentException("Unexpected ResultOpcode");
            }
        }
        private static IEnumerable<object> ReadRows(IFrameReader frameReader, IColumnSpec[] columnSpecs, IDataMapperFactory mapperFactory)
        {
            Stream stream = frameReader.ReadOnlyStream;
            int rowCount = stream.ReadInt();
            for (int rowIdx = 0; rowIdx < rowCount; ++rowIdx)
            {
                IInstanceBuilder instanceBuilder = mapperFactory.CreateBuilder();
                foreach (ColumnSpec colSpec in columnSpecs)
                {
                    byte[] rawData = stream.ReadByteArray();
                    object data = null != rawData
                                          ? colSpec.Deserialize(rawData)
                                          : null;
                    instanceBuilder.Set(colSpec, data);
                }

                yield return instanceBuilder.Build();
            }
        }
        private static IColumnSpec[] ReadColumnSpec(IFrameReader frameReader)
        {
            Stream stream = frameReader.ReadOnlyStream;
            MetadataFlags flags = (MetadataFlags) stream.ReadInt();
            bool globalTablesSpec = 0 != (flags & MetadataFlags.GlobalTablesSpec);

            int colCount = stream.ReadInt();

            string keyspace = null;
            string table = null;
            if (globalTablesSpec)
            {
                keyspace = stream.ReadString();
                table = stream.ReadString();
            }

            IColumnSpec[] columnSpecs = new IColumnSpec[colCount];
            for (int colIdx = 0; colIdx < colCount; ++colIdx)
            {
                string colKeyspace = keyspace;
                string colTable = table;
                if (!globalTablesSpec)
                {
                    colKeyspace = stream.ReadString();
                    colTable = stream.ReadString();
                }
                string colName = stream.ReadString();
                ColumnType colType = (ColumnType) stream.ReadShort();
                string colCustom = null;
                ColumnType colKeyType = ColumnType.Custom;
                ColumnType colValueType = ColumnType.Custom;
                switch (colType)
                {
                    case ColumnType.Custom:
                        colCustom = stream.ReadString();
                        break;

                    case ColumnType.List:
                    case ColumnType.Set:
                        colValueType = (ColumnType) stream.ReadShort();
                        break;

                    case ColumnType.Map:
                        colKeyType = (ColumnType) stream.ReadShort();
                        colValueType = (ColumnType) stream.ReadShort();
                        break;
                }

                columnSpecs[colIdx] = new ColumnSpec(colIdx, colKeyspace, colTable, colName, colType, colCustom, colKeyType, colValueType);
            }

            return columnSpecs;
        }
Ejemplo n.º 27
0
 public FrameWriterDisk(IFrameReader aReader)
 {
     iReader = aReader;
     //iFileStream = new FileStream("c:\\multipus.dat", FileMode.Create, FileAccess.Write);
     //iBinFormatter = new BinaryFormatter();
 }
Ejemplo n.º 28
0
 public FrameDecoder(IFrameReader <TFrame> frameReader) => _frameReader = frameReader;
        private static IEnumerable<object> ReadPreparedQuery(IFrameReader frameReader)
        {
            if (MessageOpcodes.Result != frameReader.MessageOpcode)
            {
                throw new ArgumentException("Unknown server response");
            }

            Stream stream = frameReader.ReadOnlyStream;
            ResultOpcode resultOpcode = (ResultOpcode) stream.ReadInt();
            switch (resultOpcode)
            {
                case ResultOpcode.Prepared:
                    byte[] queryId = stream.ReadShortBytes();
                    IColumnSpec[] columnSpecs = ReadColumnSpec(frameReader);
                    yield return Tuple.Create(queryId, columnSpecs);
                    break;

                default:
                    throw new ArgumentException("Unexpected ResultOpcode");
            }
        }
Ejemplo n.º 30
0
 public abstract void Push(IFrameReader frameReader);
Ejemplo n.º 31
0
        protected override IEnumerable <bool> ReadFrame(IFrameReader frameReader)
        {
            bool mustAuthenticate = frameReader.MessageOpcode == MessageOpcodes.Authenticate;

            yield return(mustAuthenticate);
        }
Ejemplo n.º 32
0
 protected abstract IEnumerable <T> ReadFrame(IFrameReader frameReader);
        private static IEnumerable<object> ReadAuthenticate(IFrameReader frameReader)
        {
            if (frameReader.MessageOpcode != MessageOpcodes.Ready)
            {
                throw new InvalidCredentialException();
            }

            return Enumerable.Empty<object>();
        }
Ejemplo n.º 34
0
        private void HandleFrameTerminaison(Exception ex, IFrameReader frameReader, byte streamId)
        {
            if (null != ex)
            {
                _logger.Debug("HandleFrameTerminaison notified with exception {0}", ex);
            }

            bool isFatal = ex is IOException || ex is SocketException || ex is OperationCanceledException;
            if (! isFatal)
            {
                frameReader.SafeDispose();

                InstrumentationToken token = _queryInfos[streamId].InstrumentationToken;
                _instrumentation.ClientTrace(token, EventType.EndRead);

                _queryInfos[streamId] = new QueryInfo();

                // release streamId now
                lock (_globalLock)
                {
                    if (_cancellation.IsCancellationRequested)
                    {
                        return;
                    }

                    // release stream id (since result streaming has started)
                    _availableStreamIds.Push(streamId);
                    Monitor.Pulse(_globalLock);

                    if (_streaming && null != frameReader)
                    {
                        Task.Factory.StartNew(ReadNextFrameHeader, _cancellation.Token);
                    }
                }
                return;
            }

            lock (_globalLock)
            {
                _logger.Error("Connection to {0} is broken", Endpoint);

                if (null != OnFailure)
                {
                    FailureEventArgs failureEventArgs = new FailureEventArgs(ex);
                    OnFailure(this, failureEventArgs);
                }
            }
        }
 private static IEnumerable<object> ReadReady(IFrameReader frameReader)
 {
     bool mustAuthenticate = frameReader.MessageOpcode == MessageOpcodes.Authenticate;
     yield return mustAuthenticate;
 }