コード例 #1
0
        internal override async Task <ContainerProperties> GetCachedContainerPropertiesAsync(
            string containerUri,
            CancellationToken cancellationToken)
        {
            this.ThrowIfDisposed();
            CosmosDiagnosticsContext diagnosticsContext = CosmosDiagnosticsContextCore.Create(requestOptions: null);

            using (diagnosticsContext.GetOverallScope())
            {
                ClientCollectionCache collectionCache = await this.DocumentClient.GetCollectionCacheAsync();

                try
                {
                    using (diagnosticsContext.CreateScope("ContainerCache.ResolveByNameAsync"))
                    {
                        return(await collectionCache.ResolveByNameAsync(
                                   HttpConstants.Versions.CurrentVersion,
                                   containerUri,
                                   cancellationToken));
                    }
                }
                catch (DocumentClientException ex)
                {
                    throw CosmosExceptionFactory.Create(ex, diagnosticsContext);
                }
            }
        }
コード例 #2
0
        private static QueryResponseCore CreateFromExceptionWithStackTrace(ExceptionWithStackTraceException exceptionWithStackTrace)
        {
            // Use the original stack trace from the inner exception.
            if (exceptionWithStackTrace.InnerException is DocumentClientException ||
                exceptionWithStackTrace.InnerException is CosmosException)
            {
                return(QueryResponseFactory.CreateFromException(exceptionWithStackTrace.InnerException));
            }

            QueryResponseCore queryResponseCore = QueryResponseFactory.CreateFromException(exceptionWithStackTrace.InnerException);
            CosmosException   cosmosException   = queryResponseCore.CosmosException;

            queryResponseCore = QueryResponseCore.CreateFailure(
                statusCode: queryResponseCore.StatusCode,
                subStatusCodes: queryResponseCore.SubStatusCode,
                cosmosException: CosmosExceptionFactory.Create(
                    statusCode: cosmosException.StatusCode,
                    message: cosmosException.Message,
                    stackTrace: exceptionWithStackTrace.StackTrace,
                    headers: cosmosException.Headers,
                    trace: cosmosException.Trace,
                    error: cosmosException.Error,
                    innerException: cosmosException.InnerException),
                requestCharge: queryResponseCore.RequestCharge,
                activityId: queryResponseCore.ActivityId);

            return(queryResponseCore);
        }
コード例 #3
0
        private static bool TryCreateFromExceptionWithStackTrace(
            ExceptionWithStackTraceException exceptionWithStackTrace,
            ITrace trace,
            out CosmosException cosmosException)
        {
            // Use the original stack trace from the inner exception.
            if (exceptionWithStackTrace.InnerException is Microsoft.Azure.Documents.DocumentClientException ||
                exceptionWithStackTrace.InnerException is CosmosException)
            {
                return(ExceptionToCosmosException.TryCreateFromException(
                           exceptionWithStackTrace.InnerException,
                           trace,
                           out cosmosException));
            }

            if (!ExceptionToCosmosException.TryCreateFromException(
                    exceptionWithStackTrace.InnerException,
                    trace,
                    out cosmosException))
            {
                return(false);
            }

            cosmosException = CosmosExceptionFactory.Create(
                cosmosException.StatusCode,
                cosmosException.Message,
                exceptionWithStackTrace.StackTrace,
                headers: cosmosException.Headers,
                cosmosException.Trace,
                cosmosException.Error,
                cosmosException.InnerException);
            return(true);
        }
コード例 #4
0
        internal override async Task <ContainerProperties> GetCachedContainerPropertiesAsync(
            string containerUri,
            ITrace trace,
            CancellationToken cancellationToken)
        {
            using (ITrace childTrace = trace.StartChild("Get Container Properties", TraceComponent.Transport, Tracing.TraceLevel.Info))
            {
                this.ThrowIfDisposed();
                CosmosDiagnosticsContext diagnosticsContext = CosmosDiagnosticsContextCore.Create(requestOptions: null);
                using (diagnosticsContext.GetOverallScope())
                {
                    ClientCollectionCache collectionCache = await this.DocumentClient.GetCollectionCacheAsync();

                    try
                    {
                        using (diagnosticsContext.CreateScope("ContainerCache.ResolveByNameAsync"))
                        {
                            return(await collectionCache.ResolveByNameAsync(
                                       HttpConstants.Versions.CurrentVersion,
                                       containerUri,
                                       forceRefesh : false,
                                       cancellationToken));
                        }
                    }
                    catch (DocumentClientException ex)
                    {
                        throw CosmosExceptionFactory.Create(ex, diagnosticsContext);
                    }
                }
            }
        }
        public async Task <(bool isSuccess, Exception error)> TryCheckpointAsync()
        {
            try
            {
                await this.checkpointer.CheckpointPartitionAsync(this.responseMessage.Headers.ContinuationToken);

                return(isSuccess : true, error : null);
            }
            catch (LeaseLostException leaseLostException)
            {
                // LeaseLost means another instance stole the lease due to load balancing, so the right status is 412
                CosmosException cosmosException = CosmosExceptionFactory.Create(
                    statusCode: HttpStatusCode.PreconditionFailed,
                    message: "Lease was lost due to load balancing and will be processed by another instance",
                    stackTrace: leaseLostException.StackTrace,
                    headers: new Headers(),
                    trace: NoOpTrace.Singleton,
                    error: null,
                    innerException: leaseLostException);
                return(isSuccess : false, error : cosmosException);
            }
            catch (Exception exception)
            {
                return(isSuccess : false, error : exception);
            }
        }
