using System.Diagnostics; using System.Text.Json.Nodes; using XFEWorkflow.Abstractions; namespace XFEWorkflow.Core.Runtime; /// Cooperative node checkpoints. No UI thread or executing OS thread is suspended. public sealed class WorkflowDebugger(WorkflowDebugSettings settings, Func report) { private readonly object gate = new(); private readonly SemaphoreSlim checkpoints = new(1); private readonly Dictionary<(string Workflow, string Node), bool> breakpoints = []; private WorkflowDebugCommandKind mode = settings.BreakOnEntry ? WorkflowDebugCommandKind.StepInto : WorkflowDebugCommandKind.Continue; private int stepDepth = int.MaxValue; private WorkflowDebugState? paused; private TaskCompletionSource? resume; private TaskCompletionSource clockChanged = NewSignal(); private readonly long startedAt = Stopwatch.GetTimestamp(); private long pausedAt; private TimeSpan pausedTime; private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously); public bool Command(WorkflowDebugCommand command) { lock (gate) { if (command.Kind == WorkflowDebugCommandKind.SetBreakpoint) { if (command.WorkflowId.Length == 0 || command.NodeId.Length == 0) return false; breakpoints[(command.WorkflowId, command.NodeId)] = command.Enabled; return true; } if (command.Kind == WorkflowDebugCommandKind.Pause) { if (paused is null) mode = WorkflowDebugCommandKind.StepInto; return true; } if (command.Kind is not (WorkflowDebugCommandKind.Continue or WorkflowDebugCommandKind.StepInto or WorkflowDebugCommandKind.StepOver)) return false; if (paused is null || command.PauseId != paused.PauseId) return false; mode = command.Kind; stepDepth = paused.Depth; pausedTime += Stopwatch.GetElapsedTime(pausedAt); pausedAt = 0; paused = null; ClockUpdated(); resume!.TrySetResult(); return true; } } public async ValueTask BeforeNodeAsync(NodeDefinition node, JsonObject parameters, WorkflowExecutionContext context, CancellationToken ct) { await checkpoints.WaitAsync(ct); WorkflowDebugState? snapshot = null; Task? continuation = null; try { lock (gate) { var breakpoint = breakpoints.GetValueOrDefault((context.WorkflowId, node.Id), node.Breakpoint); var stepping = mode == WorkflowDebugCommandKind.StepInto || mode == WorkflowDebugCommandKind.StepOver && context.DebugDepth <= stepDepth; if (!breakpoint && !stepping) return; snapshot = Capture(node, parameters, context, breakpoint ? "断点" : "单步"); paused = snapshot; resume = NewSignal(); continuation = resume.Task; pausedAt = Stopwatch.GetTimestamp(); ClockUpdated(); } await report(snapshot, ct); await continuation.WaitAsync(ct); await report(new() { PauseId = snapshot.PauseId, WorkflowId = snapshot.WorkflowId, NodeId = snapshot.NodeId, NodeName = snapshot.NodeName }, ct); } finally { lock (gate) { if (snapshot is not null && paused?.PauseId == snapshot.PauseId) { pausedTime += Stopwatch.GetElapsedTime(pausedAt); pausedAt = 0; paused = null; ClockUpdated(); } } checkpoints.Release(); } } private void ClockUpdated() { var changed = clockChanged; clockChanged = NewSignal(); changed.TrySetResult(); } private (TimeSpan Elapsed, bool Paused, Task Changed) Clock() { lock (gate) { var now = pausedAt == 0 ? Stopwatch.GetTimestamp() : pausedAt; return (Stopwatch.GetElapsedTime(startedAt, now) - pausedTime, pausedAt != 0, clockChanged.Task); } } public IDisposable StartTimeout(TimeSpan duration, CancellationTokenSource target) => new DebugDeadline(this, duration, target); private async Task WaitForActiveTimeAsync(TimeSpan duration, CancellationToken ct) { var start = Clock().Elapsed; while (true) { ct.ThrowIfCancellationRequested(); var clock = Clock(); var remaining = duration - (clock.Elapsed - start); if (remaining <= TimeSpan.Zero) return; if (clock.Paused) { await clock.Changed.WaitAsync(ct); continue; } using var iteration = CancellationTokenSource.CreateLinkedTokenSource(ct); await Task.WhenAny(Task.Delay(remaining, iteration.Token), clock.Changed.WaitAsync(iteration.Token)); await iteration.CancelAsync(); } } private sealed class DebugDeadline : IDisposable { private readonly CancellationTokenSource lifetime = new(); private readonly Task watch; public DebugDeadline(WorkflowDebugger debugger, TimeSpan duration, CancellationTokenSource target) { watch = WatchAsync(); async Task WatchAsync() { try { await debugger.WaitForActiveTimeAsync(duration, lifetime.Token); target.Cancel(); } catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { } catch (ObjectDisposedException) { } } } public void Dispose() { lifetime.Cancel(); _ = watch.ContinueWith(_ => lifetime.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } private static WorkflowDebugState Capture(NodeDefinition node, JsonObject parameters, WorkflowExecutionContext context, string reason) { var truncated = false; var budget = 64_000; JsonNode? Copy(JsonNode? value, int depth = 0) { if (value is null) return null; if (depth > 8 || budget <= 0) { truncated = true; return value is JsonObject ? new JsonObject() : value is JsonArray ? new JsonArray() : JsonValue.Create("(调试预览已省略)"); } if (value is JsonValue scalar) { var text = scalar.ToJsonString(); if (text.Length > 4096 || text.Length > budget) { truncated = true; return JsonValue.Create("(数据过长,调试预览已省略)"); } budget -= text.Length; return scalar.DeepClone(); } if (value is JsonArray array) { var result = new JsonArray(); foreach (var item in array.Take(128)) { if (budget <= 0) break; result.Add(Copy(item, depth + 1)); } if (result.Count != array.Count) truncated = true; return result; } var obj = new JsonObject(); foreach (var pair in value.AsObject().Take(128)) { if (budget <= 0) break; if (pair.Key.Length > 256) { truncated = true; continue; } budget -= pair.Key.Length; obj[pair.Key] = Copy(pair.Value, depth + 1); } if (obj.Count != value.AsObject().Count) truncated = true; return obj; } var result = new WorkflowDebugState { IsPaused = true, PauseId = Guid.NewGuid().ToString("N"), WorkflowId = context.WorkflowId, NodeId = node.Id, NodeName = node.Name.Length == 0 ? node.CapabilityId : node.Name, Depth = context.DebugDepth, Reason = reason, Parameters = Copy(parameters)?.AsObject() ?? [], Variables = Copy(context.Variables)?.AsObject() ?? [], Inputs = Copy(context.Inputs)?.AsObject() ?? [] }; foreach (var pair in context.NodeOutputs.Take(64)) result.NodeOutputs[pair.Key] = Copy(pair.Value); if (result.NodeOutputs.Count != context.NodeOutputs.Count) truncated = true; result.Truncated = truncated; return result; } }