public void UpdateStatusWhenOperationFails( [Values(true, false)] bool async, [Values(true, false)] bool useDefaultException) { RequestFailedException originalException = new RequestFailedException(""); MockResponse mockResponse = new MockResponse(200); TestOperation testOperation = new TestOperation() { OnUpdateState = _ => useDefaultException ? OperationState <int> .Failure(mockResponse) : OperationState <int> .Failure(mockResponse, originalException) }; MockOperationInternal <int> operationInternal = testOperation.MockOperationInternal; RequestFailedException thrownException = async ? Assert.ThrowsAsync <RequestFailedException>(async() => await operationInternal.UpdateStatusAsync(CancellationToken.None)) : Assert.Throws <RequestFailedException>(() => operationInternal.UpdateStatus(CancellationToken.None)); if (!useDefaultException) { Assert.AreEqual(originalException, thrownException); } Assert.AreEqual(mockResponse, operationInternal.RawResponse); Assert.True(operationInternal.HasCompleted); Assert.False(operationInternal.HasValue); RequestFailedException valueException = Assert.Throws <RequestFailedException>(() => _ = operationInternal.Value); Assert.AreEqual(thrownException, valueException); }
public async Task UpdateStatusSetsFailedScopeWhenOperationFails(bool async) { using ClientDiagnosticListener testListener = new ClientDiagnosticListener(DiagnosticNamespace); RequestFailedException originalException = new RequestFailedException(""); MockResponse mockResponse = new MockResponse(200); TestOperation testOperation = new TestOperation() { OnUpdateState = _ => OperationState <int> .Failure(mockResponse, originalException) }; MockOperationInternal <int> operationInternal = testOperation.MockOperationInternal; try { _ = async ? await operationInternal.UpdateStatusAsync(CancellationToken.None) : operationInternal.UpdateStatus(CancellationToken.None); } catch { } testListener.AssertScopeException($"{nameof(TestOperation)}.UpdateStatus", (Exception scopeException) => { Assert.AreEqual(originalException, scopeException); }); }
async ValueTask <OperationState <CustomFormModel> > IOperation <CustomFormModel> .UpdateStateAsync(bool async, CancellationToken cancellationToken) { // Include keys is always set to true -- the service does not have a use case for includeKeys: false. Response <Model> response = async ? await _serviceClient.GetCustomModelAsync(new Guid(Id), includeKeys : true, cancellationToken).ConfigureAwait(false) : _serviceClient.GetCustomModel(new Guid(Id), includeKeys: true, cancellationToken); CustomFormModelStatus status = response.Value.ModelInfo.Status; Response rawResponse = response.GetRawResponse(); if (status == CustomFormModelStatus.Ready) { return(OperationState <CustomFormModel> .Success(rawResponse, new CustomFormModel(response.Value, _serviceVersion))); } else if (status == CustomFormModelStatus.Invalid) { RequestFailedException requestFailedException = await ClientCommon.CreateExceptionForFailedOperationAsync( async, _diagnostics, rawResponse, response.Value.TrainResult.Errors, $"Invalid model created with ID {response.Value.ModelInfo.ModelId}").ConfigureAwait(false); return(OperationState <CustomFormModel> .Failure(rawResponse, requestFailedException)); } return(OperationState <CustomFormModel> .Pending(rawResponse)); }
/// <summary> /// Calls the server to get updated status of the long-running operation. /// </summary> /// <param name="async">When <c>true</c>, the method will be executed asynchronously; otherwise, it will execute synchronously.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> used for the service call.</param> /// <returns>The HTTP response received from the server.</returns> async ValueTask <OperationState <AsyncPageable <DocumentStatusResult> > > IOperation <AsyncPageable <DocumentStatusResult> > .UpdateStateAsync(bool async, CancellationToken cancellationToken) { var update = async ? await _serviceClient.GetTranslationStatusAsync(new Guid(Id), cancellationToken).ConfigureAwait(false) : _serviceClient.GetTranslationStatus(new Guid(Id), cancellationToken); _createdOn = update.Value.CreatedOn; _lastModified = update.Value.LastModified; _status = update.Value.Status; _documentsTotal = update.Value.DocumentsTotal; _documentsFailed = update.Value.DocumentsFailed; _documentsInProgress = update.Value.DocumentsInProgress; _documentsSucceeded = update.Value.DocumentsSucceeded; _documentsNotStarted = update.Value.DocumentsNotStarted; _documentsCanceled = update.Value.DocumentsCanceled; Response rawResponse = update.GetRawResponse(); if (update.Value.Status == DocumentTranslationStatus.Succeeded || update.Value.Status == DocumentTranslationStatus.Failed) { return(OperationState <AsyncPageable <DocumentStatusResult> > .Success(rawResponse, CreateOperationValueAsync(CancellationToken.None))); } else if (update.Value.Status == DocumentTranslationStatus.ValidationFailed) { RequestFailedException requestFailedException = _diagnostics.CreateRequestFailedException(rawResponse, update.Value.Error, CreateAdditionalInformation(update.Value.Error)); return(OperationState <AsyncPageable <DocumentStatusResult> > .Failure(rawResponse, requestFailedException)); } return(OperationState <AsyncPageable <DocumentStatusResult> > .Pending(rawResponse)); }
async ValueTask <OperationState <CustomFormModelInfo> > IOperation <CustomFormModelInfo> .UpdateStateAsync(bool async, CancellationToken cancellationToken) { Response <CopyOperationResult> response = async ? await _serviceClient.GetCustomModelCopyResultAsync(new Guid(_modelId), new Guid(_resultId), cancellationToken).ConfigureAwait(false) : _serviceClient.GetCustomModelCopyResult(new Guid(_modelId), new Guid(_resultId), cancellationToken); OperationStatus status = response.Value.Status; Response rawResponse = response.GetRawResponse(); if (status == OperationStatus.Succeeded) { return(OperationState <CustomFormModelInfo> .Success(rawResponse, ConvertValue(response.Value, _targetModelId, CustomFormModelStatus.Ready))); } else if (status == OperationStatus.Failed) { RequestFailedException requestFailedException = await ClientCommon .CreateExceptionForFailedOperationAsync(async, _diagnostics, rawResponse, response.Value.CopyResult.Errors) .ConfigureAwait(false); return(OperationState <CustomFormModelInfo> .Failure(rawResponse, requestFailedException)); } return(OperationState <CustomFormModelInfo> .Pending(rawResponse)); }
public TestOperation( UpdateResult result, Func <MockResponse> responseFactory, string operationTypeName = null, IEnumerable <KeyValuePair <string, string> > scopeAttributes = null, int?callsToComplete = null) { MockOperationInternal = new MockOperationInternal(ClientDiagnostics, this, responseFactory, operationTypeName, scopeAttributes); MockOperationInternal.CallsToComplete = callsToComplete; OnUpdateState = result switch { UpdateResult.Pending => _ => { return(MockOperationInternal.CallsToComplete.HasValue && MockOperationInternal.UpdateStatusCallCount >= MockOperationInternal.CallsToComplete.Value ? OperationState.Success(responseFactory()) : OperationState.Pending(responseFactory())); }, UpdateResult.Failure => _ => OperationState.Failure(responseFactory()), UpdateResult.FailureCustomException => _ => OperationState.Failure(responseFactory(), originalException), UpdateResult.Success => _ => OperationState.Success(responseFactory()), UpdateResult.Throw => _ => throw customException, _ => null }; }
async ValueTask <OperationState> IOperation.UpdateStateAsync(bool async, CancellationToken cancellationToken) { var statusResponse = async ? await _client.GetTransactionStatusAsync( Id, new RequestContext { CancellationToken = cancellationToken, ErrorOptions = ErrorOptions.NoThrow }) .ConfigureAwait(false) : _client.GetTransactionStatus(Id, new RequestContext { CancellationToken = cancellationToken, ErrorOptions = ErrorOptions.NoThrow }); _operationInternal.RawResponse = statusResponse; if (statusResponse.Status != (int)HttpStatusCode.OK) { var error = new ResponseError(null, exceptionMessage); var ex = async ? await _client.ClientDiagnostics.CreateRequestFailedExceptionAsync(statusResponse, error).ConfigureAwait(false) : _client.ClientDiagnostics.CreateRequestFailedException(statusResponse, error); return(OperationState.Failure(GetRawResponse(), new RequestFailedException(exceptionMessage, ex))); } string status = JsonDocument.Parse(statusResponse.Content) .RootElement .GetProperty("state") .GetString(); if (status != "Pending") { return(OperationState.Success(statusResponse)); } return(OperationState.Pending(statusResponse)); }
async ValueTask <OperationState <AnalyzeResult> > IOperation <AnalyzeResult> .UpdateStateAsync(bool async, CancellationToken cancellationToken) { Response <AnalyzeResultOperation> response = async ? await _serviceClient.DocumentAnalysisGetAnalyzeDocumentResultAsync(_modelId, _resultId, cancellationToken).ConfigureAwait(false) : _serviceClient.DocumentAnalysisGetAnalyzeDocumentResult(_modelId, _resultId, cancellationToken); AnalyzeResultOperationStatus status = response.Value.Status; Response rawResponse = response.GetRawResponse(); if (status == AnalyzeResultOperationStatus.Succeeded) { return(OperationState <AnalyzeResult> .Success(rawResponse, response.Value.AnalyzeResult)); } else if (status == AnalyzeResultOperationStatus.Failed) { RequestFailedException requestFailedException = await ClientCommon .CreateExceptionForFailedOperationAsync(async, _diagnostics, rawResponse, response.Value.Error) .ConfigureAwait(false); return(OperationState <AnalyzeResult> .Failure(rawResponse, requestFailedException)); } return(OperationState <AnalyzeResult> .Pending(rawResponse)); }
async ValueTask <OperationState <RecognizedFormCollection> > IOperation <RecognizedFormCollection> .UpdateStateAsync(bool async, CancellationToken cancellationToken) { Response <AnalyzeOperationResult> response = async ? await _serviceClient.GetAnalyzeBusinessCardResultAsync(new Guid(Id), cancellationToken).ConfigureAwait(false) : _serviceClient.GetAnalyzeBusinessCardResult(new Guid(Id), cancellationToken); OperationStatus status = response.Value.Status; Response rawResponse = response.GetRawResponse(); if (status == OperationStatus.Succeeded) { return(OperationState <RecognizedFormCollection> .Success(rawResponse, ClientCommon.ConvertPrebuiltOutputToRecognizedForms(response.Value.AnalyzeResult))); } else if (status == OperationStatus.Failed) { RequestFailedException requestFailedException = await ClientCommon .CreateExceptionForFailedOperationAsync(async, _diagnostics, rawResponse, response.Value.AnalyzeResult.Errors) .ConfigureAwait(false); return(OperationState <RecognizedFormCollection> .Failure(rawResponse, requestFailedException)); } return(OperationState <RecognizedFormCollection> .Pending(rawResponse)); }
async ValueTask <OperationState <DocumentModel> > IOperation <DocumentModel> .UpdateStateAsync(bool async, CancellationToken cancellationToken) { Response <ModelOperation> response = async ? await _serviceClient.GetOperationAsync(Id, cancellationToken).ConfigureAwait(false) : _serviceClient.GetOperation(Id, cancellationToken); DocumentOperationStatus status = response.Value.Status; Response rawResponse = response.GetRawResponse(); _percentCompleted = response.Value.PercentCompleted ?? 0; if (status == DocumentOperationStatus.Succeeded) { return(OperationState <DocumentModel> .Success(rawResponse, response.Value.Result)); } else if (status == DocumentOperationStatus.Failed) { RequestFailedException requestFailedException = await ClientCommon .CreateExceptionForFailedOperationAsync(async, _diagnostics, rawResponse, response.Value.Error) .ConfigureAwait(false); return(OperationState <DocumentModel> .Failure(rawResponse, requestFailedException)); } else if (status == DocumentOperationStatus.Canceled) { return(OperationState <DocumentModel> .Failure(rawResponse, new RequestFailedException("The operation was canceled so no value is available."))); } return(OperationState <DocumentModel> .Pending(rawResponse)); }
public void FailureProperties() { RequestFailedException expectedException = new RequestFailedException(""); MockResponse mockResponse = new MockResponse(200); OperationState <int> state = OperationState <int> .Failure(mockResponse, expectedException); Assert.True(state.HasCompleted); Assert.False(state.HasSucceeded); Assert.AreEqual(mockResponse, state.RawResponse); Assert.AreEqual(default(int), state.Value); Assert.AreEqual(expectedException, state.OperationFailedException); }
async ValueTask <OperationState <AsyncPageable <AnalyzeActionsResult> > > IOperation <AsyncPageable <AnalyzeActionsResult> > .UpdateStateAsync(bool async, CancellationToken cancellationToken) { Response <AnalyzeTextJobStatusResult> response = async ? await _serviceClient.AnalyzeStatusAsync(_jobId, _showStats, null, null, _idToIndexMap, cancellationToken).ConfigureAwait(false) : _serviceClient.AnalyzeStatus(_jobId, _showStats, null, null, _idToIndexMap, cancellationToken); _displayName = response.Value.DisplayName; _createdOn = response.Value.CreatedOn; _expiresOn = response.Value.ExpiresOn; _lastModified = response.Value.LastModifiedOn; _status = response.Value.Status; _actionsFailed = response.Value.ActionsFailed; _actionsInProgress = response.Value.AcionsInProgress; _actionSucceeded = response.Value.AcionsSucceeded; _actionsTotal = response.Value.ActionsTotal; Response rawResponse = response.GetRawResponse(); if (response.Value.Status == TextAnalyticsOperationStatus.Failed) { if (CheckIfGenericError(response.Value)) { RequestFailedException requestFailedException; if (async) { requestFailedException = await ClientCommon.CreateExceptionForFailedOperationAsync(true, _diagnostics, rawResponse, response.Value.Errors).ConfigureAwait(false); } else { requestFailedException = ClientCommon.CreateExceptionForFailedOperationAsync(false, _diagnostics, rawResponse, response.Value.Errors).EnsureCompleted(); } return(OperationState <AsyncPageable <AnalyzeActionsResult> > .Failure(rawResponse, requestFailedException)); } } if (response.Value.Status == TextAnalyticsOperationStatus.Succeeded || response.Value.Status == TextAnalyticsOperationStatus.Failed) { string nextLink = response.Value.NextLink; _firstPage = Page.FromValues(new List <AnalyzeActionsResult>() { response.Value.Result }, nextLink, rawResponse); return(OperationState <AsyncPageable <AnalyzeActionsResult> > .Success(rawResponse, CreateOperationValueAsync(CancellationToken.None))); } return(OperationState <AsyncPageable <AnalyzeActionsResult> > .Pending(rawResponse)); }
public async ValueTask<OperationState<VoidValue>> UpdateStateAsync(bool async, CancellationToken cancellationToken) { var state = await _operation.UpdateStateAsync(async, cancellationToken).ConfigureAwait(false); if (!state.HasCompleted) { return OperationState<VoidValue>.Pending(state.RawResponse); } if (state.HasSucceeded) { return OperationState<VoidValue>.Success(state.RawResponse, new VoidValue()); } return OperationState<VoidValue>.Failure(state.RawResponse, state.OperationFailedException); }
async ValueTask <OperationState <AsyncPageable <AnalyzeActionsResult> > > IOperation <AsyncPageable <AnalyzeActionsResult> > .UpdateStateAsync(bool async, CancellationToken cancellationToken) { Response <AnalyzeJobState> response = async ? await _serviceClient.AnalyzeStatusAsync(Id, _showStats, null, null, cancellationToken).ConfigureAwait(false) : _serviceClient.AnalyzeStatus(Id, _showStats, null, null, cancellationToken); // Add lock to avoid race condition? _displayName = response.Value.DisplayName; _createdOn = response.Value.CreatedDateTime; _expiresOn = response.Value.ExpirationDateTime; _lastModified = response.Value.LastUpdateDateTime; _status = response.Value.Status; _actionsFailed = response.Value.Tasks.Failed; _actionsInProgress = response.Value.Tasks.InProgress; _actionSucceeded = response.Value.Tasks.Completed; _actionsTotal = response.Value.Tasks.Total; Response rawResponse = response.GetRawResponse(); if (response.Value.Status == TextAnalyticsOperationStatus.Failed) { if (CheckIfGenericError(response.Value)) { RequestFailedException requestFailedException = await ClientCommon.CreateExceptionForFailedOperationAsync(async, _diagnostics, rawResponse, response.Value.Errors).ConfigureAwait(false); return(OperationState <AsyncPageable <AnalyzeActionsResult> > .Failure(rawResponse, requestFailedException)); } } if (response.Value.Status == TextAnalyticsOperationStatus.Succeeded || response.Value.Status == TextAnalyticsOperationStatus.Failed) { string nextLink = response.Value.NextLink; AnalyzeActionsResult value = Transforms.ConvertToAnalyzeActionsResult(response.Value, _idToIndexMap); _firstPage = Page.FromValues(new List <AnalyzeActionsResult>() { value }, nextLink, rawResponse); return(OperationState <AsyncPageable <AnalyzeActionsResult> > .Success(rawResponse, CreateOperationValueAsync(CancellationToken.None))); } return(OperationState <AsyncPageable <AnalyzeActionsResult> > .Pending(rawResponse)); }
async ValueTask <OperationState <AsyncPageable <AnalyzeHealthcareEntitiesResultCollection> > > IOperation <AsyncPageable <AnalyzeHealthcareEntitiesResultCollection> > .UpdateStateAsync(bool async, CancellationToken cancellationToken) { Response <HealthcareJobState> response = async ? await _serviceClient.HealthStatusAsync(new Guid(_jobId), null, null, _showStats, cancellationToken).ConfigureAwait(false) : _serviceClient.HealthStatus(new Guid(_jobId), null, null, _showStats, cancellationToken); // Add lock to avoid race condition? _status = response.Value.Status; _createdOn = response.Value.CreatedDateTime; _expiresOn = response.Value.ExpirationDateTime; _lastModified = response.Value.LastUpdateDateTime; Response rawResponse = response.GetRawResponse(); if (response.Value.Status == TextAnalyticsOperationStatus.Succeeded) { string nextLink = response.Value.NextLink; AnalyzeHealthcareEntitiesResultCollection value = Transforms.ConvertToAnalyzeHealthcareEntitiesResultCollection(response.Value.Results, _idToIndexMap); _firstPage = Page.FromValues(new List <AnalyzeHealthcareEntitiesResultCollection>() { value }, nextLink, rawResponse); return(OperationState <AsyncPageable <AnalyzeHealthcareEntitiesResultCollection> > .Success(rawResponse, CreateOperationValueAsync(CancellationToken.None))); } else if (response.Value.Status == TextAnalyticsOperationStatus.Failed) { RequestFailedException requestFailedException = await ClientCommon .CreateExceptionForFailedOperationAsync(async, _diagnostics, rawResponse, response.Value.Errors) .ConfigureAwait(false); return(OperationState <AsyncPageable <AnalyzeHealthcareEntitiesResultCollection> > .Failure(rawResponse, requestFailedException)); } else if (response.Value.Status == TextAnalyticsOperationStatus.Cancelled) { return(OperationState <AsyncPageable <AnalyzeHealthcareEntitiesResultCollection> > .Failure(rawResponse, new RequestFailedException("The operation was canceled so no value is available."))); } return(OperationState <AsyncPageable <AnalyzeHealthcareEntitiesResultCollection> > .Pending(rawResponse)); }
async ValueTask <OperationState> IOperation.UpdateStateAsync(bool async, CancellationToken cancellationToken) { Response response = async ? await _pipeline.GetResponseAsync(RequestMethod.Get, cancellationToken, SecretClient.SecretsPath, _value.Name, "/", _value.Version).ConfigureAwait(false) : _pipeline.GetResponse(RequestMethod.Get, cancellationToken, SecretClient.SecretsPath, _value.Name, "/", _value.Version); switch (response.Status) { case 200: case 403: // Access denied but proof the secret was recovered. return(OperationState.Success(response)); case 404: return(OperationState.Pending(response)); default: RequestFailedException ex = async ? await _pipeline.Diagnostics.CreateRequestFailedExceptionAsync(response).ConfigureAwait(false) : _pipeline.Diagnostics.CreateRequestFailedException(response); return(OperationState.Failure(response, ex)); } }
public void FailureThrowsIfRawResponseIsNull() => Assert.Throws <ArgumentNullException>(() => OperationState <int> .Failure(null, new RequestFailedException("")));