using System.Collections.Specialized; using System.Text.Json.Nodes; using XFEExtension.NetCore.XUnit.Assertions; using XFEExtension.NetCore.XUnit.Attributes; using XFEWorkflow.Abstractions; using XFEWorkflow.Core.Utilities; using XFEWorkflow.Infrastructure.Execution; using XFEWorkflow.Infrastructure.Plugins; using XFEWorkflow.Infrastructure.Storage; namespace XFEWorkflow.Test; [TestFixture] public sealed class RunPresentationTests { [Test] public async Task EventFloodCoalescesToOneSelectedWorkflowUpdate() { var buffer = new RunUpdateBuffer(); buffer.Select("selected"); await Task.WhenAll(Enumerable.Range(0, 4).Select(_ => Task.Run(() => { for (var i = 0; i < 25000; i++) buffer.Publish(new() { WorkflowId = "selected" }); }))); var final = new RunRecord { WorkflowId = "selected", Status = RunStatus.Succeeded }; buffer.Publish(final); buffer.Publish(new() { WorkflowId = "other" }); Assert.True(ReferenceEquals(final, buffer.TakeLatest())); Assert.Null(buffer.TakeLatest()); buffer.Publish(final); buffer.Select("other"); Assert.Null(buffer.TakeLatest()); buffer.Publish(final); Assert.Null(buffer.TakeLatest()); } [Test] public void LogSnapshotKeepsStableIdsAndBoundsWithoutLifecycleNoise() { var run = new RunRecord(); for (var i = 0; i < 20000; i++) run.Events.Add(new() { Kind = RunEventKind.Log, Message = "日志 " + i }); var tail = WorkflowLogService.RunEntries(run, 1000); Assert.Equal(1000, tail.Count); Assert.Equal(run.Id + "/event/19000", tail[0].Id); Assert.Equal("日志 19999", tail[^1].LogText); run.Status = RunStatus.Succeeded; run.FinishedAt = DateTimeOffset.UtcNow; tail = WorkflowLogService.RunEntries(run, 1000); Assert.Equal(1000, tail.Count); Assert.Equal(run.Id + "/event/19000", tail[0].Id); Assert.Equal(run.Id + "/event/19999", tail[^1].Id); Assert.Equal(0, WorkflowLogService.RunEntries(run, 0).Count); Assert.Throws(() => WorkflowLogService.RunEntries(run, -1)); var collection = new BulkObservableCollection(); var notifications = 0; collection.CollectionChanged += (_, e) => { Assert.Equal(NotifyCollectionChangedAction.Reset, e.Action); notifications++; }; collection.ReplaceAll(tail); Assert.Equal(1, notifications); Assert.Equal(1000, collection.Count); collection.ReplaceAll(WorkflowLogService.RunEntries(run, 5)); Assert.Equal(2, notifications); Assert.Equal(5, collection.Count); } [Test] public async Task RunnerStartupAndNotificationsDoNotUseCallersSynchronizationContext() { await using var workspace = new TestWorkspace(); await using var coordinator = new RunCoordinator(workspace.Paths, new PluginManager(workspace.Paths, workspace.State), new CredentialVault(workspace.State), new(), TestSupport.FindOutput("XFEWorkflow.Runner", "XFEWorkflow.Runner.exe")); var wrongContext = false; var events = 0; var context = new CountingContext(); coordinator.RunChanged += _ => { if (SynchronizationContext.Current == context) wrongContext = true; Interlocked.Increment(ref events); }; Task running; var previous = SynchronizationContext.Current; SynchronizationContext.SetSynchronizationContext(context); try { running = coordinator.RunAsync(TestSupport.Graph(new NodeDefinition { CapabilityId = "core.log", Parameters = new() { ["message"] = "后台线程" } })); } finally { SynchronizationContext.SetSynchronizationContext(previous); } var result = await running.WaitAsync(TimeSpan.FromSeconds(20)); Assert.Equal(RunStatus.Succeeded, result.Status, result.Error); Assert.False(wrongContext); Assert.Equal(0, context.Posts); Assert.True(events > 0); var history = (await new WorkflowLogService(workspace.Paths, coordinator, new()).HistoryAsync()).Where(e => e.RunId == result.Id).ToArray(); Assert.Equal(1, history.Length); Assert.True(history.Any(e => e.LogText == "后台线程")); } private sealed class CountingContext : SynchronizationContext { public int Posts; public override void Post(SendOrPostCallback callback, object? state) { Interlocked.Increment(ref Posts); ThreadPool.QueueUserWorkItem(_ => callback(state)); } } [Test] public async Task EmptySuccessfulRunAndLegacyLifecycleEventsStayOutOfXfeHistoryAndExport() { await using var workspace = new TestWorkspace(); await using var runs = new RunCoordinator(workspace.Paths, new PluginManager(workspace.Paths, workspace.State), new CredentialVault(workspace.State), new(), TestSupport.FindOutput("XFEWorkflow.Runner", "XFEWorkflow.Runner.exe")); var logs = new WorkflowLogService(workspace.Paths, runs, new()); runs.RunChanged += logs.Observe; var empty = await runs.RunAsync(TestSupport.Graph()); Assert.Equal(RunStatus.Succeeded, empty.Status, empty.Error); Assert.Equal(0, WorkflowLogService.RunEntries(empty).Count); Assert.Equal(0, (await logs.HistoryAsync()).Count(e => e.RunId == empty.Id)); var legacy = new RunRecord { Status = RunStatus.Succeeded, FinishedAt = DateTimeOffset.UtcNow }; foreach (var kind in new[] { RunEventKind.Started, RunEventKind.NodeStarted, RunEventKind.NodeSucceeded, RunEventKind.Finished }) legacy.Events.Add(new() { Kind = kind, Message = "内部生命周期" }); legacy.Events.Insert(2, new() { Kind = RunEventKind.Log, Message = "仅业务输出" }); var entries = WorkflowLogService.RunEntries(legacy); Assert.Equal(1, entries.Count); Assert.Equal(legacy.Id + "/event/2", entries[0].Id); var path = Path.Combine(workspace.Paths.Temp, "quiet.log"); await WorkflowLogExporter.ExportAsync(path, entries, "log", false, new()); var text = await File.ReadAllTextAsync(path); Assert.True(text.Contains("仅业务输出")); Assert.False(text.Contains("内部生命周期")); } [Test] public void FailuresAndCancellationRemainVisibleWithoutDuplicatingNodeFailure() { var run = new RunRecord { Status = RunStatus.Failed, ErrorNodeId = "broken", Error = "实际错误", FinishedAt = DateTimeOffset.UtcNow }; run.Events.Add(new() { Kind = RunEventKind.NodeFailed, NodeId = "broken", Message = "实际错误" }); Assert.Equal(1, WorkflowLogService.RunEntries(run).Count); run.Events.Clear(); Assert.Equal("实际错误", WorkflowLogService.RunEntries(run).Single().LogText); run.Status = RunStatus.Cancelled; run.Error = null; Assert.Equal(1, WorkflowLogService.RunEntries(run).Count); run.Status = RunStatus.Interrupted; Assert.Equal(1, WorkflowLogService.RunEntries(run).Count); } }