PlotDirector/PlotLine/Services/ContextWorkspaceNotifications.cs
2026-11-30 23:20:12 +00:00

45 lines
2.4 KiB
C#

using Microsoft.AspNetCore.SignalR;
using System.Text.Json.Serialization;
using PlotLine.Hubs;
namespace PlotLine.Services;
// Presentation hints only. A notification failure must never turn a durable save into a failed write.
public sealed class ContextWorkspaceNotifications(IHubContext<NativeCompanionPresenceHub> hub, ILogger<ContextWorkspaceNotifications> logger,IHttpContextAccessor? accessor=null)
{
private const string Marker="PlotDirector.ContextInvalidated";
private const string Pending="PlotDirector.ContextPending";
public bool AlreadyInvalidated=>accessor?.HttpContext?.Items.ContainsKey(Marker)==true;
public Task Position(int user) => Send(user, "ContextPositionChanged", new { });
public Task Invalidate(int user,int? bookId=null,int? chapterId=null,int? sceneId=null,int? projectId=null,string? kind=null,
int? entityId=null,string? entityType=null)
{
var hint=new SavedHint(bookId,chapterId,sceneId,projectId,kind,entityId,entityType);
if(accessor?.HttpContext is not {} context)return Send(user,"ContextInvalidated",hint);
context.Items[Marker]=true;
if(context.Items[Pending] is not HashSet<(int User,SavedHint Hint)> pending)
context.Items[Pending]=pending=[];
pending.Add((user,hint));
return Task.CompletedTask;
}
// The action filter publishes explicit save hints only after the whole action succeeds.
public async Task PublishPending()
{
if(accessor?.HttpContext?.Items[Pending] is not HashSet<(int User,SavedHint Hint)> pending)return;
foreach(var item in pending)await Send(item.User,"ContextInvalidated",item.Hint);
pending.Clear();
}
private sealed record SavedHint(
[property: JsonPropertyName("bookId")] int? BookId,
[property: JsonPropertyName("chapterId")] int? ChapterId,
[property: JsonPropertyName("sceneId")] int? SceneId,
[property: JsonPropertyName("projectId")] int? ProjectId,
[property: JsonPropertyName("kind")] string? Kind,
[property: JsonPropertyName("entityId")] int? EntityId,
[property: JsonPropertyName("entityType")] string? EntityType);
private async Task Send(int user, string name, object hint)
{
try { await hub.Clients.Group(NativeCompanionPresenceHub.UserGroup(user)).SendAsync(name, hint); }
catch (Exception exception) { logger.LogWarning("Context notification unavailable: {Category}", exception.GetType().Name); }
}
}