コード例 #6
0
        internal override async Task <ContainerProperties> GetCachedContainerPropertiesAsync(
            string containerUri,
            ITrace trace,
            CancellationToken cancellationToken)
        {
            using (ITrace childTrace = trace.StartChild("Get Container Properties", TraceComponent.Transport, Tracing.TraceLevel.Info))
            {
                this.ThrowIfDisposed();
                ClientCollectionCache collectionCache = await this.DocumentClient.GetCollectionCacheAsync(childTrace);

                try
                {
                    return(await collectionCache.ResolveByNameAsync(
                               HttpConstants.Versions.CurrentVersion,
                               containerUri,
                               forceRefesh : false,
                               trace : childTrace,
                               clientSideRequestStatistics : null,
                               cancellationToken : cancellationToken));
                }
                catch (DocumentClientException ex)
                {
                    throw CosmosExceptionFactory.Create(ex, childTrace);
                }
            }
        }
コード例 #7
0
        private static CosmosException CreateFromDocumentClientException(Microsoft.Azure.Documents.DocumentClientException documentClientException)
        {
            CosmosException cosmosException = CosmosExceptionFactory.Create(
                documentClientException,
                null);

            return(cosmosException);
        }
コード例 #8
0
        internal static ResponseMessage ToCosmosResponseMessage(this DocumentClientException documentClientException, RequestMessage requestMessage)
        {
            CosmosDiagnosticsContext diagnosticsContext = requestMessage?.DiagnosticsContext;

            if (requestMessage != null)
            {
                diagnosticsContext = requestMessage.DiagnosticsContext;

                if (diagnosticsContext == null)
                {
                    throw new ArgumentNullException("Request message should contain a DiagnosticsContext");
                }
            }
            else
            {
                diagnosticsContext = new CosmosDiagnosticsContextCore();
            }

            CosmosException cosmosException = CosmosExceptionFactory.Create(
                documentClientException,
                diagnosticsContext);

            PointOperationStatistics pointOperationStatistics = new PointOperationStatistics(
                activityId: cosmosException.Headers.ActivityId,
                statusCode: cosmosException.StatusCode,
                subStatusCode: (int)SubStatusCodes.Unknown,
                responseTimeUtc: DateTime.UtcNow,
                requestCharge: cosmosException.Headers.RequestCharge,
                errorMessage: documentClientException.ToString(),
                method: requestMessage?.Method,
                requestUri: requestMessage?.RequestUriString,
                requestSessionToken: requestMessage?.Headers?.Session,
                responseSessionToken: cosmosException.Headers.Session);

            diagnosticsContext.AddDiagnosticsInternal(pointOperationStatistics);

            // if StatusCode is null it is a client business logic error and it never hit the backend, so throw
            if (documentClientException.StatusCode == null)
            {
                throw cosmosException;
            }

            // if there is a status code then it came from the backend, return error as http error instead of throwing the exception
            ResponseMessage responseMessage = cosmosException.ToCosmosResponseMessage(requestMessage);

            if (requestMessage != null)
            {
                requestMessage.Properties.Remove(nameof(DocumentClientException));
                requestMessage.Properties.Add(nameof(DocumentClientException), documentClientException);
            }

            return(responseMessage);
        }
コード例 #9
0
        private static QueryResponseCore CreateFromDocumentClientException(Microsoft.Azure.Documents.DocumentClientException documentClientException)
        {
            CosmosException cosmosException = CosmosExceptionFactory.Create(
                documentClientException,
                null);

            QueryResponseCore queryResponseCore = QueryResponseCore.CreateFailure(
                statusCode: documentClientException.StatusCode.GetValueOrDefault(System.Net.HttpStatusCode.InternalServerError),
                subStatusCodes: null,
                cosmosException: cosmosException,
                requestCharge: 0,
                activityId: documentClientException.ActivityId);

            return(queryResponseCore);
        }
