public static void WriteDocument(this BlittableJsonTextWriter writer, JsonOperationContext context, Document document, bool metadataOnly, Func <LazyStringValue, bool> filterMetadataProperty = null)
        {
            if (document == null)
            {
                writer.WriteNull();
                return;
            }

            if (document == Document.ExplicitNull)
            {
                writer.WriteNull();
                return;
            }

            // Explicitly not disposing it, a single document can be
            // used multiple times in a single query, for example, due to projections
            // so we will let the context handle it, rather than handle it directly ourselves
            //using (document.Data)
            {
                if (metadataOnly == false)
                {
                    writer.WriteDocumentInternal(context, document, filterMetadataProperty);
                }
                else
                {
                    writer.WriteDocumentMetadata(context, document, filterMetadataProperty);
                }
            }
        }
예제 #2
0
        public void WriteTo(BlittableJsonTextWriter writer)
        {
            writer.WriteStartObject();

            writer.WritePropertyName(nameof(UpTime));
            writer.WriteString(UpTime.ToString("c"));
            writer.WriteComma();

            writer.WritePropertyName(nameof(StartUpTime));
            writer.WriteDateTime(StartUpTime, isUtc: true);
            writer.WriteComma();

            writer.WritePropertyName(nameof(LastRequestTime));
            if (LastRequestTime.HasValue)
            {
                writer.WriteDateTime(LastRequestTime.Value, isUtc: true);
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(LastAuthorizedNonClusterAdminRequestTime));
            if (LastAuthorizedNonClusterAdminRequestTime.HasValue)
            {
                writer.WriteDateTime(LastAuthorizedNonClusterAdminRequestTime.Value, isUtc: true);
            }
            else
            {
                writer.WriteNull();
            }

            writer.WriteEndObject();
        }
        public static void WriteDocument(this BlittableJsonTextWriter writer, JsonOperationContext context, Document document, bool metadataOnly)
        {
            if (document == null)
            {
                writer.WriteNull();
                return;
            }

            if (document == Document.ExplicitNull)
            {
                writer.WriteNull();
                return;
            }

            using (document.Data)
            {
                if (metadataOnly == false)
                {
                    writer.WriteDocumentInternal(context, document);
                }
                else
                {
                    writer.WriteDocumentMetadata(context, document);
                }
            }
        }
예제 #4
0
        public Task GetSetupParameters()
        {
            AssertOnlyInSetupMode();
            var setupParameters = SetupParameters.Get(ServerStore);

            using (ServerStore.ContextPool.AllocateOperationContext(out TransactionOperationContext context))
                using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName(nameof(SetupParameters.FixedServerPortNumber));

                    if (setupParameters.FixedServerPortNumber.HasValue)
                    {
                        writer.WriteInteger(setupParameters.FixedServerPortNumber.Value);
                    }
                    else
                    {
                        writer.WriteNull();
                    }

                    writer.WriteComma();

                    writer.WritePropertyName(nameof(SetupParameters.IsDocker));
                    writer.WriteBool(setupParameters.IsDocker);

                    writer.WriteEndObject();
                }

            return(Task.CompletedTask);
        }
        public static void WriteObjects(this BlittableJsonTextWriter writer, JsonOperationContext context, IEnumerable <BlittableJsonReaderObject> objects, out int numberOfResults)
        {
            numberOfResults = 0;

            writer.WriteStartArray();

            var first = true;

            foreach (var o in objects)
            {
                numberOfResults++;

                if (first == false)
                {
                    writer.WriteComma();
                }
                first = false;

                if (o == null)
                {
                    writer.WriteNull();
                    continue;
                }

                using (o)
                {
                    writer.WriteObject(o);
                }
            }

            writer.WriteEndArray();
        }
예제 #6
0
        public Task GetClientConfiguration()
        {
            var inherit = GetBoolValueQueryString("inherit", required: false) ?? true;

            var  configuration       = Database.ClientConfiguration;
            long etag                = configuration?.Etag ?? -1;
            var  serverConfiguration = GetServerClientConfiguration(out long serverIndex);

            etag = Hashing.Combine(etag, serverConfiguration?.Etag ?? -2);
            if (inherit)
            {
                if (configuration == null || configuration.Disabled)
                {
                    if (serverConfiguration != null)
                    {
                        configuration = serverConfiguration;
                        etag          = serverIndex;
                    }
                }
            }

            using (ContextPool.AllocateOperationContext(out JsonOperationContext context))
            {
                BlittableJsonReaderObject clientConfigurationJson = null;
                if (configuration != null)
                {
                    var val = configuration.ToJson();
                    clientConfigurationJson = context.ReadObject(val, Constants.Configuration.ClientId);
                }

                using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    writer.WriteStartObject();

                    writer.WritePropertyName(nameof(GetClientConfigurationOperation.Result.Etag));
                    writer.WriteInteger(etag);
                    writer.WriteComma();

                    writer.WritePropertyName(nameof(GetClientConfigurationOperation.Result.Configuration));
                    if (clientConfigurationJson != null)
                    {
                        writer.WriteObject(clientConfigurationJson);
                    }
                    else
                    {
                        writer.WriteNull();
                    }

                    writer.WriteEndObject();
                }
            }

            return(Task.CompletedTask);
        }
예제 #7
0
        internal static void WriteTimeSeriesRangeResults(DocumentsOperationContext context, BlittableJsonTextWriter writer, string documentId, Dictionary <string, List <TimeSeriesRangeResult> > dictionary)
        {
            if (dictionary == null)
            {
                writer.WriteNull();
                return;
            }

            writer.WriteStartObject();

            bool first = true;

            foreach (var(name, ranges) in dictionary)
            {
                if (first == false)
                {
                    writer.WriteComma();
                }

                first = false;

                writer.WritePropertyName(name);

                writer.WriteStartArray();

                (long Count, DateTime Start, DateTime End)stats = default;
                if (documentId != null)
                {
                    Debug.Assert(context != null);
                    stats = context.DocumentDatabase.DocumentsStorage.TimeSeriesStorage.Stats.GetStats(context, documentId, name);
                }

                for (var i = 0; i < ranges.Count; i++)
                {
                    long?totalCount = null;

                    if (i > 0)
                    {
                        writer.WriteComma();
                    }

                    if (stats != default && ranges[i].From <= stats.Start && ranges[i].To >= stats.End)
                    {
                        totalCount = stats.Count;
                    }

                    WriteRange(writer, ranges[i], totalCount);
                }
                writer.WriteEndArray();
            }

            writer.WriteEndObject();
        }
예제 #8
0
            private void WriteClientConfiguration(ClientConfiguration clientConfiguration)
            {
                if (clientConfiguration == null)
                {
                    _writer.WriteNull();
                    return;
                }

                _writer.WriteStartObject();

                _writer.WritePropertyName(nameof(clientConfiguration.Etag));
                _writer.WriteInteger(clientConfiguration.Etag);
                _writer.WriteComma();

                _writer.WritePropertyName(nameof(clientConfiguration.Disabled));
                _writer.WriteBool(clientConfiguration.Disabled);

                if (clientConfiguration.MaxNumberOfRequestsPerSession.HasValue)
                {
                    _writer.WriteComma();
                    _writer.WritePropertyName(nameof(clientConfiguration.MaxNumberOfRequestsPerSession));
                    _writer.WriteInteger(clientConfiguration.MaxNumberOfRequestsPerSession.Value);
                }

                if (clientConfiguration.PrettifyGeneratedLinqExpressions.HasValue)
                {
                    _writer.WriteComma();
                    _writer.WritePropertyName(nameof(clientConfiguration.PrettifyGeneratedLinqExpressions));
                    _writer.WriteBool(clientConfiguration.PrettifyGeneratedLinqExpressions.Value);
                }

                if (clientConfiguration.ReadBalanceBehavior.HasValue)
                {
                    _writer.WriteComma();
                    _writer.WritePropertyName(nameof(clientConfiguration.ReadBalanceBehavior));
                    _writer.WriteString(clientConfiguration.ReadBalanceBehavior.Value.ToString());
                }

                _writer.WriteEndObject();
            }
