Heimdall Gitea / Detect CI scope (push) Successful in 19s
Heimdall Gitea / Build and tests (push) Successful in 18m10s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 5m20s
Heimdall Gitea / Build and scan agent image (push) Successful in 9m26s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m19s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 16m17s
Heimdall Gitea / CI policy (push) Successful in 2s
Fixes blocking SignalR client shutdown; see issue #233. Co-authored-by: Arnaud Dartois <admin@tordais.cc>
146 lines
4.7 KiB
C#
146 lines
4.7 KiB
C#
using System.Text.Json;
|
|
using Microsoft.AspNetCore.Components;
|
|
using Microsoft.AspNetCore.SignalR.Client;
|
|
|
|
namespace Heimdall.Web.Services;
|
|
|
|
/// <summary>
|
|
/// Client hub SignalR pour les notifications temps réel (badge compteur).
|
|
/// S'abonne au groupe personnel "notif_{userId}" et expose l'événement
|
|
/// <see cref="UnreadCountChanged"/>. Un chargement API initial garantit le
|
|
/// compteur même si la connexion temps réel n'est pas encore disponible.
|
|
/// </summary>
|
|
public class NotificationsHubClient : IAsyncDisposable, IDisposable
|
|
{
|
|
private readonly AuthState _authState;
|
|
private readonly HeimdallApiClient _api;
|
|
private readonly NavigationManager _navigation;
|
|
private readonly ILogger<NotificationsHubClient> _logger;
|
|
private HubConnection? _connection;
|
|
private bool _started;
|
|
|
|
public NotificationsHubClient(
|
|
AuthState authState,
|
|
HeimdallApiClient api,
|
|
NavigationManager navigation,
|
|
ILogger<NotificationsHubClient> logger)
|
|
{
|
|
_authState = authState;
|
|
_api = api;
|
|
_navigation = navigation;
|
|
_logger = logger;
|
|
}
|
|
|
|
/// <summary>Compteur de notifications non lues (mis à jour par le hub).</summary>
|
|
public int UnreadCount { get; private set; }
|
|
|
|
public event Action<int>? UnreadCountChanged;
|
|
|
|
public async Task RefreshUnreadCountAsync()
|
|
{
|
|
try
|
|
{
|
|
var count = await _api.GetUnreadNotificationCountAsync();
|
|
UnreadCount = count;
|
|
UnreadCountChanged?.Invoke(count);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogDebug(ex, "NotificationsHubClient: chargement initial du compteur impossible");
|
|
}
|
|
}
|
|
|
|
public async Task StartAsync()
|
|
{
|
|
if (_started || !_authState.IsLoggedIn)
|
|
return;
|
|
|
|
try
|
|
{
|
|
var accessToken = _authState.AccessToken;
|
|
if (string.IsNullOrEmpty(accessToken))
|
|
return; // session cookie (SSR/reload) : pas de JWT → pas de hub, fallback silencieux
|
|
|
|
_connection = new HubConnectionBuilder()
|
|
.WithUrl($"{_navigation.BaseUri}hubs/notifications", options =>
|
|
{
|
|
options.AccessTokenProvider = GetAccessTokenAsync;
|
|
})
|
|
.WithAutomaticReconnect()
|
|
.Build();
|
|
|
|
_connection.On<JsonElement>("UnreadCount", (payload) =>
|
|
{
|
|
if (payload.ValueKind != JsonValueKind.Object ||
|
|
!payload.TryGetProperty("count", out var countElement) ||
|
|
!countElement.TryGetInt32(out var count) || count < 0)
|
|
{
|
|
_logger.LogWarning("NotificationsHubClient: unread count payload inattendu");
|
|
return;
|
|
}
|
|
|
|
UnreadCount = count;
|
|
UnreadCountChanged?.Invoke(count);
|
|
});
|
|
|
|
_connection.On<object>("NewNotification", (_) =>
|
|
{
|
|
UnreadCount++;
|
|
UnreadCountChanged?.Invoke(UnreadCount);
|
|
});
|
|
|
|
await _connection.StartAsync();
|
|
await _connection.InvokeAsync("JoinPersonalNotifications");
|
|
_started = true;
|
|
_logger.LogDebug("NotificationsHubClient connecté");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogWarning(ex, "NotificationsHubClient: connexion impossible — fallback polling");
|
|
}
|
|
}
|
|
|
|
private Task<string?> GetAccessTokenAsync() => Task.FromResult(_authState.AccessToken);
|
|
|
|
public void Dispose()
|
|
{
|
|
// Synchronous disposal cannot safely wait for SignalR network shutdown.
|
|
// Start the asynchronous cleanup and return immediately; async consumers
|
|
// should use DisposeAsync to observe its completion.
|
|
_ = DisposeConnectionAsync();
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await DisposeConnectionAsync().ConfigureAwait(false);
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
|
|
private async Task DisposeConnectionAsync()
|
|
{
|
|
var connection = Interlocked.Exchange(ref _connection, null);
|
|
_started = false;
|
|
if (connection is null)
|
|
return;
|
|
|
|
try
|
|
{
|
|
await connection.StopAsync(CancellationToken.None).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogDebug(ex, "NotificationsHubClient: arrêt de la connexion impossible");
|
|
}
|
|
|
|
try
|
|
{
|
|
await connection.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogDebug(ex, "NotificationsHubClient: libération de la connexion impossible");
|
|
}
|
|
}
|
|
}
|