Skip to content

Commit

Permalink
fix: Azure throws an Exception when the index doesn't exist
Browse files Browse the repository at this point in the history
Why do companies do this? Just imagine if SQL Server threw an exception every time a query didn't return any results. Not finding something IS NOT EXCEPTIONAL.
  • Loading branch information
killij authored Dec 8, 2023
1 parent a2e40ef commit 4c1330d
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,13 +1,42 @@
using Azure;
using Azure.Core;
using Azure.Search.Documents;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;
using Childrens_Social_Care_CPD_Indexer.Core;
using Microsoft.Extensions.Logging;
using NSubstitute.ExceptionExtensions;
using System.Diagnostics.CodeAnalysis;

namespace Childrens_Social_Care_CPD_Indexer.Tests.Core;

public class ResourcesIndexerTest
internal sealed class MockResponse : Response
{
public override int Status => 404;
public override string ReasonPhrase => string.Empty;

public override Stream? ContentStream
{
get => new MemoryStream();
set => throw new NotImplementedException();
}
public override string ClientRequestId
{
get => throw new NotImplementedException();
set => throw new NotImplementedException();
}

public override void Dispose() => throw new NotImplementedException();
protected override bool ContainsHeader(string name) => false;
protected override IEnumerable<HttpHeader> EnumerateHeaders() => Array.Empty<HttpHeader>();
protected override bool TryGetHeader(string name, [NotNullWhen(true)] out string? value) {
value = null;
return false;
}
protected override bool TryGetHeaderValues(string name, [NotNullWhen(true)] out IEnumerable<string>? values) => throw new NotImplementedException();
}

public class ResourcesIndexerTests
{
private ILogger _logger;
private SearchIndexClient _client;
Expand All @@ -28,9 +57,8 @@ public void Setup()
public async Task DeleteIndexAsync_Skips_Deletion_If_Index_Does_Not_Exist()
{
// arrange
var response = Substitute.For<Response<SearchIndex>>();
response.HasValue.Returns(false);
_client.GetIndexAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Task.FromResult(response));
var exception = new RequestFailedException(new MockResponse());
_client.GetIndexAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Throws(exception);

// act
await _sut.DeleteIndexAsync("foo");
Expand Down Expand Up @@ -77,9 +105,8 @@ public async Task DeleteIndexAsync_Logs_Failure_To_Delete_Index()
public async Task CreateIndexAsync_Creates_The_Index()
{
// arrange
var getIndexResult = Substitute.For<Response<SearchIndex>>();
getIndexResult.HasValue.Returns(false);
_client.GetIndexAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Task.FromResult(getIndexResult));
var exception = new RequestFailedException(new MockResponse());
_client.GetIndexAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Throws(exception);

SearchIndex? searchIndex = null;
await _client.CreateIndexAsync(Arg.Do<SearchIndex>(x => searchIndex = x), Arg.Any<CancellationToken>());
Expand Down
29 changes: 24 additions & 5 deletions src/Childrens-Social-Care-CPD-Indexer/Core/ResourcesIndexer.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,33 @@
using Azure.Search.Documents.Indexes;
using Azure;
using Azure.Search.Documents.Indexes;
using Azure.Search.Documents.Indexes.Models;

namespace Childrens_Social_Care_CPD_Indexer.Core;

internal class ResourcesIndexer(SearchIndexClient searchIndexClient, IDocumentFetcher documentFetcher, ILogger logger): IResourcesIndexer
{
private async Task<bool> IndexExistsAsync(string indexName, CancellationToken cancellationToken)
{
try
{
var index = await searchIndexClient.GetIndexAsync(indexName, cancellationToken);
return index.HasValue;
}
catch (RequestFailedException rf)
{
if (rf.Status == 404)
{
return false;
}

throw;
}
}

public async Task CreateIndexAsync(string indexName, CancellationToken cancellationToken = default)
{
var index = await searchIndexClient.GetIndexAsync(indexName, cancellationToken);
if (index.HasValue)
var indexExists = await IndexExistsAsync(indexName, cancellationToken);
if (indexExists)
{
logger.LogInformation("Index already exists, skipping creation.");
return;
Expand All @@ -25,8 +44,8 @@ public async Task CreateIndexAsync(string indexName, CancellationToken cancellat
public async Task DeleteIndexAsync(string indexName, CancellationToken cancellationToken = default)
{
logger.LogInformation("Deleting index...");
var index = await searchIndexClient.GetIndexAsync(indexName, cancellationToken);
if (index.HasValue)
var indexExists = await IndexExistsAsync(indexName, cancellationToken);
if (indexExists)
{
var deleteResponse = await searchIndexClient.DeleteIndexAsync(indexName, cancellationToken);
if (deleteResponse.IsError)
Expand Down

0 comments on commit 4c1330d

Please sign in to comment.