From 2239ac99f895ae9e376c6800a9b317c016ae1f83 Mon Sep 17 00:00:00 2001 From: devinleighsmith <41091511+devinleighsmith@users.noreply.github.com> Date: Tue, 18 Jun 2024 13:45:30 -0700 Subject: [PATCH] psp-5563 prevent psp-8114 changes from overriding service level error handling. (#4121) --- source/backend/api/Pims.Api.csproj | 6 +- .../Repositories/Mayan/MayanBaseRepository.cs | 1 - .../Mayan/MayanDocumentRepository.cs | 167 ++++-------------- .../backend/api/Services/DocumentService.cs | 96 +++++++--- .../unit/api/Services/DocumentServiceTest.cs | 5 +- source/frontend/package.json | 2 +- 6 files changed, 115 insertions(+), 162 deletions(-) diff --git a/source/backend/api/Pims.Api.csproj b/source/backend/api/Pims.Api.csproj index c8d3cb6413..cc7638f6ed 100644 --- a/source/backend/api/Pims.Api.csproj +++ b/source/backend/api/Pims.Api.csproj @@ -2,9 +2,9 @@ 0ef6255f-9ea0-49ec-8c65-c172304b4926 - 5.3.2-81.35 - 5.3.2-81.35 - 5.3.2.81 + 5.3.3-81.35 + 5.3.3-81.35 + 5.3.3.81 true 16BC0468-78F6-4C91-87DA-7403C919E646 net8.0 diff --git a/source/backend/api/Repositories/Mayan/MayanBaseRepository.cs b/source/backend/api/Repositories/Mayan/MayanBaseRepository.cs index 127e47ee4b..4b7dfca7c9 100644 --- a/source/backend/api/Repositories/Mayan/MayanBaseRepository.cs +++ b/source/backend/api/Repositories/Mayan/MayanBaseRepository.cs @@ -13,7 +13,6 @@ namespace Pims.Api.Repositories.Mayan /// public abstract class MayanBaseRepository : BaseRestRepository { - protected const string MayanGenericErrorMessage = "Error response received from Mayan Document Service"; protected readonly MayanConfig _config; private const string MayanConfigSectionKey = "Mayan"; diff --git a/source/backend/api/Repositories/Mayan/MayanDocumentRepository.cs b/source/backend/api/Repositories/Mayan/MayanDocumentRepository.cs index 8f8ea7a403..a628b39a5f 100644 --- a/source/backend/api/Repositories/Mayan/MayanDocumentRepository.cs +++ b/source/backend/api/Repositories/Mayan/MayanDocumentRepository.cs @@ -16,7 +16,6 @@ using Pims.Api.Models.Mayan.Document; using Pims.Api.Models.Mayan.Metadata; using Pims.Api.Models.Requests.Http; -using Pims.Core.Exceptions; namespace Pims.Api.Repositories.Mayan { @@ -47,7 +46,7 @@ public MayanDocumentRepository( public async Task> TryCreateDocumentTypeAsync(DocumentTypeModel documentType) { - _logger.LogDebug("Creating document type..."); + _logger.LogDebug("Creating document type {documentType}...", documentType); string authenticationToken = await _authRepository.GetTokenAsync(); string serializedDocumentType = JsonSerializer.Serialize(documentType, SerializerOptions); @@ -57,19 +56,14 @@ public async Task> TryCreateDocumentTypeAsyn Uri endpoint = new($"{_config.BaseUri}/document_types/"); var response = await PostAsync(endpoint, content, authenticationToken); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Error while Creating document type"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug($"Finished creating a document type"); + _logger.LogDebug($"Finished creating a document type {documentType} ", documentType); return response; } public async Task> TryUpdateDocumentTypeAsync(DocumentTypeModel documentType) { - _logger.LogDebug("Updating document type..."); + _logger.LogDebug("Updating document type {documentType}...", documentType); string authenticationToken = await _authRepository.GetTokenAsync(); string serializedDocumentType = JsonSerializer.Serialize(documentType, SerializerOptions); @@ -80,29 +74,19 @@ public async Task> TryUpdateDocumentTypeAsyn var response = await PutAsync(endpoint, content, authenticationToken); - if (response.Status == ExternalResponseStatus.Error) - { - ThrowMayanResponseError(response.Message); - _logger.LogDebug($"Finished updating a document type"); - } return response; } public async Task> TryDeleteDocumentTypeAsync(long documentTypeId) { - _logger.LogDebug("Deleting document type..."); + _logger.LogDebug("Deleting document type {documentTypeId}...", documentTypeId); string authenticationToken = await _authRepository.GetTokenAsync(); Uri endpoint = new($"{this._config.BaseUri}/document_types/{documentTypeId}/"); var response = await DeleteAsync(endpoint, authenticationToken); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Error while Deleting document type"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug($"Finished deleting document type"); + _logger.LogDebug($"Finished deleting document type {documentTypeId}", documentTypeId); return response; } @@ -117,11 +101,6 @@ public async Task>> TryGetDocu string authenticationToken = await _authRepository.GetTokenAsync(); ExternalResponse> response = await GetAsync>(endpoint, authenticationToken).ConfigureAwait(true); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Error while Retrieving document types"); - ThrowMayanResponseError(response.Message); - } _logger.LogDebug("Finished retrieving document types"); return response; @@ -129,7 +108,7 @@ public async Task>> TryGetDocu public async Task>> TryGetDocumentTypeMetadataTypesAsync(long documentTypeId, string ordering = "", int? page = null, int? pageSize = null) { - _logger.LogDebug("Retrieving document type metadata types..."); + _logger.LogDebug("Retrieving document type metadata types {documentTypeId}...", documentTypeId); string authenticationToken = await _authRepository.GetTokenAsync(); var queryParams = GenerateQueryParams(ordering, page, pageSize); @@ -137,13 +116,8 @@ public async Task> string endpointString = $"{this._config.BaseUri}/document_types/{documentTypeId}/metadata_types/"; Uri endpoint = new(QueryHelpers.AddQueryString(endpointString, queryParams)); var response = await GetAsync>(endpoint, authenticationToken).ConfigureAwait(true); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Error while Retrieving document type metadata types"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug("Finished retrieving document type's metadata types"); + _logger.LogDebug("Finished retrieving document type's metadata types {documentTypeId}", documentTypeId); return response; } @@ -158,11 +132,6 @@ public async Task>> TryGetDo string endpointString = $"{_config.BaseUri}/documents/"; Uri endpoint = new(QueryHelpers.AddQueryString(endpointString, queryParams)); var response = await GetAsync>(endpoint, authenticationToken).ConfigureAwait(true); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Error while Retrieving document list"); - ThrowMayanResponseError(response.Message); - } _logger.LogDebug("Finished retrieving document list"); return response; @@ -170,25 +139,20 @@ public async Task>> TryGetDo public async Task> TryGetDocumentAsync(long documentId) { - _logger.LogDebug("Retrieving document..."); + _logger.LogDebug("Retrieving document {documentId}...", documentId); string authenticationToken = await _authRepository.GetTokenAsync(); Uri endpoint = new($"{this._config.BaseUri}/documents/{documentId}/"); var response = await GetAsync(endpoint, authenticationToken).ConfigureAwait(true); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Error while Retrieving document"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug("Finished retrieving document"); + _logger.LogDebug("Finished retrieving document {documentId}", documentId); return response; } public async Task>> TryGetDocumentMetadataAsync(long documentId, string ordering = "", int? page = null, int? pageSize = null) { - _logger.LogDebug("Retrieving document metadata..."); + _logger.LogDebug("Retrieving document metadata {documentId}...", documentId); string authenticationToken = await _authRepository.GetTokenAsync(); @@ -197,19 +161,15 @@ public async Task>> TryGet string endpointString = $"{_config.BaseUri}/documents/{documentId}/metadata/"; Uri endpoint = new(QueryHelpers.AddQueryString(endpointString, queryParams)); var response = await GetAsync>(endpoint, authenticationToken).ConfigureAwait(true); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Error while Retrieving document metadata"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug("Finished retrieving document metadata"); + + _logger.LogDebug("Finished retrieving document metadata {documentId}", documentId); return response; } public async Task> TryDownloadFileAsync(long documentId, long fileId) { - _logger.LogDebug("Downloading file..."); + _logger.LogDebug("Downloading file {documentId}, {fileId}...", documentId, fileId); string authenticationToken = await _authRepository.GetTokenAsync(); using HttpClient client = _httpClientFactory.CreateClient("Pims.Api.Logging"); @@ -225,14 +185,9 @@ public async Task> TryDownloadFileAsync(l try { Uri endpoint = new($"{this._config.BaseUri}/documents/{documentId}/files/{fileId}/download/"); - HttpResponseMessage httppResponse = await client.GetAsync(endpoint).ConfigureAwait(true); + HttpResponseMessage httpResponse = await client.GetAsync(endpoint).ConfigureAwait(true); - var response = await ProcessDownloadResponse(httppResponse); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Error while Downloading file"); - ThrowMayanResponseError(response.Message); - } + var response = await ProcessDownloadResponse(httpResponse); return response; } @@ -249,27 +204,21 @@ public async Task> TryDownloadFileAsync(l public async Task> TryDeleteDocument(long documentId) { - _logger.LogDebug("Deleting document..."); - _logger.LogTrace("Document id {documentId}", documentId); + _logger.LogDebug("Deleting document {documentId}...", documentId); string authenticationToken = await _authRepository.GetTokenAsync(); Uri endpoint = new($"{this._config.BaseUri}/documents/{documentId}/"); var response = await DeleteAsync(endpoint, authenticationToken); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Error while Deleting document"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug($"Finished deleting document"); + _logger.LogDebug($"Finished deleting document {documentId}", documentId); return response; } public async Task> TryUploadDocumentAsync(long documentType, IFormFile file) { - _logger.LogDebug("Uploading document..."); + _logger.LogDebug("Uploading document {documentType}...", documentType); string authenticationToken = await _authRepository.GetTokenAsync(); byte[] fileData; @@ -287,13 +236,8 @@ public async Task> TryUploadDocumentAsync( Uri endpoint = new($"{_config.BaseUri}/documents/upload/"); ExternalResponse response = await PostAsync(endpoint, multiContent, authenticationToken); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug($"Error while updating a file"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug($"Finished uploading file"); + _logger.LogDebug($"Finished uploading file of type {documentType}", documentType); return response; } @@ -308,11 +252,6 @@ public async Task>> TryGetMeta Uri endpoint = new(QueryHelpers.AddQueryString(endpointString, queryParams)); var response = await GetAsync>(endpoint, authenticationToken); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug($"Error while Retrieving metadata types"); - ThrowMayanResponseError(response.Message); - } _logger.LogDebug("Finished retrieving metadata types"); return response; @@ -320,7 +259,7 @@ public async Task>> TryGetMeta public async Task> TryCreateDocumentTypeMetadataTypeAsync(long documentTypeId, long metadataTypeId, bool isRequired) { - _logger.LogDebug("Creating document type's metadata type..."); + _logger.LogDebug("Creating document type's metadata type {documentTypeId}, {metadataTypeId}, {isRequired}...", documentTypeId, metadataTypeId, isRequired); string authenticationToken = await _authRepository.GetTokenAsync(); @@ -331,19 +270,14 @@ public async Task> TryCreateDocu Uri endpoint = new($"{this._config.BaseUri}/document_types/{documentTypeId}/metadata_types/"); var response = await PostAsync(endpoint, content, authenticationToken); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug($"Error while Creating document type's metadata type"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug($"Finished creating document type's metadata type"); + _logger.LogDebug($"Finished creating document type's metadata type {documentTypeId}, {metadataTypeId}, {isRequired}...", documentTypeId, metadataTypeId, isRequired); return response; } public async Task> TryCreateDocumentMetadataAsync(long documentId, long metadataTypeId, string value) { - _logger.LogDebug("Add existing metadata type with value to an existing document"); + _logger.LogDebug("Add existing metadata type with value to an existing document {documentId}, {metadataTypeId}, {value}", documentId, metadataTypeId, value); string authenticationToken = await _authRepository.GetTokenAsync(); @@ -354,19 +288,14 @@ public async Task> TryCreateDocumentMeta Uri endpoint = new($"{this._config.BaseUri}/documents/{documentId}/metadata/"); var response = await PostAsync(endpoint, content, authenticationToken); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Add existing metadata type with value"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug($"Finished adding existing metadata value to a document"); + _logger.LogDebug($"Finished adding existing metadata value to a document, {documentId}, {metadataTypeId}, {value}", documentId, metadataTypeId, value); return response; } public async Task> TryUpdateDocumentMetadataAsync(long documentId, long metadataId, string value) { - _logger.LogDebug("Update existing metadata type with value to an existing document"); + _logger.LogDebug("Update existing metadata type with value to an existing document {documentId}, {metadataId}, {value}", documentId, metadataId, value); string authenticationToken = await _authRepository.GetTokenAsync(); @@ -377,37 +306,27 @@ public async Task> TryUpdateDocumentMeta Uri endpoint = new($"{this._config.BaseUri}/documents/{documentId}/metadata/{metadataId}/"); var response = await PutAsync(endpoint, content, authenticationToken); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Update existing metadata type"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug($"Finished updating existing metadata value to a document"); + _logger.LogDebug($"Finished updating existing metadata value to a document {documentId}, {metadataId}, {value}", documentId, metadataId, value); return response; } public async Task> TryDeleteDocumentMetadataAsync(long documentId, long metadataId) { - _logger.LogDebug("Delete existing metadata type from an existing document"); + _logger.LogDebug("Delete existing metadata type from an existing document {documentId} {metadataId}", documentId, metadataId); string authenticationToken = await _authRepository.GetTokenAsync(); Uri endpoint = new($"{this._config.BaseUri}/documents/{documentId}/metadata/{metadataId}/"); var response = await DeleteAsync(endpoint, authenticationToken); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Delete existing metadata type"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug($"Finished deleting existing metadata from a document"); + _logger.LogDebug($"Finished deleting existing metadata from a document {documentId}, {metadataId}", documentId, metadataId); return response; } public async Task> TryUpdateDocumentTypeMetadataTypeAsync(long documentTypeId, long documentTypeMetadataTypeId, bool isRequired) { - _logger.LogDebug("Updating document type and metadata type..."); + _logger.LogDebug("Updating document type and metadata type {documentTypeId} {documentTypeMetadataTypeId} {isRequired}...", documentTypeId, documentTypeMetadataTypeId, isRequired); string authenticationToken = await _authRepository.GetTokenAsync(); @@ -418,45 +337,35 @@ public async Task> TryUpdateDocu Uri endpoint = new($"{this._config.BaseUri}/document_types/{documentTypeId}/metadata_types/{documentTypeMetadataTypeId}/"); var response = await PutAsync(endpoint, form, authenticationToken); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Updating document type and metadata type"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug($"Finished update document type with a metadata type"); + _logger.LogDebug($"Finished update document type with a metadata type {documentTypeId} {documentTypeMetadataTypeId} {isRequired}", documentTypeId, documentTypeMetadataTypeId, isRequired); return response; } public async Task> TryDeleteDocumentTypeMetadataTypeAsync(long documentTypeId, long documentTypeMetadataTypeId) { - _logger.LogDebug("Deleting document type's metadata type..."); + _logger.LogDebug("Deleting document type's metadata {documentTypeId} {documentTypeMetadataTypeId}...", documentTypeId, documentTypeMetadataTypeId); string authenticationToken = await _authRepository.GetTokenAsync(); Uri endpoint = new($"{this._config.BaseUri}/document_types/{documentTypeId}/metadata_types/{documentTypeMetadataTypeId}/"); var response = await DeleteAsync(endpoint, authenticationToken); - if (response.Status == ExternalResponseStatus.Error) - { - _logger.LogDebug("Deleting document type's metadata type"); - ThrowMayanResponseError(response.Message); - } - _logger.LogDebug($"Finished deleting document type's metadata type"); + _logger.LogDebug($"Finished deleting document type's metadata type {documentTypeId} {documentTypeMetadataTypeId}", documentTypeId, documentTypeMetadataTypeId); return response; } public async Task>> TryGetFilePageListAsync(long documentId, long documentFileId, int pageSize, int pageNumber) { - _logger.LogDebug("Retrieving page list for mayan file..."); + _logger.LogDebug("Retrieving page list for mayan file {documentId} {documentFileId}...", documentId, documentFileId); string authenticationToken = await _authRepository.GetTokenAsync(); Uri endpoint = new($"{_config.BaseUri}/documents/{documentId}/files/{documentFileId}/pages/?page_size={pageSize}&page={pageNumber}"); var response = await GetAsync>(endpoint, authenticationToken); - _logger.LogDebug("Finished retrieving mayan file pages"); + _logger.LogDebug("Finished retrieving mayan file pages {documentId} {documentFileId}", documentId, documentFileId); return response; } @@ -472,15 +381,5 @@ public async Task TryGetFilePageImage(long documentId, long _logger.LogDebug("Finished retrieving mayan file page"); return response; } - - private void ThrowMayanResponseError(string errorMesage) - { - if(_config.ExposeErrors) - { - throw new MayanRepositoryException(errorMesage); - } - - throw new MayanRepositoryException(MayanGenericErrorMessage); - } } } diff --git a/source/backend/api/Services/DocumentService.cs b/source/backend/api/Services/DocumentService.cs index e93a9df06e..18a0fc5d17 100644 --- a/source/backend/api/Services/DocumentService.cs +++ b/source/backend/api/Services/DocumentService.cs @@ -22,6 +22,7 @@ using Pims.Api.Models.Requests.Http; using Pims.Api.Repositories.Mayan; using Pims.Av; +using Pims.Core.Exceptions; using Pims.Core.Http.Configuration; using Pims.Dal.Entities; using Pims.Dal.Helpers.Extensions; @@ -36,7 +37,7 @@ namespace Pims.Api.Services /// public class DocumentService : BaseService, IDocumentService { - + protected const string MayanGenericErrorMessage = "Error response received from Mayan Document Service"; private static readonly string[] ValidExtensions = { "txt", @@ -198,19 +199,23 @@ public async Task UploadDocumentAsync(DocumentUploadRequ response.Document = mapper.Map(newPimsDocument); } + else + { + throw GetMayanResponseError(externalResponse.Message); + } return response; } public async Task UpdateDocumentAsync(DocumentUpdateRequest updateRequest) { - this.Logger.LogInformation("Updating document"); + this.Logger.LogInformation("Updating document {documentId}", updateRequest.DocumentId); this.User.ThrowIfNotAuthorized(Permissions.DocumentEdit); // update the pims document status PimsDocument existingDocument = documentRepository.TryGet(updateRequest.DocumentId); if (existingDocument == null) { - throw new BadRequestException("Document Id not found."); + throw new BadRequestException($"Document Id {updateRequest.DocumentId} not found."); } existingDocument.DocumentStatusTypeCode = updateRequest.DocumentStatusCode; documentRepository.Update(existingDocument); @@ -282,7 +287,9 @@ public async Task UpdateDocumentAsync(DocumentUpdateRequ } else { - this.Logger.LogError("Metadata & Status for Document with id {id} update aborted", updateRequest.DocumentId); + string error = $"Metadata & Status for Document with id {updateRequest.DocumentId} update aborted. {existingMetadata.Message}"; + this.Logger.LogError(error); + throw GetMayanResponseError(error); } return response; @@ -290,7 +297,7 @@ public async Task UpdateDocumentAsync(DocumentUpdateRequ public async Task> DeleteDocumentAsync(PimsDocument document) { - this.Logger.LogInformation("Deleting document"); + this.Logger.LogInformation("Deleting document {documentId}", document.Internal_Id); this.User.ThrowIfNotAuthorized(Permissions.DocumentDelete); // If the storage deletion was successful or the id was not found on the storage (already deleted) delete the pims reference. @@ -300,6 +307,10 @@ public async Task> DeleteDocumentAsync(PimsDocument doc documentRepository.Delete(document); documentRepository.CommitTransaction(); } + else + { + throw GetMayanResponseError(result.Message); + } return result; } @@ -310,6 +321,10 @@ public async Task> DeleteDocumentAsync(PimsDocument doc this.User.ThrowIfNotAuthorizedOrServiceAccount(Permissions.DocumentView, keycloakOptions); ExternalResponse> result = await documentStorageRepository.TryGetDocumentTypesAsync(ordering, page, pageSize); + if (result.Status != ExternalResponseStatus.Success) + { + throw GetMayanResponseError(result.Message); + } return result; } @@ -319,41 +334,64 @@ public async Task>> GetStora this.User.ThrowIfNotAuthorized(Permissions.DocumentView); ExternalResponse> result = await documentStorageRepository.TryGetDocumentsListAsync(ordering, page, pageSize); + if (result.Status != ExternalResponseStatus.Success) + { + throw GetMayanResponseError(result.Message); + } return result; } public async Task>> GetDocumentTypeMetadataType(long mayanDocumentTypeId, string ordering = "", int? page = null, int? pageSize = null) { + this.Logger.LogInformation("Retrieving document type metadata type {mayanDocumentTypeId}", mayanDocumentTypeId); + this.User.ThrowIfNotAuthorized(Permissions.DocumentView); + ExternalResponse> result = await documentStorageRepository.TryGetDocumentTypeMetadataTypesAsync(mayanDocumentTypeId, ordering, page, pageSize); + if (result.Status != ExternalResponseStatus.Success) + { + throw GetMayanResponseError(result.Message); + } return result; } public async Task>> GetStorageDocumentMetadata(long mayanDocumentId, string ordering = "", int? page = null, int? pageSize = null) { - this.Logger.LogInformation("Retrieving storage document metadata"); + this.Logger.LogInformation("Retrieving storage document metadata {mayanDocumentId}", mayanDocumentId); this.User.ThrowIfNotAuthorized(Permissions.DocumentView); ExternalResponse> result = await documentStorageRepository.TryGetDocumentMetadataAsync(mayanDocumentId, ordering, page, pageSize); + if (result.Status != ExternalResponseStatus.Success) + { + throw GetMayanResponseError(result.Message); + } return result; } public async Task> GetStorageDocumentDetail(long mayanDocumentId) { - this.Logger.LogInformation("Retrieving storage document"); + this.Logger.LogInformation("Retrieving storage document, {mayanDocumentId}", mayanDocumentId); this.User.ThrowIfNotAuthorized(Permissions.DocumentView); ExternalResponse result = await documentStorageRepository.TryGetDocumentAsync(mayanDocumentId); + if (result.Status != ExternalResponseStatus.Success) + { + throw GetMayanResponseError(result.Message); + } return result; } public async Task> DownloadFileAsync(long mayanDocumentId, long mayanFileId) { - this.Logger.LogInformation("Downloading storage document"); + this.Logger.LogInformation("Downloading storage document {mayanDocumentId} {mayanFileId}", mayanDocumentId, mayanFileId); this.User.ThrowIfNotAuthorized(Permissions.DocumentView); ExternalResponse downloadResult = await documentStorageRepository.TryDownloadFileAsync(mayanDocumentId, mayanFileId); if (IsValidDocumentExtension(downloadResult.Payload.FileName)) { + if (downloadResult.Status != ExternalResponseStatus.Success) + { + throw GetMayanResponseError(downloadResult.Message); + } return downloadResult; } else @@ -368,7 +406,7 @@ public async Task> DownloadFileAsync(long public async Task> DownloadFileLatestAsync(long mayanDocumentId) { - this.Logger.LogInformation("Downloading storage document latest"); + this.Logger.LogInformation("Downloading storage document latest {mayanDocumentId}", mayanDocumentId); ExternalResponse documentResult = await documentStorageRepository.TryGetDocumentAsync(mayanDocumentId); if (documentResult.Status == ExternalResponseStatus.Success) @@ -400,12 +438,7 @@ public async Task> DownloadFileLatestAsyn } else { - return new ExternalResponse() - { - Status = documentResult.Status, - Message = documentResult.Message, - HttpStatusCode = documentResult.HttpStatusCode, - }; + throw GetMayanResponseError(documentResult.Message); } } @@ -414,7 +447,12 @@ public async Task>> GetDocumentFil this.Logger.LogInformation("Retrieving pages for document: {documentId} file: {documentFileId}", documentId, documentFileId); this.User.ThrowIfNotAuthorized(Permissions.DocumentView); - return await documentStorageRepository.TryGetFilePageListAsync(documentId, documentFileId, _config.PreviewPages, 1); + var result = await documentStorageRepository.TryGetFilePageListAsync(documentId, documentFileId, _config.PreviewPages, 1); + if (result.Status != ExternalResponseStatus.Success) + { + throw GetMayanResponseError(result.Message); + } + return result; } public async Task DownloadFilePageImageAsync(long mayanDocumentId, long mayanFileId, long mayanFilePageId) @@ -426,7 +464,13 @@ public async Task DownloadFilePageImageAsync(long mayanDocu .HandleResult(result => result?.StatusCode != HttpStatusCode.OK || result?.Content == null) .WaitAndRetryAsync(_config.ImageRetries, (int retry) => TimeSpan.FromSeconds(Math.Pow(2, retry))); - return await retryPolicy.ExecuteAsync(async () => await documentStorageRepository.TryGetFilePageImage(mayanDocumentId, mayanFileId, mayanFilePageId)); + var result = await retryPolicy.ExecuteAsync(async () => await documentStorageRepository.TryGetFilePageImage(mayanDocumentId, mayanFileId, mayanFilePageId)); + + if (result.StatusCode != HttpStatusCode.OK) + { + throw GetMayanResponseError(await result.Content.ReadAsStringAsync()); + } + return result; } private static bool IsValidDocumentExtension(string fileName) @@ -462,7 +506,7 @@ private async Task PrecacheDocumentPreviews(long documentId, long documentFileId private async Task> UploadDocumentAsync(long documentType, IFormFile fileRaw) { - this.Logger.LogInformation("Uploading storage document"); + this.Logger.LogInformation("Uploading storage document {documentType}", documentType); this.User.ThrowIfNotAuthorized(Permissions.DocumentAdd); await this.avService.ScanAsync(fileRaw); @@ -480,7 +524,7 @@ private async Task> UploadDocumentAsync(lo private async Task>> CreateMetadata(long mayanDocumentId, List metadataRequest) { // Save metadata of document - IList>> metadataCreateTasks = new List>>(); + List>> metadataCreateTasks = new List>>(); foreach (var metadata in metadataRequest) { metadataCreateTasks.Add(documentStorageRepository.TryCreateDocumentMetadataAsync(mayanDocumentId, metadata.MetadataTypeId, metadata.Value)); @@ -502,7 +546,7 @@ private async Task>> CreateMetadata private async Task>> UpdateMetadata(long mayanDocumentId, List metadataRequest) { // Save metadata of document - IList>> metadataUpdateTasks = new List>>(); + List>> metadataUpdateTasks = new List>>(); foreach (var metadata in metadataRequest) { metadataUpdateTasks.Add(documentStorageRepository.TryUpdateDocumentMetadataAsync(mayanDocumentId, metadata.Id, metadata.Value)); @@ -524,7 +568,7 @@ private async Task>> UpdateMetadata private async Task>> DeleteMetadata(long mayanDocumentId, List metadataRequest) { // Save metadata of document - IList>> metadataDeleteTasks = new List>>(); + List>> metadataDeleteTasks = new List>>(); foreach (var metadata in metadataRequest) { metadataDeleteTasks.Add(documentStorageRepository.TryDeleteDocumentMetadataAsync(mayanDocumentId, metadata.Id)); @@ -547,5 +591,15 @@ private async Task>> DeleteMetadata return result; } + + private MayanRepositoryException GetMayanResponseError(string errorMesage) + { + if (_config.ExposeErrors) + { + return new MayanRepositoryException(errorMesage); + } + + return new MayanRepositoryException(MayanGenericErrorMessage); + } } } diff --git a/source/backend/tests/unit/api/Services/DocumentServiceTest.cs b/source/backend/tests/unit/api/Services/DocumentServiceTest.cs index 219eea28bb..367553cc23 100644 --- a/source/backend/tests/unit/api/Services/DocumentServiceTest.cs +++ b/source/backend/tests/unit/api/Services/DocumentServiceTest.cs @@ -29,6 +29,7 @@ using Pims.Api.Models.Requests.Document.UpdateMetadata; using Pims.Api.Constants; using Microsoft.Extensions.Configuration; +using Pims.Core.Exceptions; namespace Pims.Api.Test.Services { @@ -723,10 +724,10 @@ public async void DownloadFileLatestAsync_UnSuccessfull() }); // Act - await service.DownloadFileLatestAsync(1); + Func act = async () => await service.DownloadFileLatestAsync(1); // Assert - documentStorageRepository.Verify(x => x.TryDownloadFileAsync(It.IsAny(), It.IsAny()), Times.Never); + await act.Should().ThrowAsync(); } [Fact] diff --git a/source/frontend/package.json b/source/frontend/package.json index 74cba783cd..bf45a7c91e 100644 --- a/source/frontend/package.json +++ b/source/frontend/package.json @@ -1,6 +1,6 @@ { "name": "frontend", - "version": "5.3.2-81.35", + "version": "5.3.3-81.35", "private": true, "dependencies": { "@bcgov/bc-sans": "1.0.1",