コード例 #1
0
        /// <inheritdoc/>
        public virtual async Task <bool?> RequestPredictionsAsync(IEnumerable <string> commands, string requestId, CancellationToken cancellationToken)
        {
            Validation.CheckArgument(commands, $"{nameof(commands)} cannot be null.");

            var  localCommands = string.Join(AzPredictorConstants.CommandConcatenator, commands);
            bool isRequestSent = false;

            try
            {
                if (string.Equals(localCommands, _commandToRequestPrediction, StringComparison.OrdinalIgnoreCase))
                {
                    // It's the same history we've already requested the prediction for last time, skip it.
                    return(null);
                }

                if (!commands.Any())
                {
                    return(null);
                }

                // We have a check to avoid sending the request using the same commands. So we only check if it's cancelled
                // here. We don't cancel the request once we set _commandToRequestPrediction to localCommands.
                cancellationToken.ThrowIfCancellationRequested();
                cancellationToken = CancellationToken.None;
                SetCommandToRequestPrediction(localCommands);

                AzPredictorService.SetHttpRequestHeader(_client?.DefaultRequestHeaders, _azContext.HashUserId, requestId);

                var requestContext = new PredictionRequestBody.RequestContext()
                {
                    VersionNumber = this._azContext.AzVersion
                };

                var requestBody = new PredictionRequestBody(commands)
                {
                    Context = requestContext,
                };

                var requestBodyString   = JsonSerializer.Serialize(requestBody, JsonUtilities.DefaultSerializerOptions);
                var httpResponseMessage = await _client.PostAsync(_predictionsEndpoint, new StringContent(requestBodyString, Encoding.UTF8, "application/json"), cancellationToken);

                isRequestSent = true;

                httpResponseMessage.EnsureSuccessStatusCode();
                var reply = await httpResponseMessage.Content.ReadAsStreamAsync(cancellationToken);

                var suggestionsList = await JsonSerializer.DeserializeAsync <IList <PredictiveCommand> >(reply, JsonUtilities.DefaultSerializerOptions);

                SetCommandBasedPreditor(localCommands, suggestionsList);
            }
            catch (Exception e) when(!(e is OperationCanceledException))
            {
                throw new ServiceRequestException(e.Message, e)
                      {
                          IsRequestSent = isRequestSent
                      };
            }

            return(isRequestSent);
        }
コード例 #2
0
        /// <inheritdoc/>
        public virtual void RequestPredictions(IEnumerable <string> commands)
        {
            AzPredictorService.ReplaceThrottleUserIdToHeader(this._client?.DefaultRequestHeaders, this._azContext.UserId);
            var localCommands = string.Join(AzPredictorConstants.CommandConcatenator, commands);

            this._telemetryClient.OnRequestPrediction(localCommands);

            if (string.Equals(localCommands, this._commandForPrediction, StringComparison.Ordinal))
            {
                // It's the same history we've already requested the prediction for last time, skip it.
                return;
            }
            else
            {
                this.SetPredictionCommand(localCommands);

                // When it's called multiple times, we only need to keep the one for the latest command.

                this._predictionRequestCancellationSource?.Cancel();
                this._predictionRequestCancellationSource = new CancellationTokenSource();

                var cancellationToken = this._predictionRequestCancellationSource.Token;

                // We don't need to block on the task. We send the HTTP request and update prediction list at the background.
                Task.Run(async() => {
                    try
                    {
                        var requestContext = new PredictionRequestBody.RequestContext()
                        {
                            SessionId     = this._telemetryClient.SessionId,
                            CorrelationId = this._telemetryClient.CorrelationId,
                        };
                        var requestBody = new PredictionRequestBody(localCommands)
                        {
                            Context = requestContext,
                        };

                        var requestBodyString   = JsonConvert.SerializeObject(requestBody);
                        var httpResponseMessage = await _client.PostAsync(this._predictionsEndpoint, new StringContent(requestBodyString, Encoding.UTF8, "application/json"), cancellationToken);

                        var reply           = await httpResponseMessage.Content.ReadAsStringAsync(cancellationToken);
                        var suggestionsList = JsonConvert.DeserializeObject <List <string> >(reply);

                        this.SetSuggestionPredictor(localCommands, suggestionsList);
                    }
                    catch (Exception e) when(!(e is OperationCanceledException))
                    {
                        this._telemetryClient.OnRequestPredictionError(localCommands, e);
                    }
                },
                         cancellationToken);
            }
        }
コード例 #3
0
        /// <inheritdoc/>
        public virtual void RequestPredictions(IEnumerable <string> commands)
        {
            Validation.CheckArgument(commands, $"{nameof(commands)} cannot be null.");

            var       localCommands    = string.Join(AzPredictorConstants.CommandConcatenator, commands);
            bool      postSuccess      = false;
            Exception exception        = null;
            bool      startRequestTask = false;

            try
            {
                if (string.Equals(localCommands, _commandToRequestPrediction, StringComparison.Ordinal))
                {
                    // It's the same history we've already requested the prediction for last time, skip it.
                    return;
                }

                if (commands.Any())
                {
                    SetCommandToRequestPrediction(localCommands);

                    // When it's called multiple times, we only need to keep the one for the latest command.

                    _predictionRequestCancellationSource?.Cancel();
                    _predictionRequestCancellationSource = new CancellationTokenSource();

                    var cancellationToken = _predictionRequestCancellationSource.Token;

                    // We don't need to block on the task. We send the HTTP request and update prediction list at the background.
                    startRequestTask = true;
                    Task.Run(async() => {
                        try
                        {
                            AzPredictorService.SetHttpRequestHeader(_client?.DefaultRequestHeaders, _azContext.UserId, _telemetryClient.CorrelationId);

                            var requestContext = new PredictionRequestBody.RequestContext()
                            {
                                VersionNumber = this._azContext.AzVersion
                            };

                            var requestBody = new PredictionRequestBody(commands)
                            {
                                Context = requestContext,
                            };

                            var requestBodyString   = JsonSerializer.Serialize(requestBody, JsonUtilities.DefaultSerializerOptions);
                            var httpResponseMessage = await _client.PostAsync(_predictionsEndpoint, new StringContent(requestBodyString, Encoding.UTF8, "application/json"), cancellationToken);
                            postSuccess             = true;

                            httpResponseMessage.EnsureSuccessStatusCode();
                            var reply           = await httpResponseMessage.Content.ReadAsStreamAsync(cancellationToken);
                            var suggestionsList = await JsonSerializer.DeserializeAsync <IList <PredictiveCommand> >(reply, JsonUtilities.DefaultSerializerOptions);

                            SetCommandBasedPreditor(localCommands, suggestionsList);
                        }
                        catch (Exception e) when(!(e is OperationCanceledException))
                        {
                            exception = e;
                        }
                        finally
                        {
                            _telemetryClient.OnRequestPrediction(new RequestPredictionTelemetryData(localCommands, postSuccess, exception));
                        }
                    },
                             cancellationToken);
                }
            }
            catch (Exception e)
            {
                exception = e;
            }
            finally
            {
                if (!startRequestTask)
                {
                    _telemetryClient.OnRequestPrediction(new RequestPredictionTelemetryData(localCommands, hasSentHttpRequest: false, exception: exception));
                }
            }
        }