Skip to content

Commit

Permalink
Make sure AkkaHostedService failures are always visible (#494)
Browse files Browse the repository at this point in the history
* Make sure `AkkaHostedService` failures are always visible

close #470 - application crashes and exits should always be explicitly logged someplace where they can be seen regardless of logging configuration.

* Re-throw exception on application startup

---------

Co-authored-by: Gregorius Soedharmo <arkatufus@yahoo.com>
  • Loading branch information
Aaronontheweb and Arkatufus authored Oct 1, 2024
1 parent fb80b87 commit 401e020
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
52 changes: 52 additions & 0 deletions src/Akka.Hosting.Tests/StartFailureSpec.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System;
using System.Threading.Tasks;
using Akka.Actor;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;
using static FluentAssertions.FluentActions;

namespace Akka.Hosting.Tests;

public class StartFailureSpec
{
private readonly ITestOutputHelper _output;

public StartFailureSpec(ITestOutputHelper output)
{
_output = output;
}

[Fact]
public async Task ShouldThrowWhenActorSystemFailedToStart()
{
// arrange
var host = new HostBuilder()
.ConfigureLogging(builder =>
{
builder.ClearProviders();
builder.AddProvider(new XUnitLoggerProvider(_output, LogLevel.Debug));
})
.ConfigureServices(services =>
{
services.AddAkka("MySys", (builder, provider) =>
{
builder.AddStartup((_, _) => throw new TestException("BOOM"));
});
})
.Build();

await Awaiting(async () => await host.StartAsync()).Should()
.ThrowExactlyAsync<TestException>().WithMessage("BOOM");
}

private class TestException: Exception
{
public TestException(string? message) : base(message)
{
}
}
}
11 changes: 10 additions & 1 deletion src/Akka.Hosting/AkkaHostedService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Akka.Actor;
Expand Down Expand Up @@ -72,7 +73,15 @@ async Task TerminationHook()
catch (Exception ex)
{
Logger.Log(LogLevel.Critical, ex, "Unable to start AkkaHostedService - shutting down application");
HostApplicationLifetime?.StopApplication();

// resolve https://github.com/akkadotnet/Akka.Hosting/issues/470 - never allow failures to be silent
Console.WriteLine($"Unable to start AkkaHostedService - shutting down application.\nCause: {ex}");

// Best effort to perform a clean stop
var capturedException = ExceptionDispatchInfo.Capture(ex);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3));
await StopAsync(cts.Token);
capturedException.Throw();
}
}

Expand Down

0 comments on commit 401e020

Please sign in to comment.