Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions Octans.Client/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,12 @@
builder.AddOctansObservability();
builder.Services.AddOctansClient();
builder.Services.AddInfrastructure();
builder.Services.AddOctansServices();
var registerBackgroundWorkers = builder.Configuration.GetValue("Octans:BackgroundWorkers:Enabled", true);
builder.Services.AddOctansServices(options =>
{
options.RegisterBackgroundWorkers = registerBackgroundWorkers;
options.RegisterDownloadBackgroundWorker = registerBackgroundWorkers;
});
builder.Services.AddViewmodels();
builder.Services.AddDatabase();

Expand All @@ -40,7 +45,7 @@
{
options.MaxConcurrentDownloads = 5;
options.MaxConcurrentDownloadsPerDomain = 2;
});
}, registerBackgroundWorkers);

builder.SetupConfiguration();

Expand Down
6 changes: 4 additions & 2 deletions Octans.Client/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,11 @@ public static void AddKeyProtection(this WebApplicationBuilder builder)
#pragma warning restore RS0030
}

public static IServiceCollection AddOctansServices(this IServiceCollection services)
public static IServiceCollection AddOctansServices(
this IServiceCollection services,
Action<OctansCoreServiceOptions>? configure = null)
{
return services.AddOctansCoreServices();
return services.AddOctansCoreServices(configure);
}

public static void AddDatabase(this IServiceCollection services)
Expand Down
13 changes: 9 additions & 4 deletions Octans.Core/Http/DownloadServiceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ public static class DownloadServiceExtensions
/// </summary>
public static IServiceCollection AddDownloadManager(
this IServiceCollection services,
Action<DownloadManagerOptions>? configure = null)
Action<DownloadManagerOptions>? configure = null,
bool registerBackgroundService = true)
{
services.RemoveAll<DownloadManagerOptions>();
services.AddOptions<DownloadManagerOptions>()
Expand All @@ -42,7 +43,10 @@ public static IServiceCollection AddDownloadManager(
services.TryAddSingleton<HttpDownloader>();
services.TryAddSingleton<IDownloadService, DownloadService>();
services.TryAddSingleton<IDownloadQueue, DatabaseDownloadQueue>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, DownloadBackgroundService>());
if (registerBackgroundService)
{
services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, DownloadBackgroundService>());
}

services.AddHttpClient("DownloadClient", client => client.Timeout = Timeout.InfiniteTimeSpan)
.ConfigurePrimaryHttpMessageHandler(provider =>
Expand Down Expand Up @@ -141,12 +145,13 @@ private static TimeSpan Double(TimeSpan value)
public static IServiceCollection AddDownloadManager(
this IServiceCollection services,
IConfiguration configuration,
Action<DownloadManagerOptions>? configure = null)
Action<DownloadManagerOptions>? configure = null,
bool registerBackgroundService = true)
{
return services.AddDownloadManager(options =>
{
configuration.Bind(options);
configure?.Invoke(options);
});
}, registerBackgroundService);
}
}
60 changes: 52 additions & 8 deletions Octans.Core/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,38 @@ namespace Octans.Core;