예제 #9
0
 private void WriteOperationHeaderToRemote(BlittableJsonTextWriter writer)
 {
     writer.WriteStartObject();
     {
         writer.WritePropertyName(nameof(TcpConnectionHeaderMessage.Operation));
         writer.WriteString(TcpConnectionHeaderMessage.OperationTypes.Heartbeats.ToString());
         writer.WritePropertyName(nameof(TcpConnectionHeaderMessage.OperationVersion));
         writer.WriteInteger(TcpConnectionHeaderMessage.HeartbeatsTcpVersion);
         writer.WritePropertyName(nameof(TcpConnectionHeaderMessage.DatabaseName));
         writer.WriteNull();
     }
     writer.WriteEndObject();
     writer.Flush();
 }
예제 #10
0
        protected override void PersistMapFields(JsonOperationContext context, BlittableJsonTextWriter writer)
        {
            writer.WritePropertyName(nameof(MapFields));
            writer.WriteStartArray();
            var first = true;

            foreach (var field in MapFields.Values.Select(x => x.As <AutoIndexField>()))
            {
                if (first == false)
                {
                    writer.WriteComma();
                }

                writer.WriteStartObject();

                writer.WritePropertyName(nameof(field.Name));
                writer.WriteString(field.Name);
                writer.WriteComma();

                writer.WritePropertyName(nameof(field.Indexing));
                writer.WriteString(field.Indexing.ToString());
                writer.WriteComma();

                writer.WritePropertyName(nameof(field.Aggregation));
                writer.WriteInteger((int)field.Aggregation);
                writer.WriteComma();

                writer.WritePropertyName(nameof(field.Spatial));
                if (field.Spatial == null)
                {
                    writer.WriteNull();
                }
                else
                {
                    writer.WriteObject(DocumentConventions.DefaultForServer.Serialization.DefaultConverter.ToBlittable(field.Spatial, context));
                }
                writer.WriteComma();

                writer.WritePropertyName(nameof(field.HasSuggestions));
                writer.WriteBool(field.HasSuggestions);

                writer.WriteEndObject();

                first = false;
            }
            writer.WriteEndArray();
        }
예제 #11
0
        public static string ConvertResultToString(ScriptRunnerResult result)
        {
            var ms = new MemoryStream();

            using (var ctx = JsonOperationContext.ShortTermSingleUse())
                using (var writer = new BlittableJsonTextWriter(ctx, ms))
                {
                    writer.WriteStartObject();

                    writer.WritePropertyName("Result");

                    if (result.IsNull)
                    {
                        writer.WriteNull();
                    }
                    else if (result.RawJsValue.IsBoolean())
                    {
                        writer.WriteBool(result.RawJsValue.AsBoolean());
                    }
                    else if (result.RawJsValue.IsString())
                    {
                        writer.WriteString(result.RawJsValue.AsString());
                    }
                    else if (result.RawJsValue.IsDate())
                    {
                        var date = result.RawJsValue.AsDate();
                        writer.WriteString(date.ToDateTime().ToString("O"));
                    }
                    else if (result.RawJsValue.IsNumber())
                    {
                        writer.WriteDouble(result.RawJsValue.AsNumber());
                    }
                    else
                    {
                        writer.WriteObject(result.TranslateToObject(ctx));
                    }

                    writer.WriteEndObject();
                    writer.Flush();
                }

            var str = Encoding.UTF8.GetString(ms.ToArray());

            return(str);
        }
예제 #12
0
        private void WriteOperationHeaderToRemote(BlittableJsonTextWriter writer, bool drop = false)
        {
            var operation = drop ? TcpConnectionHeaderMessage.OperationTypes.Drop : TcpConnectionHeaderMessage.OperationTypes.Heartbeats;

            writer.WriteStartObject();
            {
                writer.WritePropertyName(nameof(TcpConnectionHeaderMessage.Operation));
                writer.WriteString(operation.ToString());
                writer.WriteComma();
                writer.WritePropertyName(nameof(TcpConnectionHeaderMessage.OperationVersion));
                writer.WriteInteger(TcpConnectionHeaderMessage.HeartbeatsTcpVersion);
                writer.WriteComma();
                writer.WritePropertyName(nameof(TcpConnectionHeaderMessage.DatabaseName));
                writer.WriteNull();
            }
            writer.WriteEndObject();
            writer.Flush();
        }
        private static void WriteIndexFieldOptions(this BlittableJsonTextWriter writer, JsonOperationContext context, IndexFieldOptions options, bool removeAnalyzers)
        {
            writer.WriteStartObject();

            writer.WritePropertyName(nameof(options.Analyzer));
            if (string.IsNullOrWhiteSpace(options.Analyzer) == false && !removeAnalyzers)
            {
                writer.WriteString(options.Analyzer);
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(options.Indexing));
            if (options.Indexing.HasValue)
            {
                writer.WriteString(options.Indexing.ToString());
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(options.Storage));
            if (options.Storage.HasValue)
            {
                writer.WriteString(options.Storage.ToString());
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(options.Suggestions));
            if (options.Suggestions.HasValue)
            {
                writer.WriteBool(options.Suggestions.Value);
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(options.TermVector));
            if (options.TermVector.HasValue)
            {
                writer.WriteString(options.TermVector.ToString());
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(options.Spatial));
            if (options.Spatial != null)
            {
                writer.WriteStartObject();

                writer.WritePropertyName(nameof(options.Spatial.Type));
                writer.WriteString(options.Spatial.Type.ToString());
                writer.WriteComma();

                writer.WritePropertyName(nameof(options.Spatial.MaxTreeLevel));
                writer.WriteInteger(options.Spatial.MaxTreeLevel);
                writer.WriteComma();

                writer.WritePropertyName(nameof(options.Spatial.MaxX));
                LazyStringValue lazyStringValue;
                using (lazyStringValue = context.GetLazyString(CharExtensions.ToInvariantString(options.Spatial.MaxX)))
                    writer.WriteDouble(new LazyNumberValue(lazyStringValue));
                writer.WriteComma();

                writer.WritePropertyName(nameof(options.Spatial.MaxY));
                using (lazyStringValue = context.GetLazyString(CharExtensions.ToInvariantString(options.Spatial.MaxY)))
                    writer.WriteDouble(new LazyNumberValue(lazyStringValue));
                writer.WriteComma();

                writer.WritePropertyName(nameof(options.Spatial.MinX));
                using (lazyStringValue = context.GetLazyString(CharExtensions.ToInvariantString(options.Spatial.MinX)))
                    writer.WriteDouble(new LazyNumberValue(lazyStringValue));
                writer.WriteComma();

                writer.WritePropertyName(nameof(options.Spatial.MinY));
                using (lazyStringValue = context.GetLazyString(CharExtensions.ToInvariantString(options.Spatial.MinY)))
                    writer.WriteDouble(new LazyNumberValue(lazyStringValue));
                writer.WriteComma();

                writer.WritePropertyName(nameof(options.Spatial.Strategy));
                writer.WriteString(options.Spatial.Strategy.ToString());
                writer.WriteComma();

                writer.WritePropertyName(nameof(options.Spatial.Units));
                writer.WriteString(options.Spatial.Units.ToString());

                writer.WriteEndObject();
            }
            else
            {
                writer.WriteNull();
            }

            writer.WriteEndObject();
        }
