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
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Copyright (c) Kurrent, Inc and/or licensed to Kurrent, Inc under one or more agreements.
// Kurrent, Inc licenses this file to you under the Kurrent License v1 (see LICENSE.md).

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Xunit;

namespace KurrentDB.Components.Tests;

// The host only watches ExecuteTask (and applies BackgroundServiceExceptionBehavior) for services that are
// BackgroundService instances, so the lifecycle decorator must not hide that from it.
public class HostedServiceLifecycleDecoratorTests {
class PlainService : IHostedService {
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}

class WaitingService : BackgroundService {
protected override Task ExecuteAsync(CancellationToken stoppingToken) =>
Task.Delay(Timeout.Infinite, stoppingToken);
}

class FailingService : BackgroundService {
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
await Task.Yield();
throw new InvalidOperationException("failed after startup");
}
}

[Fact]
public void Background_services_stay_background_services() {
Assert.IsType<BackgroundServiceLifecycleDecorator>(HostedServiceLifecycleDecorator.Decorate(new WaitingService()));
Assert.IsType<HostedServiceLifecycleDecorator>(HostedServiceLifecycleDecorator.Decorate(new PlainService()));
}

[Fact]
public async Task Execute_task_is_the_inner_services_task() {
var inner = new WaitingService();
var decorator = (BackgroundService)HostedServiceLifecycleDecorator.Decorate(inner);

await decorator.StartAsync(TestContext.Current.CancellationToken);
Assert.NotNull(inner.ExecuteTask);
Assert.Same(inner.ExecuteTask, decorator.ExecuteTask);

await decorator.StopAsync(TestContext.Current.CancellationToken);
Assert.True(inner.ExecuteTask.IsCompleted);
}

[Fact]
public async Task Stop_host_applies_to_a_decorated_background_service() {
var builder = Host.CreateEmptyApplicationBuilder(new());
builder.Services.Configure<HostOptions>(x =>
x.BackgroundServiceExceptionBehavior = BackgroundServiceExceptionBehavior.StopHost);
builder.Services.AddSingleton<IHostedService>(_ => HostedServiceLifecycleDecorator.Decorate(new FailingService()));
using var host = builder.Build();

var stopping = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
host.Services.GetRequiredService<IHostApplicationLifetime>().ApplicationStopping
.Register(() => stopping.TrySetResult());

await host.StartAsync(TestContext.Current.CancellationToken);
// Behind a decorator that hides BackgroundService, the failure goes unnoticed and this times out.
await stopping.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
}
}
29 changes: 29 additions & 0 deletions src/KurrentDB.Hosting/HostedServiceLifecycleDecorator.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) Kurrent, Inc and/or licensed to Kurrent, Inc under one or more agreements.
// Kurrent, Inc licenses this file to you under the Kurrent License v1 (see LICENSE.md).

#nullable enable

using System;
using System.Threading;
using System.Threading.Tasks;
Expand All @@ -12,9 +14,16 @@ namespace KurrentDB;

// Decorates every registered IHostedService and logs entry/exit/duration for
// StartAsync and StopAsync, so a slow or stalling service stands out during shutdown.
// Use Decorate to choose the decorator: a BackgroundService must stay a BackgroundService,
// or the host stops watching its ExecuteTask (see BackgroundServiceLifecycleDecorator).
public sealed class HostedServiceLifecycleDecorator(IHostedService inner) : IHostedService {
static readonly ILogger Log = Serilog.Log.ForContext<HostedServiceLifecycleDecorator>();

public static IHostedService Decorate(IHostedService inner) =>
inner is BackgroundService backgroundService
? new BackgroundServiceLifecycleDecorator(backgroundService)
: new HostedServiceLifecycleDecorator(inner);

readonly string _name = inner.GetType().Name;

public async Task StartAsync(CancellationToken cancellationToken) {
Expand Down Expand Up @@ -51,3 +60,23 @@ public async Task StopAsync(CancellationToken cancellationToken) {
}
}
}

// The host checks each started service for BackgroundService and watches its ExecuteTask:
// when that task faults it logs the failure and applies HostOptions.BackgroundServiceExceptionBehavior.
// Deriving from BackgroundService and passing ExecuteTask through keeps that working behind the decorator.
public sealed class BackgroundServiceLifecycleDecorator(BackgroundService inner) : BackgroundService {
readonly HostedServiceLifecycleDecorator _logging = new(inner);

public override Task? ExecuteTask =>
inner.ExecuteTask;

public override Task StartAsync(CancellationToken cancellationToken) =>
_logging.StartAsync(cancellationToken);

public override Task StopAsync(CancellationToken cancellationToken) =>
_logging.StopAsync(cancellationToken);

// StartAsync is overridden and never calls base, so this is never invoked.
protected override Task ExecuteAsync(CancellationToken stoppingToken) =>
throw new InvalidOperationException("Unexpected error, this should never be called");
}
2 changes: 1 addition & 1 deletion src/KurrentDB.Hosting/NodeWebApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public static void ConfigureServices(IServiceCollection services, ClusterVNodeHo
// call once every hosted service has been registered, the host's own included: it decorates what is
// already there.
public static void LogHostedServiceLifecycle(IServiceCollection services) =>
services.Decorate<IHostedService, HostedServiceLifecycleDecorator>();
services.Decorate<IHostedService>(HostedServiceLifecycleDecorator.Decorate);

public static void Configure(WebApplication app, ClusterVNodeHostedService hostedService) =>
hostedService.Node.Startup.Configure(app);
Expand Down
Loading