public static class ServiceCollectionExtensions
{
public static IServiceCollection AddOctansCoreServices(this IServiceCollection services)
private static readonly HashSet<Type> OctansBackgroundWorkerTypes =
[
typeof(ImportFolderBackgroundService),
typeof(ImportProcessorService),
typeof(SubscriptionBackgroundService),
typeof(RepositoryChangeBackgroundService),
typeof(DownloadBackgroundService),
typeof(ThumbnailCreationBackgroundService)
];

public static IServiceCollection AddOctansCoreServices(
this IServiceCollection services,
Action<OctansCoreServiceOptions>? configure = null)
{
var options = new OctansCoreServiceOptions();
configure?.Invoke(options);

services.AddOctansChannels();

services.AddHostedService<ImportFolderBackgroundService>();
services.AddHostedService<ImportProcessorService>();
services.AddHostedService<SubscriptionBackgroundService>();
services.AddHostedService<RepositoryChangeBackgroundService>();
if (options.RegisterBackgroundWorkers)
{
services.AddHostedService<ImportFolderBackgroundService>();
services.AddHostedService<ImportProcessorService>();
services.AddHostedService<SubscriptionBackgroundService>();
services.AddHostedService<RepositoryChangeBackgroundService>();
}

services.AddSingleton<IBackgroundProgressReporter, BackgroundProgressService>();
services.AddScoped<ImportFolderScanner>();
services.AddSingleton<RepositoryChangeProcessor>();

services.AddBusinessServices();
services.AddBusinessServices(options.RegisterDownloadBackgroundWorker);

return services;
}
Expand All @@ -63,7 +81,27 @@ public static IServiceCollection AddOctansChannels(this IServiceCollection servi
return services;
}

public static IServiceCollection AddBusinessServices(this IServiceCollection services)
public static IServiceCollection RemoveOctansBackgroundWorkers(this IServiceCollection services)
{
for (var i = services.Count - 1; i >= 0; i--)
{
var descriptor = services[i];
if (descriptor.ServiceType != typeof(IHostedService) ||
descriptor.ImplementationType is not { } implementationType ||
!OctansBackgroundWorkerTypes.Contains(implementationType))
{
continue;
}

services.RemoveAt(i);
}

return services;
}

public static IServiceCollection AddBusinessServices(
this IServiceCollection services,
bool registerDownloadBackgroundWorker = true)
{
// Imports
services.AddScoped<SimpleImporter>();
Expand Down Expand Up @@ -100,7 +138,7 @@ public static IServiceCollection AddBusinessServices(this IServiceCollection ser
services.AddSingleton(TimeProvider.System);
services.AddSingleton<IRobustFileWriter, RobustFileWriter>();
services.AddBandwidthLimiter();
services.AddDownloadManager();
services.AddDownloadManager(registerBackgroundService: registerDownloadBackgroundWorker);

// Queries
services.AddScoped<IQueryService, QueryService>();
Expand Down Expand Up @@ -130,3 +168,9 @@ public static IServiceCollection AddBusinessServices(this IServiceCollection ser
return services;
}
}

public sealed class OctansCoreServiceOptions
{
public bool RegisterBackgroundWorkers { get; set; } = true;
public bool RegisterDownloadBackgroundWorker { get; set; } = true;
}
98 changes: 98 additions & 0 deletions Octans.Tests/Infrastructure/OctansApiFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System.IO.Abstractions;
using System.IO.Abstractions.TestingHelpers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Time.Testing;
using Octans.Client;
using Octans.Core;
using Octans.Data.Models;
using Octans.Tests.Helpers;
using Xunit.Abstractions;

namespace Octans.Tests.Infrastructure;

public sealed class OctansApiFactory : WebApplicationFactory<Program>
{
private readonly SqliteConnection _keepAliveConnection;
private readonly ITestOutputHelper? _output;

public OctansApiFactory(ITestOutputHelper? output = null)
{
_output = output;
AppRoot = $"/octans-api-{Guid.NewGuid():N}";
FileSystem = new();
TimeProvider = new(TestClock.UtcNow);

var connectionString = $"Data Source=OctansApiFactory-{Guid.NewGuid():N};Mode=Memory;Cache=Shared";
_keepAliveConnection = new(connectionString);
_keepAliveConnection.Open();
ConnectionString = connectionString;
}

public string AppRoot { get; }
public MockFileSystem FileSystem { get; }
public FakeTimeProvider TimeProvider { get; }
public string ConnectionString { get; }

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration((_, configuration) =>
{
configuration.AddInMemoryCollection(new Dictionary<string, string?>
{
["GlobalSettings:AppRoot"] = AppRoot,
["Octans:BackgroundWorkers:Enabled"] = "false",
["ImportFolder:Enabled"] = "false"
});
});

builder.ConfigureTestServices(services =>
{
services.RemoveOctansBackgroundWorkers();

services.RemoveAll<ServerDbContext>();
services.RemoveAll<DbContextOptions<ServerDbContext>>();
services.RemoveAll<IDbContextFactory<ServerDbContext>>();

services.AddDbContextFactory<ServerDbContext>(options => options.UseSqlite(ConnectionString));
services.AddDbContext<ServerDbContext>(
options => options.UseSqlite(ConnectionString),
optionsLifetime: ServiceLifetime.Singleton);

services.RemoveAll<IFileSystem>();
services.AddSingleton<IFileSystem>(FileSystem);

services.RemoveAll<TimeProvider>();
services.AddSingleton<TimeProvider>(TimeProvider);

services.Configure<GlobalSettings>(settings => settings.AppRoot = AppRoot);

if (_output is not null)
{
services.AddLogging(logging => logging.AddProvider(new XUnitLoggerProvider(_output)));
}
});
}

public AsyncServiceScope CreateAsyncScope()
{
return Services.CreateAsyncScope();
}

protected override void Dispose(bool disposing)
{
base.Dispose(disposing);

if (disposing)
{
_keepAliveConnection.Dispose();
}
}
}
48 changes: 48 additions & 0 deletions Octans.Tests/Infrastructure/OctansApiFactoryTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System.Net.Http.Json;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Octans.Client;
using Octans.Core;
using Xunit.Abstractions;

namespace Octans.Tests.Infrastructure;

public sealed class OctansApiFactoryTests(ITestOutputHelper output)
{
[Fact]
public async Task Health_ShouldReturnHealthy()
{
using var factory = new OctansApiFactory(output);
var client = factory.CreateClient();

var response = await client.GetAsync(new Uri("/health", UriKind.Relative));

response.EnsureSuccessStatusCode();
var body = await response.Content.ReadAsStringAsync();
body.Should().Be("Healthy");
}

[Fact]
public async Task Version_ShouldReturnApiVersion()
{
using var factory = new OctansApiFactory(output);
var client = factory.CreateClient();

var version = await client.GetFromJsonAsync<OctansVersion>(new Uri("/version", UriKind.Relative));

version.Should().Be(new OctansVersion("1.0.0"));
}

[Fact]
public void Factory_ShouldDisableHostedServicesByDefault()
{
using var factory = new OctansApiFactory(output);
_ = factory.CreateClient();

factory.Services
.GetServices<IHostedService>()
.Should()
.NotContain(service => service.GetType().Assembly == typeof(OctansCoreServiceOptions).Assembly);
}
}