예제 #14
0
        public Task GetErrors()
        {
            var names = HttpContext.Request.Query["name"];

            List <Index> indexes;

            if (names.Count == 0)
            {
                indexes = Database.IndexStore.GetIndexes().ToList();
            }
            else
            {
                indexes = new List <Index>();
                foreach (var name in names)
                {
                    var index = Database.IndexStore.GetIndex(name);
                    if (index == null)
                    {
                        throw new InvalidOperationException("There is not index with name: " + name);
                    }

                    indexes.Add(index);
                }
            }

            DocumentsOperationContext context;

            using (ContextPool.AllocateOperationContext(out context))
                using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    writer.WriteStartArray();

                    var first = true;
                    foreach (var index in indexes)
                    {
                        if (first == false)
                        {
                            writer.WriteComma();
                        }

                        first = false;

                        writer.WriteStartObject();

                        writer.WritePropertyName(("Name"));
                        writer.WriteString((index.Name));
                        writer.WriteComma();

                        writer.WritePropertyName(("Errors"));
                        writer.WriteStartArray();
                        var firstError = true;
                        foreach (var error in index.GetErrors())
                        {
                            if (firstError == false)
                            {
                                writer.WriteComma();
                            }

                            firstError = false;

                            writer.WriteStartObject();

                            writer.WritePropertyName((nameof(error.Timestamp)));
                            writer.WriteString((error.Timestamp.GetDefaultRavenFormat()));
                            writer.WriteComma();

                            writer.WritePropertyName((nameof(error.Document)));
                            if (string.IsNullOrWhiteSpace(error.Document) == false)
                            {
                                writer.WriteString((error.Document));
                            }
                            else
                            {
                                writer.WriteNull();
                            }
                            writer.WriteComma();

                            writer.WritePropertyName((nameof(error.Action)));
                            if (string.IsNullOrWhiteSpace(error.Action) == false)
                            {
                                writer.WriteString((error.Action));
                            }
                            else
                            {
                                writer.WriteNull();
                            }
                            writer.WriteComma();

                            writer.WritePropertyName((nameof(error.Error)));
                            if (string.IsNullOrWhiteSpace(error.Error) == false)
                            {
                                writer.WriteString((error.Error));
                            }
                            else
                            {
                                writer.WriteNull();
                            }

                            writer.WriteEndObject();
                        }

                        writer.WriteEndArray();

                        writer.WriteEndObject();
                    }

                    writer.WriteEndArray();
                }

            return(Task.CompletedTask);
        }
        public static void WriteIndexDefinition(this BlittableJsonTextWriter writer, JsonOperationContext context, IndexDefinition indexDefinition, bool removeAnalyzers = false)
        {
            writer.WriteStartObject();

            writer.WritePropertyName(nameof(indexDefinition.Name));
            writer.WriteString(indexDefinition.Name);
            writer.WriteComma();

            writer.WritePropertyName(nameof(indexDefinition.Etag));
            writer.WriteInteger(indexDefinition.Etag);
            writer.WriteComma();

            writer.WritePropertyName(nameof(indexDefinition.Type));
            writer.WriteString(indexDefinition.Type.ToString());
            writer.WriteComma();

            writer.WritePropertyName(nameof(indexDefinition.LockMode));
            if (indexDefinition.LockMode.HasValue)
            {
                writer.WriteString(indexDefinition.LockMode.ToString());
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(indexDefinition.Priority));
            if (indexDefinition.Priority.HasValue)
            {
                writer.WriteString(indexDefinition.Priority.ToString());
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(indexDefinition.OutputReduceToCollection));
            writer.WriteString(indexDefinition.OutputReduceToCollection);
            writer.WriteComma();

            writer.WritePropertyName(nameof(indexDefinition.Configuration));
            writer.WriteStartObject();
            var isFirstInternal = true;

            foreach (var kvp in indexDefinition.Configuration)
            {
                if (isFirstInternal == false)
                {
                    writer.WriteComma();
                }

                isFirstInternal = false;

                writer.WritePropertyName(kvp.Key);
                writer.WriteString(kvp.Value);
            }
            writer.WriteEndObject();
            writer.WriteComma();

            writer.WritePropertyName(nameof(indexDefinition.AdditionalSources));
            writer.WriteStartObject();
            isFirstInternal = true;
            foreach (var kvp in indexDefinition.AdditionalSources)
            {
                if (isFirstInternal == false)
                {
                    writer.WriteComma();
                }

                isFirstInternal = false;

                writer.WritePropertyName(kvp.Key);
                writer.WriteString(kvp.Value);
            }
            writer.WriteEndObject();
            writer.WriteComma();

            writer.WritePropertyName(nameof(indexDefinition.IsTestIndex));
            writer.WriteBool(indexDefinition.IsTestIndex);
            writer.WriteComma();

            writer.WritePropertyName(nameof(indexDefinition.Reduce));
            if (string.IsNullOrWhiteSpace(indexDefinition.Reduce) == false)
            {
                writer.WriteString(indexDefinition.Reduce);
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(indexDefinition.Maps));
            writer.WriteStartArray();
            isFirstInternal = true;
            foreach (var map in indexDefinition.Maps)
            {
                if (isFirstInternal == false)
                {
                    writer.WriteComma();
                }

                isFirstInternal = false;
                writer.WriteString(map);
            }
            writer.WriteEndArray();
            writer.WriteComma();

            writer.WritePropertyName(nameof(indexDefinition.Fields));
            writer.WriteStartObject();
            isFirstInternal = true;
            foreach (var kvp in indexDefinition.Fields)
            {
                if (isFirstInternal == false)
                {
                    writer.WriteComma();
                }

                isFirstInternal = false;
                writer.WritePropertyName(kvp.Key);
                if (kvp.Value != null)
                {
                    writer.WriteIndexFieldOptions(context, kvp.Value, removeAnalyzers);
                }
                else
                {
                    writer.WriteNull();
                }
            }
            writer.WriteEndObject();

            writer.WriteEndObject();
        }
        public static void WriteIndexProgress(this BlittableJsonTextWriter writer, JsonOperationContext context, IndexProgress progress)
        {
            writer.WriteStartObject();

            writer.WritePropertyName(nameof(progress.IsStale));
            writer.WriteBool(progress.IsStale);
            writer.WriteComma();

            writer.WritePropertyName(nameof(progress.Collections));
            if (progress.Collections != null)
            {
                writer.WriteStartObject();
                var isFirst = true;
                foreach (var kvp in progress.Collections)
                {
                    if (isFirst == false)
                    {
                        writer.WriteComma();
                    }

                    isFirst = false;

                    writer.WritePropertyName(kvp.Key);

                    writer.WriteStartObject();

                    writer.WritePropertyName(nameof(kvp.Value.LastProcessedDocumentEtag));
                    writer.WriteInteger(kvp.Value.LastProcessedDocumentEtag);
                    writer.WriteComma();

                    writer.WritePropertyName(nameof(kvp.Value.LastProcessedTombstoneEtag));
                    writer.WriteInteger(kvp.Value.LastProcessedTombstoneEtag);
                    writer.WriteComma();

                    writer.WritePropertyName(nameof(kvp.Value.NumberOfDocumentsToProcess));
                    writer.WriteInteger(kvp.Value.NumberOfDocumentsToProcess);
                    writer.WriteComma();

                    writer.WritePropertyName(nameof(kvp.Value.NumberOfTombstonesToProcess));
                    writer.WriteInteger(kvp.Value.NumberOfTombstonesToProcess);
                    writer.WriteComma();

                    writer.WritePropertyName(nameof(kvp.Value.TotalNumberOfDocuments));
                    writer.WriteInteger(kvp.Value.TotalNumberOfDocuments);
                    writer.WriteComma();

                    writer.WritePropertyName(nameof(kvp.Value.TotalNumberOfTombstones));
                    writer.WriteInteger(kvp.Value.TotalNumberOfTombstones);

                    writer.WriteEndObject();
                }
                writer.WriteEndObject();
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(progress.Name));
            writer.WriteString(progress.Name);
            writer.WriteComma();

            writer.WritePropertyName(nameof(progress.Type));
            writer.WriteString(progress.Type.ToString());
            writer.WriteComma();

            writer.WritePropertyName(nameof(progress.Etag));
            writer.WriteInteger(progress.Etag);

            writer.WriteEndObject();
        }
        public static void WriteIndexQuery(this BlittableJsonTextWriter writer, JsonOperationContext context, IndexQueryServerSide query)
        {
            writer.WriteStartObject();

            writer.WritePropertyName(nameof(query.CutoffEtag));
            if (query.CutoffEtag.HasValue)
            {
                writer.WriteInteger(query.CutoffEtag.Value);
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(query.ExplainScores));
            writer.WriteBool(query.ExplainScores);
            writer.WriteComma();

            writer.WritePropertyName(nameof(query.PageSize));
            writer.WriteInteger(query.PageSize);
            writer.WriteComma();

            writer.WritePropertyName(nameof(query.Query));
            if (query.Query != null)
            {
                writer.WriteString(query.Query);
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(query.ShowTimings));
            writer.WriteBool(query.ShowTimings);
            writer.WriteComma();

            writer.WritePropertyName(nameof(query.SkipDuplicateChecking));
            writer.WriteBool(query.SkipDuplicateChecking);
            writer.WriteComma();

            writer.WritePropertyName(nameof(query.Start));
            writer.WriteInteger(query.Start);
            writer.WriteComma();

            writer.WritePropertyName(nameof(query.WaitForNonStaleResults));
            writer.WriteBool(query.WaitForNonStaleResults);
            writer.WriteComma();

            writer.WritePropertyName(nameof(query.WaitForNonStaleResultsTimeout));
            if (query.WaitForNonStaleResultsTimeout.HasValue)
            {
                writer.WriteString(query.WaitForNonStaleResultsTimeout.Value.ToString());
            }
            else
            {
                writer.WriteNull();
            }

            writer.WriteEndObject();
        }
        public static void WriteDatabaseStatistics(this BlittableJsonTextWriter writer, JsonOperationContext context, DatabaseStatistics statistics)
        {
            writer.WriteStartObject();

            writer.WritePropertyName(nameof(statistics.CountOfIndexes));
            writer.WriteInteger(statistics.CountOfIndexes);
            writer.WriteComma();

            writer.WritePropertyName(nameof(statistics.CountOfDocuments));
            writer.WriteInteger(statistics.CountOfDocuments);
            writer.WriteComma();

            if (statistics.CountOfRevisionDocuments > 0)
            {
                writer.WritePropertyName(nameof(statistics.CountOfRevisionDocuments));
                writer.WriteInteger(statistics.CountOfRevisionDocuments);
                writer.WriteComma();
            }

            writer.WritePropertyName(nameof(statistics.CountOfAttachments));
            writer.WriteInteger(statistics.CountOfAttachments);
            writer.WriteComma();

            writer.WritePropertyName(nameof(statistics.CountOfUniqueAttachments));
            writer.WriteInteger(statistics.CountOfUniqueAttachments);
            writer.WriteComma();

            writer.WritePropertyName(nameof(statistics.DatabaseChangeVector));
            writer.WriteString(statistics.DatabaseChangeVector);
            writer.WriteComma();

            writer.WritePropertyName(nameof(statistics.DatabaseId));
            writer.WriteString(statistics.DatabaseId);
            writer.WriteComma();

            writer.WritePropertyName(nameof(statistics.Is64Bit));
            writer.WriteBool(statistics.Is64Bit);
            writer.WriteComma();

            writer.WritePropertyName(nameof(statistics.Pager));
            writer.WriteString(statistics.Pager);
            writer.WriteComma();

            writer.WritePropertyName(nameof(statistics.LastDocEtag));
            if (statistics.LastDocEtag.HasValue)
            {
                writer.WriteInteger(statistics.LastDocEtag.Value);
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName((nameof(statistics.DatabaseChangeVector)));
            writer.WriteString(statistics.DatabaseChangeVector);
            writer.WriteComma();

            writer.WritePropertyName(nameof(statistics.LastIndexingTime));
            if (statistics.LastIndexingTime.HasValue)
            {
                writer.WriteDateTime(statistics.LastIndexingTime.Value, isUtc: true);
            }
            else
            {
                writer.WriteNull();
            }
            writer.WriteComma();

            writer.WritePropertyName(nameof(statistics.Indexes));
            writer.WriteStartArray();
            var isFirstInternal = true;

            foreach (var index in statistics.Indexes)
            {
                if (isFirstInternal == false)
                {
                    writer.WriteComma();
                }

                isFirstInternal = false;

                writer.WriteStartObject();

                writer.WritePropertyName(nameof(index.IsStale));
                writer.WriteBool(index.IsStale);
                writer.WriteComma();

                writer.WritePropertyName(nameof(index.Name));
                writer.WriteString(index.Name);
                writer.WriteComma();

                writer.WritePropertyName(nameof(index.Etag));
                writer.WriteInteger(index.Etag);
                writer.WriteComma();

                writer.WritePropertyName(nameof(index.LockMode));
                writer.WriteString(index.LockMode.ToString());
                writer.WriteComma();

                writer.WritePropertyName(nameof(index.Priority));
                writer.WriteString(index.Priority.ToString());
                writer.WriteComma();

                writer.WritePropertyName(nameof(index.State));
                writer.WriteString(index.State.ToString());
                writer.WriteComma();

                writer.WritePropertyName(nameof(index.Type));
                writer.WriteString(index.Type.ToString());
                writer.WriteComma();

                writer.WritePropertyName(nameof(index.LastIndexingTime));
                if (index.LastIndexingTime.HasValue)
                {
                    writer.WriteDateTime(index.LastIndexingTime.Value, isUtc: true);
                }
                else
                {
                    writer.WriteNull();
                }

                writer.WriteEndObject();
            }
            writer.WriteEndArray();

            writer.WriteEndObject();
        }
예제 #19
0
        public override HttpRequestMessage CreateRequest(JsonOperationContext ctx, ServerNode node, out string url)
        {
            _baseUrl = $"{node.Url}/databases/{node.Database}";
            url      = $"{_baseUrl}/multi_get";

            if (MaybeReadAllFromCache(ctx, _requestExecutor.AggressiveCaching.Value))
            {
                AggressivelyCached = true;
                return(null);// aggressively cached
            }

            var request = new HttpRequestMessage
            {
                Method  = HttpMethod.Post,
                Content = new BlittableJsonContent(stream =>
                {
                    using (var writer = new BlittableJsonTextWriter(ctx, stream))
                    {
                        writer.WriteStartObject();

                        var first = true;
                        writer.WritePropertyName("Requests");
                        writer.WriteStartArray();
                        foreach (var command in _commands)
                        {
                            if (first == false)
                            {
                                writer.WriteComma();
                            }
                            first = false;

                            writer.WriteStartObject();

                            writer.WritePropertyName(nameof(GetRequest.Url));
                            writer.WriteString($"/databases/{node.Database}{command.Url}");
                            writer.WriteComma();

                            writer.WritePropertyName(nameof(GetRequest.Query));
                            writer.WriteString(command.Query);
                            writer.WriteComma();

                            writer.WritePropertyName(nameof(GetRequest.Method));
                            writer.WriteString(command.Method?.Method);
                            writer.WriteComma();

                            writer.WritePropertyName(nameof(GetRequest.Headers));
                            writer.WriteStartObject();

                            var firstInner = true;
                            foreach (var kvp in command.Headers)
                            {
                                if (firstInner == false)
                                {
                                    writer.WriteComma();
                                }

                                firstInner = false;
                                writer.WritePropertyName(kvp.Key);
                                writer.WriteString(kvp.Value);
                            }

                            writer.WriteEndObject();
                            writer.WriteComma();

                            writer.WritePropertyName(nameof(GetRequest.Content));
                            if (command.Content != null)
                            {
                                command.Content.WriteContent(writer, ctx);
                            }
                            else
                            {
                                writer.WriteNull();
                            }

                            writer.WriteEndObject();
                        }
                        writer.WriteEndArray();

                        writer.WriteEndObject();
                    }
                })
            };

            return(request);
        }
        public static void WriteTreePagesRecursively(this BlittableJsonTextWriter writer, IEnumerable <ReduceTreePage> pages)
        {
            var first = true;

            foreach (var page in pages)
            {
                if (first == false)
                {
                    writer.WriteComma();
                }

                writer.WriteStartObject();

                writer.WritePropertyName(nameof(TreePage.PageNumber));
                writer.WriteInteger(page.PageNumber);
                writer.WriteComma();

                writer.WritePropertyName(nameof(ReduceTreePage.AggregationResult));
                if (page.AggregationResult != null)
                {
                    writer.WriteObject(page.AggregationResult);
                }
                else
                {
                    writer.WriteNull();
                }
                writer.WriteComma();

                writer.WritePropertyName(nameof(ReduceTreePage.Children));
                if (page.Children != null)
                {
                    writer.WriteStartArray();
                    WriteTreePagesRecursively(writer, page.Children);
                    writer.WriteEndArray();
                }
                else
                {
                    writer.WriteNull();
                }
                writer.WriteComma();

                writer.WritePropertyName(nameof(ReduceTreePage.Entries));
                if (page.Entries != null)
                {
                    writer.WriteStartArray();

                    var firstEntry = true;
                    foreach (var entry in page.Entries)
                    {
                        if (firstEntry == false)
                        {
                            writer.WriteComma();
                        }

                        writer.WriteStartObject();

                        writer.WritePropertyName(nameof(MapResultInLeaf.Data));
                        writer.WriteObject(entry.Data);
                        writer.WriteComma();

                        writer.WritePropertyName(nameof(MapResultInLeaf.Source));
                        writer.WriteString(entry.Source);

                        writer.WriteEndObject();

                        firstEntry = false;
                    }

                    writer.WriteEndArray();
                }
                else
                {
                    writer.WriteNull();
                }

                writer.WriteEndObject();
                first = false;
            }
        }
예제 #21
0
        public static void WriteIndexQuery(this BlittableJsonTextWriter writer, DocumentConventions conventions, JsonOperationContext context, IndexQuery query)
        {
            writer.WriteStartObject();

            writer.WritePropertyName(nameof(query.Query));
            writer.WriteString(query.Query);
            writer.WriteComma();

#pragma warning disable 618
            if (query.PageSizeSet && query.PageSize >= 0)
            {
                writer.WritePropertyName(nameof(query.PageSize));
                writer.WriteInteger(query.PageSize);
                writer.WriteComma();
            }
#pragma warning restore 618

            if (query.WaitForNonStaleResults)
            {
                writer.WritePropertyName(nameof(query.WaitForNonStaleResults));
                writer.WriteBool(query.WaitForNonStaleResults);
                writer.WriteComma();
            }

#pragma warning disable 618
            if (query.Start > 0)
            {
                writer.WritePropertyName(nameof(query.Start));
                writer.WriteInteger(query.Start);
                writer.WriteComma();
            }
#pragma warning restore 618

            if (query.WaitForNonStaleResultsTimeout.HasValue)
            {
                writer.WritePropertyName(nameof(query.WaitForNonStaleResultsTimeout));
                writer.WriteString(query.WaitForNonStaleResultsTimeout.Value.ToInvariantString());
                writer.WriteComma();
            }

            if (query.DisableCaching)
            {
                writer.WritePropertyName(nameof(query.DisableCaching));
                writer.WriteBool(query.DisableCaching);
                writer.WriteComma();
            }

            if (query.SkipDuplicateChecking)
            {
                writer.WritePropertyName(nameof(query.SkipDuplicateChecking));
                writer.WriteBool(query.SkipDuplicateChecking);
                writer.WriteComma();
            }

            writer.WritePropertyName(nameof(query.QueryParameters));
            if (query.QueryParameters != null)
            {
                writer.WriteObject(conventions.Serialization.DefaultConverter.ToBlittable(query.QueryParameters, context));
            }
            else
            {
                writer.WriteNull();
            }

            writer.WriteEndObject();
        }
        public static void WriteFacetResult(this BlittableJsonTextWriter writer, JsonOperationContext context, FacetResult result)
        {
            writer.WriteStartObject();

            writer.WritePropertyName(nameof(result.RemainingHits));
            writer.WriteInteger(result.RemainingHits);
            writer.WriteComma();

            writer.WritePropertyName(nameof(result.RemainingTermsCount));
            writer.WriteInteger(result.RemainingTermsCount);
            writer.WriteComma();

            writer.WritePropertyName(nameof(result.RemainingTerms));
            writer.WriteStartArray();
            var isFirstInternal = true;

            foreach (var term in result.RemainingTerms)
            {
                if (isFirstInternal == false)
                {
                    writer.WriteComma();
                }

                isFirstInternal = false;

                writer.WriteString(term);
            }
            writer.WriteEndArray();
            writer.WriteComma();

            writer.WritePropertyName(nameof(result.Values));
            writer.WriteStartArray();
            isFirstInternal = true;
            foreach (var value in result.Values)
            {
                if (isFirstInternal == false)
                {
                    writer.WriteComma();
                }

                isFirstInternal = false;

                writer.WriteStartObject();

                writer.WritePropertyName(nameof(value.Average));
                if (value.Average.HasValue)
                {
                    using (var lazyStringValue = context.GetLazyString(value.Average.ToInvariantString()))
                        writer.WriteDouble(new LazyNumberValue(lazyStringValue));
                }
                else
                {
                    writer.WriteNull();
                }
                writer.WriteComma();

                writer.WritePropertyName(nameof(value.Count));
                if (value.Count.HasValue)
                {
                    writer.WriteInteger(value.Count.Value);
                }
                else
                {
                    writer.WriteNull();
                }
                writer.WriteComma();

                writer.WritePropertyName(nameof(value.Hits));
                writer.WriteInteger(value.Hits);
                writer.WriteComma();

                writer.WritePropertyName(nameof(value.Max));
                if (value.Max.HasValue)
                {
                    using (var lazyStringValue = context.GetLazyString(value.Max.ToInvariantString()))
                        writer.WriteDouble(new LazyNumberValue(lazyStringValue));
                }
                else
                {
                    writer.WriteNull();
                }
                writer.WriteComma();

                writer.WritePropertyName(nameof(value.Min));
                if (value.Min.HasValue)
                {
                    using (var lazyStringValue = context.GetLazyString(value.Min.ToInvariantString()))
                        writer.WriteDouble(new LazyNumberValue(lazyStringValue));
                }
                else
                {
                    writer.WriteNull();
                }
                writer.WriteComma();

                writer.WritePropertyName(nameof(value.Range));
                writer.WriteString(value.Range);
                writer.WriteComma();

                writer.WritePropertyName(nameof(value.Sum));
                if (value.Sum.HasValue)
                {
                    using (var lazyStringValue = context.GetLazyString(value.Sum.ToInvariantString()))
                        writer.WriteDouble(new LazyNumberValue(lazyStringValue));
                }
                else
                {
                    writer.WriteNull();
                }

                writer.WriteEndObject();
            }
            writer.WriteEndArray();

            writer.WriteEndObject();
        }
예제 #23
0
        public override HttpRequestMessage CreateRequest(JsonOperationContext ctx, ServerNode node, out string url)
        {
            _baseUrl = $"{node.Url}/databases/{node.Database}";
            url      = $"{_baseUrl}/multi_get";

            var aggressiveCacheOptions = _requestExecutor.AggressiveCaching.Value;

            if (aggressiveCacheOptions?.Mode == AggressiveCacheMode.TrackChanges)
            {
                Result = new List <GetResponse>();
                foreach (var command in _commands)
                {
                    if (command.CanCacheAggressively == false)
                    {
                        break;
                    }
                    var cacheKey = GetCacheKey(command, out string _);
                    using (var cachedItem = _cache.Get(ctx, cacheKey, out _, out var cached))
                    {
                        if (cached == null ||
                            cachedItem.Age > aggressiveCacheOptions.Duration ||
                            cachedItem.MightHaveBeenModified)
                        {
                            break;
                        }

                        Result.Add(new GetResponse
                        {
                            Result     = cached,
                            StatusCode = HttpStatusCode.NotModified,
                        });
                    }
                }

                if (Result.Count == _commands.Count)
                {
                    return(null);// aggressively cached
                }
                // not all of it is cached, might as well read it all
                Result = null;
            }

            var request = new HttpRequestMessage
            {
                Method  = HttpMethod.Post,
                Content = new BlittableJsonContent(stream =>
                {
                    using (var writer = new BlittableJsonTextWriter(ctx, stream))
                    {
                        writer.WriteStartObject();

                        var first = true;
                        writer.WritePropertyName("Requests");
                        writer.WriteStartArray();
                        foreach (var command in _commands)
                        {
                            if (first == false)
                            {
                                writer.WriteComma();
                            }
                            first        = false;
                            var cacheKey = GetCacheKey(command, out string _);
                            using (_cache.Get(ctx, cacheKey, out string cachedChangeVector, out var _))
                            {
                                var headers = new Dictionary <string, string>();
                                if (cachedChangeVector != null)
                                {
                                    headers["If-None-Match"] = $"\"{cachedChangeVector}\"";
                                }

                                foreach (var header in command.Headers)
                                {
                                    headers[header.Key] = header.Value;
                                }

                                writer.WriteStartObject();

                                writer.WritePropertyName(nameof(GetRequest.Url));
                                writer.WriteString($"/databases/{node.Database}{command.Url}");
                                writer.WriteComma();

                                writer.WritePropertyName(nameof(GetRequest.Query));
                                writer.WriteString(command.Query);
                                writer.WriteComma();

                                writer.WritePropertyName(nameof(GetRequest.Method));
                                writer.WriteString(command.Method?.Method);
                                writer.WriteComma();

                                writer.WritePropertyName(nameof(GetRequest.Headers));
                                writer.WriteStartObject();

                                var firstInner = true;
                                foreach (var kvp in headers)
                                {
                                    if (firstInner == false)
                                    {
                                        writer.WriteComma();
                                    }

                                    firstInner = false;
                                    writer.WritePropertyName(kvp.Key);
                                    writer.WriteString(kvp.Value);
                                }
                                writer.WriteEndObject();
                                writer.WriteComma();

                                writer.WritePropertyName(nameof(GetRequest.Content));
                                if (command.Content != null)
                                {
                                    command.Content.WriteContent(writer, ctx);
                                }
                                else
                                {
                                    writer.WriteNull();
                                }

                                writer.WriteEndObject();
                            }
                        }
                        writer.WriteEndArray();

                        writer.WriteEndObject();
                    }
                })
            };

            return(request);
        }
예제 #24
0
        public override HttpRequestMessage CreateRequest(JsonOperationContext ctx, ServerNode node, out string url)
        {
            _baseUrl = $"{node.Url}/databases/{node.Database}";

            var request = new HttpRequestMessage
            {
                Method  = HttpMethod.Post,
                Content = new BlittableJsonContent(stream =>
                {
                    using (var writer = new BlittableJsonTextWriter(ctx, stream))
                    {
                        writer.WriteStartObject();

                        var first = true;
                        writer.WritePropertyName("Requests");
                        writer.WriteStartArray();
                        foreach (var command in _commands)
                        {
                            if (first == false)
                            {
                                writer.WriteComma();
                            }

                            first        = false;
                            var cacheKey = GetCacheKey(command, out string _);
                            using (_cache.Get(ctx, cacheKey, out string cachedChangeVector, out var _))
                            {
                                var headers = new Dictionary <string, string>();
                                if (cachedChangeVector != null)
                                {
                                    headers["If-None-Match"] = $"\"{cachedChangeVector}\"";
                                }

                                foreach (var header in command.Headers)
                                {
                                    headers[header.Key] = header.Value;
                                }

                                writer.WriteStartObject();

                                writer.WritePropertyName(nameof(GetRequest.Url));
                                writer.WriteString($"/databases/{node.Database}{command.Url}");
                                writer.WriteComma();

                                writer.WritePropertyName(nameof(GetRequest.Query));
                                writer.WriteString(command.Query);
                                writer.WriteComma();

                                writer.WritePropertyName(nameof(GetRequest.Method));
                                writer.WriteString(command.Method?.Method);
                                writer.WriteComma();

                                writer.WritePropertyName(nameof(GetRequest.Headers));
                                writer.WriteStartObject();

                                var firstInner = true;
                                foreach (var kvp in headers)
                                {
                                    if (firstInner == false)
                                    {
                                        writer.WriteComma();
                                    }

                                    firstInner = false;
                                    writer.WritePropertyName(kvp.Key);
                                    writer.WriteString(kvp.Value);
                                }
                                writer.WriteEndObject();
                                writer.WriteComma();

                                writer.WritePropertyName(nameof(GetRequest.Content));
                                if (command.Content != null)
                                {
                                    command.Content.WriteContent(writer, ctx);
                                }
                                else
                                {
                                    writer.WriteNull();
                                }

                                writer.WriteEndObject();
                            }
                        }
                        writer.WriteEndArray();

                        writer.WriteEndObject();
                    }
                })
            };

            url = $"{_baseUrl}/multi_get";

            return(request);
        }
예제 #25
0
        public async Task PostMultiGet()
        {
            using (ContextPool.AllocateOperationContext(out JsonOperationContext context))
            {
                var input = await context.ReadForMemoryAsync(RequestBodyStream(), "multi_get");

                if (input.TryGet("Requests", out BlittableJsonReaderArray requests) == false)
                {
                    ThrowRequiredPropertyNameInRequest("Requests");
                }

                using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName("Results");
                    writer.WriteStartArray();
                    var resultProperty  = context.GetLazyStringForFieldWithCaching(nameof(GetResponse.Result));
                    var statusProperty  = context.GetLazyStringForFieldWithCaching(nameof(GetResponse.StatusCode));
                    var headersProperty = context.GetLazyStringForFieldWithCaching(nameof(GetResponse.Headers));

                    var features       = new FeatureCollection(HttpContext.Features);
                    var responseStream = new MultiGetHttpResponseStream(ResponseBodyStream());
                    features.Set <IHttpResponseFeature>(new MultiGetHttpResponseFeature(responseStream));
                    var httpContext = new DefaultHttpContext(features);
                    var host        = HttpContext.Request.Host;
                    var scheme      = HttpContext.Request.Scheme;

                    for (int i = 0; i < requests.Length; i++)
                    {
                        var request = (BlittableJsonReaderObject)requests[i];

                        if (i != 0)
                        {
                            writer.WriteComma();
                        }
                        writer.WriteStartObject();

                        if (request.TryGet("Url", out string url) == false || request.TryGet("Query", out string query) == false)
                        {
                            writer.WriteEndObject();
                            continue;
                        }

                        if (request.TryGet("Method", out string method) == false || string.IsNullOrEmpty(method))
                        {
                            method = HttpMethod.Get.Method;
                        }

                        httpContext.Request.Method = method;

                        var routeInformation = Server.Router.GetRoute(method, url, out RouteMatch localMatch);
                        if (routeInformation == null)
                        {
                            writer.WritePropertyName(statusProperty);
                            writer.WriteInteger((int)HttpStatusCode.BadRequest);
                            writer.WritePropertyName(resultProperty);
                            context.Write(writer, new DynamicJsonValue
                            {
                                ["Error"] = $"There is no handler for path: {method} {url}{query}"
                            });
                            writer.WriteEndObject();
                            continue;
                        }

                        var requestHandler = routeInformation.GetRequestHandler();
                        writer.WritePropertyName(resultProperty);
                        writer.Flush();

                        httpContext.Response.StatusCode = 0;
                        httpContext.Request.Headers.Clear();
                        httpContext.Response.Headers.Clear();
                        httpContext.Request.Host        = host;
                        httpContext.Request.Scheme      = scheme;
                        httpContext.Request.QueryString = new QueryString(query);
                        if (request.TryGet("Headers", out BlittableJsonReaderObject headers))
                        {
                            foreach (var header in headers.GetPropertyNames())
                            {
                                if (headers.TryGet(header, out string value) == false)
                                {
                                    continue;
                                }

                                if (string.IsNullOrWhiteSpace(value))
                                {
                                    continue;
                                }

                                httpContext.Request.Headers.Add(header, value);
                            }
                        }

                        if (method == HttpMethod.Post.Method && request.TryGet("Content", out object content))
                        {
                            if (content is LazyStringValue)
                            {
                                var requestBody = GetRequestBody(content.ToString());
                                HttpContext.Response.RegisterForDispose(requestBody);
                                httpContext.Request.Body = requestBody;
                            }
                            else
                            {
                                var requestBody   = new MemoryStream();
                                var contentWriter = new BlittableJsonTextWriter(context, requestBody);
                                context.Write(contentWriter, (BlittableJsonReaderObject)content);
                                contentWriter.Flush();
                                HttpContext.Response.RegisterForDispose(requestBody);
                                httpContext.Request.Body          = requestBody;
                                httpContext.Request.Body.Position = 0;
                            }
                        }

                        var bytesWrittenBeforeRequest = responseStream.BytesWritten;
                        int statusCode;
                        try
                        {
                            await requestHandler(new RequestHandlerContext
                            {
                                Database    = Database,
                                RavenServer = Server,
                                RouteMatch  = localMatch,
                                HttpContext = httpContext
                            });

                            if (bytesWrittenBeforeRequest == responseStream.BytesWritten)
                            {
                                writer.WriteNull();
                            }

                            statusCode = httpContext.Response.StatusCode == 0
                                ? (int)HttpStatusCode.OK
                                : httpContext.Response.StatusCode;
                        }
                        catch (Exception e)
                        {
                            if (bytesWrittenBeforeRequest != responseStream.BytesWritten)
                            {
                                throw;
                            }

                            statusCode = (int)HttpStatusCode.InternalServerError;

                            var djv = new DynamicJsonValue
                            {
                                [nameof(ExceptionDispatcher.ExceptionSchema.Url)]     = $"{url}{query}",
                                [nameof(ExceptionDispatcher.ExceptionSchema.Type)]    = e.GetType().FullName,
                                [nameof(ExceptionDispatcher.ExceptionSchema.Message)] = e.Message,
                                [nameof(ExceptionDispatcher.ExceptionSchema.Error)]   = e.ToString()
                            };

                            using (var json = context.ReadObject(djv, "exception"))
                                writer.WriteObject(json);
                        }

                        writer.WriteComma();
                        writer.WritePropertyName(statusProperty);
                        writer.WriteInteger(statusCode);
                        writer.WriteComma();

                        writer.WritePropertyName(headersProperty);
                        writer.WriteStartObject();
                        bool headerStart = true;
                        foreach (var header in httpContext.Response.Headers)
                        {
                            foreach (var value in header.Value)
                            {
                                if (headerStart == false)
                                {
                                    writer.WriteComma();
                                }
                                headerStart = false;
                                writer.WritePropertyName(header.Key);
                                writer.WriteString(value);
                            }
                        }
                        writer.WriteEndObject();

                        writer.WriteEndObject();
                    }
                    writer.WriteEndArray();
                    writer.WriteEndObject();
                }
            }
        }
