Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change EventBus to be independent of host #437

Merged
merged 1 commit into from
Aug 7, 2022
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
6 changes: 4 additions & 2 deletions src/Tingle.EventBus/DependencyInjection/EventBusBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@ public EventBusBuilder(IServiceCollection services)
Services.AddSingleton<IEventConfigurator, DefaultEventConfigurator>();
Services.AddSingleton<IEventIdGenerator, DefaultEventIdGenerator>();

// Register the bus and its host
Services.AddSingleton<EventBus>();
Services.AddHostedService<EventBusHost>();

// Register necessary services
Services.AddTransient<IEventPublisher, EventPublisher>();
Services.AddSingleton<EventBus>();
Services.AddHostedService(p => p.GetRequiredService<EventBus>());
UseDefaultSerializer<DefaultJsonEventSerializer>();

// Register health/readiness services needed
Expand Down
52 changes: 12 additions & 40 deletions src/Tingle.EventBus/EventBus.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Diagnostics;
Expand All @@ -12,11 +11,10 @@
namespace Tingle.EventBus;

/// <summary>
/// The abstractions for an event bus
/// The event bus
/// </summary>
public class EventBus : BackgroundService
public class EventBus
{
private readonly IHostApplicationLifetime lifetime;
private readonly IReadinessProvider readinessProvider;
private readonly IEventIdGenerator idGenerator;
private readonly IList<IEventBusTransport> transports;
Expand All @@ -27,22 +25,19 @@ public class EventBus : BackgroundService
/// <summary>
///
/// </summary>
/// <param name="lifetime"></param>
/// <param name="readinessProvider"></param>
/// <param name="idGenerator"></param>
/// <param name="optionsAccessor"></param>
/// <param name="transports"></param>
/// <param name="configurators"></param>
/// <param name="loggerFactory"></param>
public EventBus(IHostApplicationLifetime lifetime,
IReadinessProvider readinessProvider,
public EventBus(IReadinessProvider readinessProvider,
IEventIdGenerator idGenerator,
IEnumerable<IEventBusTransport> transports,
IEnumerable<IEventConfigurator> configurators,
IOptions<EventBusOptions> optionsAccessor,
ILoggerFactory loggerFactory)
{
this.lifetime = lifetime ?? throw new ArgumentNullException(nameof(lifetime));
this.readinessProvider = readinessProvider ?? throw new ArgumentNullException(nameof(readinessProvider));
this.idGenerator = idGenerator ?? throw new ArgumentNullException(nameof(idGenerator));
this.configurators = configurators?.ToList() ?? throw new ArgumentNullException(nameof(configurators));
Expand Down Expand Up @@ -205,15 +200,9 @@ public async Task CancelAsync<TEvent>(IList<string> ids, CancellationToken cance
await transport.CancelAsync<TEvent>(ids: ids, registration: reg, cancellationToken: cancellationToken);
}

/// <inheritdoc/>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
///
public async Task StartAsync(CancellationToken cancellationToken)
{
if (!await WaitForAppStartupAsync(lifetime, stoppingToken).ConfigureAwait(false))
{
logger.ApplicationDidNotStartup();
return;
}

// If a startup delay has been specified, apply it
var delay = options.StartupDelay;
if (delay != null && delay > TimeSpan.Zero)
Expand All @@ -223,8 +212,8 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
try
{
logger.DelayedBusStartup(delay.Value);
await Task.Delay(delay.Value, stoppingToken);
await StartTransportsAsync(stoppingToken);
await Task.Delay(delay.Value, cancellationToken);
await StartTransportsAsync(cancellationToken);
}
catch (Exception ex)
when (!(ex is OperationCanceledException || ex is TaskCanceledException)) // skip operation cancel
Expand All @@ -235,25 +224,10 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
else
{
// Without a delay, just start the transports directly
await StartTransportsAsync(stoppingToken);
await StartTransportsAsync(cancellationToken);
}
}

private static async Task<bool> WaitForAppStartupAsync(IHostApplicationLifetime lifetime, CancellationToken stoppingToken)
{
var startedTcs = new TaskCompletionSource<object>();
var cancelledTcs = new TaskCompletionSource<object>();

// register result setting using the cancellation tokens
lifetime.ApplicationStarted.Register(() => startedTcs.SetResult(new { }));
stoppingToken.Register(() => cancelledTcs.SetResult(new { }));

var completedTask = await Task.WhenAny(startedTcs.Task, cancelledTcs.Task).ConfigureAwait(false);

// if the completed task was the "app started" one, return true
return completedTask == startedTcs.Task;
}

private async Task StartTransportsAsync(CancellationToken cancellationToken)
{
if (options.Readiness.Enabled)
Expand All @@ -279,13 +253,11 @@ private async Task StartTransportsAsync(CancellationToken cancellationToken)
}
}

/// <inheritdoc/>
public override async Task StopAsync(CancellationToken cancellationToken)
///
public async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken);

// Stop the bus and its transports in parallel
logger.StoppingBus();
// Stop the transports in parallel
logger.StoppingTransports();
var tasks = transports.Select(t => t.StopAsync(cancellationToken));
await Task.WhenAll(tasks);
}
Expand Down
62 changes: 62 additions & 0 deletions src/Tingle.EventBus/EventBusHost.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Tingle.EventBus;

/// <summary>
/// Host for <see cref="EventBus"/>.
/// </summary>
internal class EventBusHost : BackgroundService
{
private readonly IHostApplicationLifetime lifetime;
private readonly EventBus bus;
private readonly ILogger logger;

/// <summary>
///
/// </summary>
/// <param name="lifetime"></param>
/// <param name="bus"></param>
/// <param name="logger"></param>
public EventBusHost(IHostApplicationLifetime lifetime, EventBus bus, ILogger<EventBusHost> logger)
{
this.lifetime = lifetime ?? throw new ArgumentNullException(nameof(lifetime));
this.bus = bus ?? throw new ArgumentNullException(nameof(bus));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}

/// <inheritdoc/>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!await WaitForAppStartupAsync(lifetime, stoppingToken).ConfigureAwait(false))
{
logger.ApplicationDidNotStartup();
return;
}

await bus.StartAsync(stoppingToken);
}

/// <inheritdoc/>
public override async Task StopAsync(CancellationToken cancellationToken)
{
logger.StoppingBus();
await base.StopAsync(cancellationToken);
await bus.StopAsync(cancellationToken);
}

private static async Task<bool> WaitForAppStartupAsync(IHostApplicationLifetime lifetime, CancellationToken stoppingToken)
{
var startedTcs = new TaskCompletionSource<object>();
var cancelledTcs = new TaskCompletionSource<object>();

// register result setting using the cancellation tokens
lifetime.ApplicationStarted.Register(() => startedTcs.SetResult(new { }));
stoppingToken.Register(() => cancelledTcs.SetResult(new { }));

var completedTask = await Task.WhenAny(startedTcs.Task, cancelledTcs.Task).ConfigureAwait(false);

// if the completed task was the "app started" one, return true
return completedTask == startedTcs.Task;
}
}
3 changes: 3 additions & 0 deletions src/Tingle.EventBus/Extensions/ILoggerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ internal static partial class ILoggerExtensions
[LoggerMessage(107, LogLevel.Debug, "Stopping bus.")]
public static partial void StoppingBus(this ILogger logger);

[LoggerMessage(108, LogLevel.Debug, "Stopping transports.")]
public static partial void StoppingTransports(this ILogger logger);

#endregion

#region Transports (200 series)
Expand Down