コード例 #10
0
        /// <summary>
        /// Gets the container's Properties by using the internal cache.
        /// In case the cache does not have information about this container, it may end up making a server call to fetch the data.
        /// </summary>
        /// <param name="cancellationToken"><see cref="CancellationToken"/> representing request cancellation.</param>
        /// <returns>A <see cref="Task"/> containing the <see cref="ContainerProperties"/> for this container.</returns>
        internal override async Task <ContainerProperties> GetCachedContainerPropertiesAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            ClientCollectionCache collectionCache = await this.ClientContext.DocumentClient.GetCollectionCacheAsync();

            try
            {
                return(await collectionCache.ResolveByNameAsync(HttpConstants.Versions.CurrentVersion, this.LinkUri.OriginalString, cancellationToken));
            }
            catch (DocumentClientException ex)
            {
                throw CosmosExceptionFactory.Create(
                          dce: ex,
                          diagnosticsContext: null);
            }
        }
コード例 #11
0
        internal static ResponseMessage ToCosmosResponseMessage(this DocumentServiceResponse documentServiceResponse, RequestMessage requestMessage)
        {
            Debug.Assert(requestMessage != null, nameof(requestMessage));
            Headers headers = documentServiceResponse.Headers.ToCosmosHeaders();

            // Only record point operation stats if ClientSideRequestStats did not record the response.
            CosmosClientSideRequestStatistics clientSideRequestStatistics = documentServiceResponse.RequestStats as CosmosClientSideRequestStatistics;

            if (clientSideRequestStatistics == null ||
                (clientSideRequestStatistics.ContactedReplicas.Count == 0 && clientSideRequestStatistics.FailedReplicas.Count == 0))
            {
                requestMessage.DiagnosticsContext.AddDiagnosticsInternal(new PointOperationStatistics(
                                                                             activityId: headers.ActivityId,
                                                                             responseTimeUtc: DateTime.UtcNow,
                                                                             statusCode: documentServiceResponse.StatusCode,
                                                                             subStatusCode: documentServiceResponse.SubStatusCode,
                                                                             requestCharge: headers.RequestCharge,
                                                                             errorMessage: null,
                                                                             method: requestMessage?.Method,
                                                                             requestUri: requestMessage?.RequestUri,
                                                                             requestSessionToken: requestMessage?.Headers?.Session,
                                                                             responseSessionToken: headers.Session));
            }

            // If it's considered a failure create the corresponding CosmosException
            if (!documentServiceResponse.StatusCode.IsSuccess())
            {
                CosmosException cosmosException = CosmosExceptionFactory.Create(
                    documentServiceResponse,
                    headers,
                    requestMessage);

                return(cosmosException.ToCosmosResponseMessage(requestMessage));
            }

            ResponseMessage responseMessage = new ResponseMessage(
                statusCode: documentServiceResponse.StatusCode,
                requestMessage: requestMessage,
                headers: headers,
                cosmosException: null,
                diagnostics: requestMessage.DiagnosticsContext)
            {
                Content = documentServiceResponse.ResponseBody
            };

            return(responseMessage);
        }
コード例 #12
0
        private static CosmosException CreateFromExceptionWithStackTrace(ExceptionWithStackTraceException exceptionWithStackTrace)
        {
            // Use the original stack trace from the inner exception.
            if (exceptionWithStackTrace.InnerException is Microsoft.Azure.Documents.DocumentClientException ||
                exceptionWithStackTrace.InnerException is CosmosException)
            {
                return(ExceptionToCosmosException.CreateFromException(exceptionWithStackTrace.InnerException));
            }

            CosmosException cosmosException = ExceptionToCosmosException.CreateFromException(exceptionWithStackTrace.InnerException);

            return(CosmosExceptionFactory.Create(
                       cosmosException.StatusCode,
                       cosmosException.Message,
                       exceptionWithStackTrace.StackTrace,
                       headers: cosmosException.Headers,
                       cosmosException.Trace,
                       cosmosException.Error,
                       cosmosException.InnerException));
        }
