plcsharp/PLCSharpWpf/Models/ProjectPipe.cs

112 lines
4.4 KiB
C#

using System.IO;
using System.IO.Pipes;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading;
namespace PLCSharp.Models;
public sealed class ProjectPipe : IDisposable
{
private readonly CancellationTokenSource stopping = new();
private readonly Mutex marker;
private readonly string name;
private readonly Func<JsonObject, JsonNode> handle;
private static readonly UTF8Encoding Utf8 = new(false);
private static string Name(string root)
{
var path = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)).ToUpperInvariant();
using var user = WindowsIdentity.GetCurrent();
var identity = user.User.Value;
return "PLCSharp-" + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(identity + "|" + path)));
}
internal static T Synchronized<T>(string root, Func<T> action)
{
using var mutex = new Mutex(false, Name(root) + "-access");
bool acquired;
try { acquired = mutex.WaitOne(TimeSpan.FromSeconds(15)); }
catch (AbandonedMutexException) { acquired = true; }
if (!acquired) throw new IOException("Project is busy. Retry the request.");
try { return action(); }
finally { mutex.ReleaseMutex(); }
}
public static JsonNode Call(string root, JsonObject request, Func<JsonNode> offline)
{
var result = Synchronized(root, () =>
{
if (!Mutex.TryOpenExisting(Name(root) + "-editor", out var active)) return offline();
active.Dispose();
return null;
});
return result ?? TryCall(root, request) ?? throw new IOException("Editor closed. Retry the request.");
}
public ProjectPipe(string root, Func<JsonObject, JsonNode> handle)
{
name = Name(root);
this.handle = handle;
marker = Synchronized(root, () =>
{
var registration = new Mutex(false, name + "-editor", out var created);
if (created) return registration;
registration.Dispose();
throw new IOException("工程已在另一个编辑器中打开。");
});
_ = ServeAsync(stopping.Token);
}
private async Task ServeAsync(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
using var pipe = new NamedPipeServerStream(name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
await pipe.WaitForConnectionAsync(token).ConfigureAwait(false);
using var input = new StreamReader(pipe, Utf8, leaveOpen: true);
using var output = new StreamWriter(pipe, Utf8, leaveOpen: true) { AutoFlush = true };
JsonObject response;
try
{
var line = await input.ReadLineAsync(token).ConfigureAwait(false);
response = new() { ["result"] = handle(JsonNode.Parse(line).AsObject()) };
}
catch (Exception ex) { response = new() { ["error"] = ex.GetBaseException().Message }; }
await output.WriteLineAsync(response.ToJsonString()).ConfigureAwait(false);
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { return; }
catch (IOException) { if (!token.IsCancellationRequested) await Task.Delay(50).ConfigureAwait(false); }
}
}
public static JsonNode TryCall(string root, JsonObject request)
{
string name = Name(root);
if (!Mutex.TryOpenExisting(name + "-editor", out var active)) return null;
using (active)
using (var pipe = new NamedPipeClientStream(".", name, PipeDirection.InOut, PipeOptions.CurrentUserOnly))
{
pipe.Connect(5000);
using var input = new StreamReader(pipe, Utf8, leaveOpen: true);
using var output = new StreamWriter(pipe, Utf8, leaveOpen: true) { AutoFlush = true };
output.WriteLine(request.ToJsonString());
var response = JsonNode.Parse(input.ReadLine() ?? throw new IOException("Editor disconnected."));
if (response["error"] != null) throw new InvalidOperationException((string)response["error"]);
return response["result"];
}
}
public void Dispose()
{
stopping.Cancel();
marker.Dispose();
}
}