예제 #26
0
        public async Task Patch()
        {
            var id = GetQueryStringValueAndAssertIfSingleAndNotEmpty("id");

            var isTest    = GetBoolValueQueryString("test", required: false) ?? false;
            var debugMode = GetBoolValueQueryString("debug", required: false) ?? isTest;
            var skipPatchIfChangeVectorMismatch = GetBoolValueQueryString("skipPatchIfChangeVectorMismatch", required: false) ?? false;

            using (ContextPool.AllocateOperationContext(out DocumentsOperationContext context))
            {
                var request = context.Read(RequestBodyStream(), "ScriptedPatchRequest");
                if (request.TryGet("Patch", out BlittableJsonReaderObject patchCmd) == false || patchCmd == null)
                {
                    throw new ArgumentException("The 'Patch' field in the body request is mandatory");
                }

                var patch = PatchRequest.Parse(patchCmd, out var patchArgs);

                PatchRequest patchIfMissing = null;
                BlittableJsonReaderObject patchIfMissingArgs = null;
                if (request.TryGet("PatchIfMissing", out BlittableJsonReaderObject patchIfMissingCmd) && patchIfMissingCmd != null)
                {
                    patchIfMissing = PatchRequest.Parse(patchIfMissingCmd, out patchIfMissingArgs);
                }

                var changeVector = context.GetLazyString(GetStringFromHeaders("If-Match"));

                var command = new PatchDocumentCommand(context,
                                                       id,
                                                       changeVector,
                                                       skipPatchIfChangeVectorMismatch,
                                                       (patch, patchArgs),
                                                       (patchIfMissing, patchIfMissingArgs),
                                                       Database,
                                                       isTest,
                                                       debugMode,
                                                       true,
                                                       returnDocument: false
                                                       );


                if (isTest == false)
                {
                    await Database.TxMerger.Enqueue(command);
                }
                else
                {
                    // PutDocument requires the write access to the docs storage
                    // testing patching is rare enough not to optimize it
                    using (context.OpenWriteTransaction())
                    {
                        command.Execute(context, null);
                    }
                }

                switch (command.PatchResult.Status)
                {
                case PatchStatus.DocumentDoesNotExist:
                    HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
                    return;

                case PatchStatus.Created:
                    HttpContext.Response.StatusCode = (int)HttpStatusCode.Created;
                    break;

                case PatchStatus.Skipped:
                    HttpContext.Response.StatusCode = (int)HttpStatusCode.NotModified;
                    return;

                case PatchStatus.Patched:
                case PatchStatus.NotModified:
                    HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                using (var writer = new BlittableJsonTextWriter(context, ResponseBodyStream()))
                {
                    writer.WriteStartObject();

                    writer.WritePropertyName(nameof(command.PatchResult.Status));
                    writer.WriteString(command.PatchResult.Status.ToString());
                    writer.WriteComma();

                    writer.WritePropertyName(nameof(command.PatchResult.ModifiedDocument));
                    writer.WriteObject(command.PatchResult.ModifiedDocument);

                    if (debugMode)
                    {
                        writer.WriteComma();
                        writer.WritePropertyName(nameof(command.PatchResult.OriginalDocument));
                        if (isTest)
                        {
                            writer.WriteObject(command.PatchResult.OriginalDocument);
                        }
                        else
                        {
                            writer.WriteNull();
                        }

                        writer.WriteComma();

                        writer.WritePropertyName(nameof(command.PatchResult.Debug));

                        context.Write(writer, new DynamicJsonValue
                        {
                            ["Info"]    = new DynamicJsonArray(command.DebugOutput),
                            ["Actions"] = command.DebugActions
                        });
                    }

                    switch (command.PatchResult.Status)
                    {
                    case PatchStatus.Created:
                    case PatchStatus.Patched:

                        writer.WriteComma();

                        writer.WritePropertyName(nameof(command.PatchResult.LastModified));
                        writer.WriteString(command.PatchResult.LastModified.GetDefaultRavenFormat(isUtc: command.PatchResult.LastModified.Kind == DateTimeKind.Utc));
                        writer.WriteComma();

                        writer.WritePropertyName(nameof(command.PatchResult.ChangeVector));
                        writer.WriteString(command.PatchResult.ChangeVector);
                        writer.WriteComma();

                        writer.WritePropertyName(nameof(command.PatchResult.Collection));
                        writer.WriteString(command.PatchResult.Collection);
                        break;
                    }

                    writer.WriteEndObject();
                }
            }
        }
예제 #27
0
            private void WriteHubPullReplications(List <PullReplicationDefinition> hubPullReplications)
            {
                if (hubPullReplications == null)
                {
                    _writer.WriteNull();
                    return;
                }
                _writer.WriteStartArray();
                var first = true;

                foreach (var pullReplication in hubPullReplications)
                {
                    if (first == false)
                    {
                        _writer.WriteComma();
                    }
                    first = false;

                    _context.Write(_writer, pullReplication.ToJson());
                }
                _writer.WriteEndArray();
            }
예제 #28
0
        public static void WriteIndexQuery(this BlittableJsonTextWriter writer, DocumentConventions conventions, JsonOperationContext context, IndexQuery query)
        {
            writer.WriteStartObject();

            writer.WritePropertyName(nameof(query.Query));
            writer.WriteString(query.Query);
            writer.WriteComma();

            if (query.PageSizeSet && query.PageSize >= 0)
            {
                writer.WritePropertyName(nameof(query.PageSize));
                writer.WriteInteger(query.PageSize);
                writer.WriteComma();
            }

            if (query.WaitForNonStaleResults)
            {
                writer.WritePropertyName(nameof(query.WaitForNonStaleResults));
                writer.WriteBool(query.WaitForNonStaleResults);
                writer.WriteComma();
            }

            if (query.Start > 0)
            {
                writer.WritePropertyName(nameof(query.Start));
                writer.WriteInteger(query.Start);
                writer.WriteComma();
            }

            if (query.WaitForNonStaleResultsTimeout.HasValue)
            {
                writer.WritePropertyName(nameof(query.WaitForNonStaleResultsTimeout));
                writer.WriteString(query.WaitForNonStaleResultsTimeout.Value.ToInvariantString());
                writer.WriteComma();
            }

            if (query.DisableCaching)
            {
                writer.WritePropertyName(nameof(query.DisableCaching));
                writer.WriteBool(query.DisableCaching);
                writer.WriteComma();
            }

#if FEATURE_EXPLAIN_SCORES
            if (query.ExplainScores)
            {
                writer.WritePropertyName(nameof(query.ExplainScores));
                writer.WriteBool(query.ExplainScores);
                writer.WriteComma();
            }
#endif

#if FEATURE_SHOW_TIMINGS
            if (query.ShowTimings)
            {
                writer.WritePropertyName(nameof(query.ShowTimings));
                writer.WriteBool(query.ShowTimings);
                writer.WriteComma();
            }
#endif

            if (query.SkipDuplicateChecking)
            {
                writer.WritePropertyName(nameof(query.SkipDuplicateChecking));
                writer.WriteBool(query.SkipDuplicateChecking);
                writer.WriteComma();
            }

            writer.WritePropertyName(nameof(query.QueryParameters));
            if (query.QueryParameters != null)
            {
                writer.WriteObject(EntityToBlittable.ConvertCommandToBlittable(query.QueryParameters, context));
            }
            else
            {
                writer.WriteNull();
            }

            writer.WriteEndObject();
        }
예제 #29
0
        private async Task HandleRequestAsync(
            BlittableJsonReaderObject request,
            JsonOperationContext context,
            MultiGetHttpResponseStream responseStream,
            BlittableJsonTextWriter writer,
            HttpContext httpContext,
            HostString host,
            string scheme,
            LazyStringValue resultProperty,
            LazyStringValue statusProperty,
            LazyStringValue headersProperty,
            StringBuilder trafficWatchStringBuilder)
        {
            writer.WriteStartObject();

            if (request.TryGet(nameof(GetRequest.Url), out string url) == false || request.TryGet(nameof(GetRequest.Query), out string query) == false)
            {
                writer.WriteEndObject();
                return;
            }

            if (request.TryGet(nameof(GetRequest.Method), out string method) == false || string.IsNullOrEmpty(method))
            {
                method = HttpMethod.Get.Method;
            }

            httpContext.Request.Method = method;

            var routeInformation = Server.Router.GetRoute(method, url, out RouteMatch localMatch);

            if (routeInformation == null)
            {
                HandleNoRoute(context, writer, method, url, query, statusProperty, resultProperty);
                return;
            }

            var requestHandler = routeInformation.GetRequestHandler();

            writer.WritePropertyName(resultProperty);
            writer.Flush();

            PrepareHttpContext(request, context, httpContext, method, query, host, scheme, trafficWatchStringBuilder, out var content);

            var bytesWrittenBeforeRequest = responseStream.BytesWritten;
            int statusCode;

            try
            {
                if (Server.Configuration.Security.AuthenticationEnabled == false ||
                    Server.Router.TryAuthorize(routeInformation, httpContext, Database, out var status))
                {
                    await requestHandler(new RequestHandlerContext
                    {
                        Database    = Database,
                        RavenServer = Server,
                        RouteMatch  = localMatch,
                        HttpContext = httpContext
                    });
                }

                if (bytesWrittenBeforeRequest == responseStream.BytesWritten)
                {
                    writer.WriteNull();
                }

                statusCode = httpContext.Response.StatusCode == 0
                    ? (int)HttpStatusCode.OK
                    : httpContext.Response.StatusCode;
            }
            catch (Exception e)
            {
                if (bytesWrittenBeforeRequest != responseStream.BytesWritten)
                {
                    throw;
                }

                statusCode = (int)HttpStatusCode.InternalServerError;

                HandleException(context, writer, e, url, query);
            }

            writer.WriteComma();

            writer.WritePropertyName(statusProperty);
            writer.WriteInteger(statusCode);

            writer.WriteComma();

            WriteHeaders(writer, httpContext, headersProperty);

            writer.WriteEndObject();

            trafficWatchStringBuilder?.Append(content).AppendLine();
        }