コード例 #13
0
        private void HandleFailedRequest(
            ResponseMessage responseMessage,
            string lastContinuation)
        {
            DocDbError docDbError = ExceptionClassifier.ClassifyStatusCodes(responseMessage.StatusCode, (int)responseMessage.Headers.SubStatusCode);

            switch (docDbError)
            {
            case DocDbError.PartitionSplit:
                throw new FeedRangeGoneException("Partition split.", lastContinuation);

            case DocDbError.Undefined:
                throw CosmosExceptionFactory.Create(responseMessage);

            default:
                DefaultTrace.TraceCritical($"Unrecognized DocDbError enum value {docDbError}");
                Debug.Fail($"Unrecognized DocDbError enum value {docDbError}");
                throw new InvalidOperationException($"Unrecognized DocDbError enum value {docDbError} for status code {responseMessage.StatusCode} and substatus code {responseMessage.Headers.SubStatusCode}");
            }
        }
コード例 #14
0
        internal override async Task <List <Documents.Routing.Range <string> > > GetEffectiveRangesAsync(
            IRoutingMapProvider routingMapProvider,
            string containerRid,
            Documents.PartitionKeyDefinition partitionKeyDefinition,
            ITrace trace)
        {
            Documents.PartitionKeyRange pkRange = await routingMapProvider.TryGetPartitionKeyRangeByIdAsync(
                collectionResourceId : containerRid,
                partitionKeyRangeId : this.PartitionKeyRangeId,
                trace : trace,
                forceRefresh : false);

            if (pkRange == null)
            {
                // Try with a refresh
                pkRange = await routingMapProvider.TryGetPartitionKeyRangeByIdAsync(
                    collectionResourceId : containerRid,
                    partitionKeyRangeId : this.PartitionKeyRangeId,
                    trace : trace,
                    forceRefresh : true);
            }

            if (pkRange == null)
            {
                throw CosmosExceptionFactory.Create(
                          statusCode: HttpStatusCode.Gone,
                          message: $"The PartitionKeyRangeId: \"{this.PartitionKeyRangeId}\" is not valid for the current container {containerRid} .",
                          stackTrace: string.Empty,
                          headers: new Headers()
                {
                    SubStatusCode = SubStatusCodes.PartitionKeyRangeGone,
                },
                          error: null,
                          innerException: null,
                          trace: NoOpTrace.Singleton);
            }

            return(new List <Documents.Routing.Range <string> > {
                pkRange.ToRange()
            });
        }
コード例 #15
0
        /// <summary>
        /// Gets the container's Properties by using the internal cache.
        /// In case the cache does not have information about this container, it may end up making a server call to fetch the data.
        /// </summary>
        /// <param name="forceRefresh">Forces the cache to refresh</param>
        /// <param name="cancellationToken"><see cref="CancellationToken"/> representing request cancellation.</param>
        /// <returns>A <see cref="Task"/> containing the <see cref="ContainerProperties"/> for this container.</returns>
        public override async Task <ContainerProperties> GetCachedContainerPropertiesAsync(
            bool forceRefresh = false,
            CancellationToken cancellationToken = default)
        {
            try
            {
                ClientCollectionCache collectionCache = await this.ClientContext.DocumentClient.GetCollectionCacheAsync();

                return(await collectionCache.ResolveByNameAsync(
                           HttpConstants.Versions.CurrentVersion,
                           this.LinkUri,
                           forceRefresh,
                           cancellationToken));
            }
            catch (DocumentClientException ex)
            {
                throw CosmosExceptionFactory.Create(
                          dce: ex,
                          diagnosticsContext: null);
            }
        }
コード例 #16
0
        internal static ResponseMessage ToCosmosResponseMessage(this StoreResponse storeResponse, RequestMessage requestMessage)
        {
            // If it's considered a failure create the corresponding CosmosException
            if (!storeResponse.StatusCode.IsSuccess())
            {
                CosmosException cosmosException = CosmosExceptionFactory.Create(
                    storeResponse,
                    requestMessage);

                return(cosmosException.ToCosmosResponseMessage(requestMessage));
            }

            // Is status code conversion lossy?
            ResponseMessage responseMessage = new ResponseMessage((HttpStatusCode)storeResponse.Status, requestMessage);

            if (storeResponse.ResponseBody != null)
            {
                responseMessage.Content = storeResponse.ResponseBody;
            }

            return(responseMessage);
        }
