using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEWorkflow.Abstractions;
namespace XFEWorkflow.Infrastructure.Communication;
public sealed class RpcMessage
{
public string Type { get; set; } = "";
public string Id { get; set; } = "";
public string Method { get; set; } = "";
public JsonNode? Payload { get; set; }
public string? Error { get; set; }
}
public sealed class RpcPeer : IAsyncDisposable
{
public const int MaxMessageCharacters = 8 * 1024 * 1024;
private readonly Stream stream;
private readonly StreamReader reader;
private readonly StreamWriter writer;
private readonly SemaphoreSlim writeGate = new(1);
private readonly ConcurrentDictionary<string, TaskCompletionSource<JsonNode?>> pending = [];
private readonly CancellationTokenSource lifetime = new();
private Task? receiveTask;
private static readonly JsonSerializerOptions Compact = new(WorkflowJson.Options) { WriteIndented = false };
public Func<string, JsonNode?, CancellationToken, Task<JsonNode?>>? RequestReceived { get; set; }
public Func<string, JsonNode?, ValueTask>? EventReceived { get; set; }
public Task Completion => receiveTask ?? Task.CompletedTask;
public RpcPeer(Stream stream)
{
this.stream = stream;
reader = new(stream, Encoding.UTF8, false, 8192, true);
writer = new(stream, new UTF8Encoding(false), 8192, true) { AutoFlush = true };
}
public void Start() => receiveTask ??= ReceiveAsync();
public async Task<T?> RequestAsync<T>(string method, object? parameters = null, CancellationToken ct = default)
{
var id = Guid.NewGuid().ToString("N");
var completion = new TaskCompletionSource<JsonNode?>(TaskCreationOptions.RunContinuationsAsynchronously);
if (!pending.TryAdd(id, completion)) throw new InvalidOperationException();
using var registration = ct.Register(() => completion.TrySetCanceled(ct));
try
{
await SendAsync(new() { Type = "request", Id = id, Method = method, Payload = JsonSerializer.SerializeToNode(parameters, Compact) }, ct);
var result = await completion.Task;
return result is null ? default : result.Deserialize<T>(WorkflowJson.Options);
}
finally { pending.TryRemove(id, out _); }
}
public ValueTask EventAsync(string method, object? payload, CancellationToken ct = default) =>
new(SendAsync(new() { Type = "event", Method = method, Payload = JsonSerializer.SerializeToNode(payload, Compact) }, ct));
private async Task SendAsync(RpcMessage message, CancellationToken ct)
{
var json = JsonSerializer.Serialize(message, Compact);
if (json.Length > MaxMessageCharacters) throw new InvalidDataException("进程通信消息超过 8 MiB;请缩小图像模板或将工作流拆分为子流程。");
await writeGate.WaitAsync(ct);
try { await writer.WriteLineAsync(json.AsMemory(), ct); }
finally { writeGate.Release(); }
}
private async Task ReceiveAsync()
{
Exception failure = new EndOfStreamException("执行进程连接已关闭");
try
{
while (!lifetime.IsCancellationRequested && await reader.ReadLineAsync(lifetime.Token) is { } line)
{
if (line.Length > MaxMessageCharacters) throw new InvalidDataException("进程通信消息过大");
var message = JsonSerializer.Deserialize<RpcMessage>(line, Compact) ?? throw new InvalidDataException("无效的进程通信消息");
switch (message.Type)
{
case "response":
if (pending.TryGetValue(message.Id, out var completion))
{
if (message.Error is not null) completion.TrySetException(new InvalidOperationException(message.Error));
else completion.TrySetResult(message.Payload);
}
break;
case "event":
if (EventReceived is { } handler) await handler(message.Method, message.Payload);
break;
case "request":
_ = HandleRequestAsync(message);
break;
}
}
}
catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
catch (Exception ex) { failure = ex; }
finally { foreach (var item in pending.Values) item.TrySetException(failure); }
}
private async Task HandleRequestAsync(RpcMessage message)
{
var reply = new RpcMessage { Type = "response", Id = message.Id };
try
{
reply.Payload = RequestReceived is { } handler
? await Task.Run(() => handler(message.Method, message.Payload, lifetime.Token), lifetime.Token)
: throw new InvalidOperationException("未注册调用处理程序");
}
catch (Exception ex) { reply.Error = ex.Message; }
try { await SendAsync(reply, lifetime.Token); }
catch (Exception) when (lifetime.IsCancellationRequested || !stream.CanWrite) { }
catch (IOException) { }
}
public async ValueTask DisposeAsync()
{
await lifetime.CancelAsync();
try { writer.Dispose(); }
catch (Exception ex) when (ex is IOException or ObjectDisposedException) { }
await stream.DisposeAsync();
if (receiveTask is not null) { try { await receiveTask; } catch (IOException) { } }
reader.Dispose(); lifetime.Dispose();
}
}
public sealed class RunRequest
{
public WorkflowDefinition Workflow { get; set; } = new();
public string RunId { get; set; } = "";
public string WorkspaceRoot { get; set; } = "";
public JsonObject Inputs { get; set; } = [];
public List<InstalledPlugin> Plugins { get; set; } = [];
public string? TriggerCapability { get; set; }
public string? EntryNodeId { get; set; }
public JsonObject TriggerParameters { get; set; } = [];
public WorkflowDebugSettings? Debug { get; set; }
}
public sealed class RunResponse
{
public RunStatus Status { get; set; }
public JsonObject Outputs { get; set; } = [];
public string? Error { get; set; }
public string? NodeId { get; set; }
}
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEWorkflow.Abstractions;
namespace XFEWorkflow.Infrastructure.Communication;
public sealed class RpcMessage
{
public string Type { get; set; } = "";
public string Id { get; set; } = "";
public string Method { get; set; } = "";
public JsonNode? Payload { get; set; }
public string? Error { get; set; }
}
public sealed class RpcPeer : IAsyncDisposable
{
public const int MaxMessageCharacters = 8 * 1024 * 1024;
private readonly Stream stream;
private readonly StreamReader reader;
private readonly StreamWriter writer;
private readonly SemaphoreSlim writeGate = new(1);
private readonly ConcurrentDictionary<string, TaskCompletionSource<JsonNode?>> pending = [];
private readonly CancellationTokenSource lifetime = new();
private Task? receiveTask;
private static readonly JsonSerializerOptions Compact = new(WorkflowJson.Options) { WriteIndented = false };
public Func<string, JsonNode?, CancellationToken, Task<JsonNode?>>? RequestReceived { get; set; }
public Func<string, JsonNode?, ValueTask>? EventReceived { get; set; }
public Task Completion => receiveTask ?? Task.CompletedTask;
public RpcPeer(Stream stream)
{
this.stream = stream;
reader = new(stream, Encoding.UTF8, false, 8192, true);
writer = new(stream, new UTF8Encoding(false), 8192, true) { AutoFlush = true };
}
public void Start() => receiveTask ??= ReceiveAsync();
public async Task<T?> RequestAsync<T>(string method, object? parameters = null, CancellationToken ct = default)
{
var id = Guid.NewGuid().ToString("N");
var completion = new TaskCompletionSource<JsonNode?>(TaskCreationOptions.RunContinuationsAsynchronously);
if (!pending.TryAdd(id, completion)) throw new InvalidOperationException();
using var registration = ct.Register(() => completion.TrySetCanceled(ct));
try
{
await SendAsync(new() { Type = "request", Id = id, Method = method, Payload = JsonSerializer.SerializeToNode(parameters, Compact) }, ct);
var result = await completion.Task;
return result is null ? default : result.Deserialize<T>(WorkflowJson.Options);
}
finally { pending.TryRemove(id, out _); }
}
public ValueTask EventAsync(string method, object? payload, CancellationToken ct = default) =>
new(SendAsync(new() { Type = "event", Method = method, Payload = JsonSerializer.SerializeToNode(payload, Compact) }, ct));
private async Task SendAsync(RpcMessage message, CancellationToken ct)
{
var json = JsonSerializer.Serialize(message, Compact);
if (json.Length > MaxMessageCharacters) throw new InvalidDataException("进程通信消息超过 8 MiB;请缩小图像模板或将工作流拆分为子流程。");
await writeGate.WaitAsync(ct);
try { await writer.WriteLineAsync(json.AsMemory(), ct); }
finally { writeGate.Release(); }
}
private async Task ReceiveAsync()
{
Exception failure = new EndOfStreamException("执行进程连接已关闭");
try
{
while (!lifetime.IsCancellationRequested && await reader.ReadLineAsync(lifetime.Token) is { } line)
{
if (line.Length > MaxMessageCharacters) throw new InvalidDataException("进程通信消息过大");
var message = JsonSerializer.Deserialize<RpcMessage>(line, Compact) ?? throw new InvalidDataException("无效的进程通信消息");
switch (message.Type)
{
case "response":
if (pending.TryGetValue(message.Id, out var completion))
{
if (message.Error is not null) completion.TrySetException(new InvalidOperationException(message.Error));
else completion.TrySetResult(message.Payload);
}
break;
case "event":
if (EventReceived is { } handler) await handler(message.Method, message.Payload);
break;
case "request":
_ = HandleRequestAsync(message);
break;
}
}
}
catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
catch (Exception ex) { failure = ex; }
finally { foreach (var item in pending.Values) item.TrySetException(failure); }
}
private async Task HandleRequestAsync(RpcMessage message)
{
var reply = new RpcMessage { Type = "response", Id = message.Id };
try
{
reply.Payload = RequestReceived is { } handler
? await Task.Run(() => handler(message.Method, message.Payload, lifetime.Token), lifetime.Token)
: throw new InvalidOperationException("未注册调用处理程序");
}
catch (Exception ex) { reply.Error = ex.Message; }
try { await SendAsync(reply, lifetime.Token); }
catch (Exception) when (lifetime.IsCancellationRequested || !stream.CanWrite) { }
catch (IOException) { }
}
public async ValueTask DisposeAsync()
{
await lifetime.CancelAsync();
try { writer.Dispose(); }
catch (Exception ex) when (ex is IOException or ObjectDisposedException) { }
await stream.DisposeAsync();
if (receiveTask is not null) { try { await receiveTask; } catch (IOException) { } }
reader.Dispose(); lifetime.Dispose();
}
}
public sealed class RunRequest
{
public WorkflowDefinition Workflow { get; set; } = new();
public string RunId { get; set; } = "";
public string WorkspaceRoot { get; set; } = "";
public JsonObject Inputs { get; set; } = [];
public List<InstalledPlugin> Plugins { get; set; } = [];
public string? TriggerCapability { get; set; }
public string? EntryNodeId { get; set; }
public JsonObject TriggerParameters { get; set; } = [];
public WorkflowDebugSettings? Debug { get; set; }
}
public sealed class RunResponse
{
public RunStatus Status { get; set; }
public JsonObject Outputs { get; set; } = [];
public string? Error { get; set; }
public string? NodeId { get; set; }
}