コード例 #17
0
        public override async Task <List <Documents.Routing.Range <string> > > GetEffectiveRangesAsync(
            IRoutingMapProvider routingMapProvider,
            string containerRid,
            Documents.PartitionKeyDefinition partitionKeyDefinition)
        {
            Documents.PartitionKeyRange pkRange = await routingMapProvider.TryGetPartitionKeyRangeByIdAsync(
                collectionResourceId : containerRid,
                partitionKeyRangeId : this.PartitionKeyRangeId,
                forceRefresh : false);

            if (pkRange == null)
            {
                // Try with a refresh
                pkRange = await routingMapProvider.TryGetPartitionKeyRangeByIdAsync(
                    collectionResourceId : containerRid,
                    partitionKeyRangeId : this.PartitionKeyRangeId,
                    forceRefresh : true);
            }

            if (pkRange == null)
            {
                throw CosmosExceptionFactory.Create(
                          statusCode: HttpStatusCode.Gone,
                          subStatusCode: (int)SubStatusCodes.PartitionKeyRangeGone,
                          message: $"The PartitionKeyRangeId: \"{this.PartitionKeyRangeId}\" is not valid for the current container {containerRid} .",
                          stackTrace: string.Empty,
                          activityId: string.Empty,
                          requestCharge: 0,
                          retryAfter: null,
                          headers: null,
                          diagnosticsContext: null,
                          error: null,
                          innerException: null);
            }

            return(new List <Documents.Routing.Range <string> > {
                pkRange.ToRange()
            });
        }
コード例 #18
0
        /// <summary>
        /// Create a <see cref="ResponseMessage"/>
        /// </summary>
        /// <param name="statusCode">The HttpStatusCode of the response</param>
        /// <param name="requestMessage">The <see cref="Cosmos.RequestMessage"/> object</param>
        /// <param name="errorMessage">The reason for failures if any.</param>
        public ResponseMessage(
            HttpStatusCode statusCode,
            RequestMessage requestMessage = null,
            string errorMessage           = null)
        {
            if ((statusCode < 0) || ((int)statusCode > 999))
            {
                throw new ArgumentOutOfRangeException(nameof(statusCode));
            }

            this.StatusCode     = statusCode;
            this.RequestMessage = requestMessage;
            this.Headers        = new Headers();
            this.Trace          = requestMessage?.Trace ?? NoOpTrace.Singleton;

            if (!string.IsNullOrEmpty(errorMessage))
            {
                this.CosmosException = CosmosExceptionFactory.Create(
                    statusCode,
                    requestMessage,
                    errorMessage);
            }
        }
コード例 #19
0
        /// <summary>
        /// Create a <see cref="ResponseMessage"/>
        /// </summary>
        /// <param name="statusCode">The HttpStatusCode of the response</param>
        /// <param name="requestMessage">The <see cref="Cosmos.RequestMessage"/> object</param>
        /// <param name="errorMessage">The reason for failures if any.</param>
        public ResponseMessage(
            HttpStatusCode statusCode,
            RequestMessage requestMessage = null,
            string errorMessage           = null)
        {
            if ((statusCode < 0) || ((int)statusCode > 999))
            {
                throw new ArgumentOutOfRangeException(nameof(statusCode));
            }

            this.StatusCode         = statusCode;
            this.RequestMessage     = requestMessage;
            this.Headers            = new Headers();
            this.DiagnosticsContext = requestMessage?.DiagnosticsContext ?? new CosmosDiagnosticsContextCore();

            if (!string.IsNullOrEmpty(errorMessage))
            {
                this.CosmosException = CosmosExceptionFactory.Create(
                    statusCode,
                    requestMessage,
                    errorMessage);
            }
        }
コード例 #20
0
        /// <summary>
        /// Gets the container's Properties by using the internal cache.
        /// In case the cache does not have information about this container, it may end up making a server call to fetch the data.
        /// </summary>
        /// <param name="forceRefresh">Forces the cache to refresh</param>
        /// <param name="trace">The trace.</param>
        /// <param name="cancellationToken"><see cref="CancellationToken"/> representing request cancellation.</param>
        /// <returns>A <see cref="Task"/> containing the <see cref="ContainerProperties"/> for this container.</returns>
        public override async Task <ContainerProperties> GetCachedContainerPropertiesAsync(
            bool forceRefresh,
            ITrace trace,
            CancellationToken cancellationToken)
        {
            try
            {
                ClientCollectionCache collectionCache = await this.ClientContext.DocumentClient.GetCollectionCacheAsync(trace);

                return(await collectionCache.ResolveByNameAsync(
                           HttpConstants.Versions.CurrentVersion,
                           this.LinkUri,
                           forceRefresh,
                           trace : trace,
                           clientSideRequestStatistics : null,
                           cancellationToken : cancellationToken));
            }
            catch (DocumentClientException ex)
            {
                throw CosmosExceptionFactory.Create(
                          dce: ex,
                          trace: trace);
            }
        }