mirror of
https://github.com/goatcorp/Dalamud.git
synced 2025-12-12 18:27:23 +01:00
feat: Dalamud RPC service
A draft for a simple RPC service for Dalamud. Enables use of Dalamud URIs, to be added later.
This commit is contained in:
parent
62b9c1f2a1
commit
78ed4a2b01
12 changed files with 911 additions and 1 deletions
107
Dalamud.Test/Pipes/DalamudUriTests.cs
Normal file
107
Dalamud.Test/Pipes/DalamudUriTests.cs
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
using System;
|
||||
using System.Linq;
|
||||
|
||||
using Dalamud.Networking.Pipes;
|
||||
using Xunit;
|
||||
|
||||
namespace Dalamud.Test.Pipes
|
||||
{
|
||||
public class DalamudUriTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("https://www.google.com/", false)]
|
||||
[InlineData("dalamud://PluginInstaller/Dalamud.FindAnything", true)]
|
||||
public void ValidatesScheme(string uri, bool valid)
|
||||
{
|
||||
Action act = () => { _ = DalamudUri.FromUri(uri); };
|
||||
|
||||
var ex = Record.Exception(act);
|
||||
if (valid)
|
||||
{
|
||||
Assert.Null(ex);
|
||||
}
|
||||
else
|
||||
{
|
||||
Assert.NotNull(ex);
|
||||
Assert.IsType<ArgumentOutOfRangeException>(ex);
|
||||
}
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("dalamud://PluginInstaller/Dalamud.FindAnything", "plugininstaller")]
|
||||
[InlineData("dalamud://Plugin/Dalamud.FindAnything/OpenWindow", "plugin")]
|
||||
[InlineData("dalamud://Test", "test")]
|
||||
public void ExtractsNamespace(string uri, string expectedNamespace)
|
||||
{
|
||||
var dalamudUri = DalamudUri.FromUri(uri);
|
||||
Assert.Equal(expectedNamespace, dalamudUri.Namespace);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("dalamud://foo/bar/baz/qux/?cow=moo", "/bar/baz/qux/")]
|
||||
[InlineData("dalamud://foo/bar/baz/qux?cow=moo", "/bar/baz/qux")]
|
||||
[InlineData("dalamud://foo/bar/baz", "/bar/baz")]
|
||||
[InlineData("dalamud://foo/bar", "/bar")]
|
||||
[InlineData("dalamud://foo/bar/", "/bar/")]
|
||||
[InlineData("dalamud://foo/", "/")]
|
||||
public void ExtractsPath(string uri, string expectedPath)
|
||||
{
|
||||
var dalamudUri = DalamudUri.FromUri(uri);
|
||||
Assert.Equal(expectedPath, dalamudUri.Path);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("dalamud://foo/bar/baz/qux/?cow=moo#frag", "/bar/baz/qux/?cow=moo#frag")]
|
||||
[InlineData("dalamud://foo/bar/baz/qux/?cow=moo", "/bar/baz/qux/?cow=moo")]
|
||||
[InlineData("dalamud://foo/bar/baz/qux?cow=moo", "/bar/baz/qux?cow=moo")]
|
||||
[InlineData("dalamud://foo/bar/baz", "/bar/baz")]
|
||||
[InlineData("dalamud://foo/bar?cow=moo", "/bar?cow=moo")]
|
||||
[InlineData("dalamud://foo/bar", "/bar")]
|
||||
[InlineData("dalamud://foo/bar/?cow=moo", "/bar/?cow=moo")]
|
||||
[InlineData("dalamud://foo/bar/", "/bar/")]
|
||||
[InlineData("dalamud://foo/?cow=moo#chicken", "/?cow=moo#chicken")]
|
||||
[InlineData("dalamud://foo/?cow=moo", "/?cow=moo")]
|
||||
[InlineData("dalamud://foo/", "/")]
|
||||
public void ExtractsData(string uri, string expectedData)
|
||||
{
|
||||
var dalamudUri = DalamudUri.FromUri(uri);
|
||||
|
||||
Assert.Equal(expectedData, dalamudUri.Data);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("dalamud://foo/bar", 0)]
|
||||
[InlineData("dalamud://foo/bar?cow=moo", 1)]
|
||||
[InlineData("dalamud://foo/bar?cow=moo&wolf=awoo", 2)]
|
||||
[InlineData("dalamud://foo/bar?cow=moo&wolf=awoo&cat", 3)]
|
||||
public void ExtractsQueryParams(string uri, int queryCount)
|
||||
{
|
||||
var dalamudUri = DalamudUri.FromUri(uri);
|
||||
Assert.Equal(queryCount, dalamudUri.QueryParams.Count);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("dalamud://foo/bar/baz/qux/meh/?foo=bar", 5, true)]
|
||||
[InlineData("dalamud://foo/bar/baz/qux/meh/", 5, true)]
|
||||
[InlineData("dalamud://foo/bar/baz/qux/meh", 5)]
|
||||
[InlineData("dalamud://foo/bar/baz/qux", 4)]
|
||||
[InlineData("dalamud://foo/bar/baz", 3)]
|
||||
[InlineData("dalamud://foo/bar/", 2)]
|
||||
[InlineData("dalamud://foo/bar", 2)]
|
||||
public void ExtractsSegments(string uri, int segmentCount, bool finalSegmentEndsWithSlash = false)
|
||||
{
|
||||
var dalamudUri = DalamudUri.FromUri(uri);
|
||||
var segments = dalamudUri.Segments;
|
||||
|
||||
// First segment must always be `/`
|
||||
Assert.Equal("/", segments[0]);
|
||||
|
||||
Assert.Equal(segmentCount, segments.Length);
|
||||
|
||||
if (finalSegmentEndsWithSlash)
|
||||
{
|
||||
Assert.EndsWith("/", segments.Last());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -81,6 +81,7 @@
|
|||
<PackageReference Include="Serilog.Sinks.Console" />
|
||||
<PackageReference Include="Serilog.Sinks.File" />
|
||||
<PackageReference Include="sqlite-net-pcl" />
|
||||
<PackageReference Include="StreamJsonRpc" />
|
||||
<PackageReference Include="StyleCop.Analyzers">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
|
|
|
|||
53
Dalamud/Networking/Pipes/Api/PluginLinkHandler.cs
Normal file
53
Dalamud/Networking/Pipes/Api/PluginLinkHandler.cs
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
using System.Linq;
|
||||
|
||||
using Dalamud.IoC;
|
||||
using Dalamud.IoC.Internal;
|
||||
using Dalamud.Networking.Pipes.Internal;
|
||||
using Dalamud.Plugin.Internal.Types;
|
||||
using Dalamud.Plugin.Services;
|
||||
|
||||
namespace Dalamud.Networking.Pipes.Api;
|
||||
|
||||
/// <inheritdoc cref="IPluginLinkHandler" />
|
||||
[PluginInterface]
|
||||
[ServiceManager.ScopedService]
|
||||
[ResolveVia<IPluginLinkHandler>]
|
||||
public class PluginLinkHandler : IInternalDisposableService, IPluginLinkHandler
|
||||
{
|
||||
private readonly LinkHandlerService linkHandler;
|
||||
private readonly LocalPlugin localPlugin;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PluginLinkHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="localPlugin">The plugin to bind this service to.</param>
|
||||
/// <param name="linkHandler">The central link handler.</param>
|
||||
internal PluginLinkHandler(LocalPlugin localPlugin, LinkHandlerService linkHandler)
|
||||
{
|
||||
this.linkHandler = linkHandler;
|
||||
this.localPlugin = localPlugin;
|
||||
|
||||
this.linkHandler.Register("plugin", this.HandleUri);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public event IPluginLinkHandler.PluginUriReceived? OnUriReceived;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void DisposeService()
|
||||
{
|
||||
this.OnUriReceived = null;
|
||||
this.linkHandler.Unregister("plugin", this.HandleUri);
|
||||
}
|
||||
|
||||
private void HandleUri(DalamudUri uri)
|
||||
{
|
||||
var target = uri.Path.Split("/").FirstOrDefault();
|
||||
if (target == null || !string.Equals(target, this.localPlugin.InternalName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
this.OnUriReceived?.Invoke(uri);
|
||||
}
|
||||
}
|
||||
102
Dalamud/Networking/Pipes/DalamudUri.cs
Normal file
102
Dalamud/Networking/Pipes/DalamudUri.cs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Web;
|
||||
|
||||
namespace Dalamud.Networking.Pipes;
|
||||
|
||||
/// <summary>
|
||||
/// A Dalamud Uri, in the format:
|
||||
/// <code>dalamud://{NAMESPACE}/{ARBITRARY}</code>
|
||||
/// </summary>
|
||||
public record DalamudUri
|
||||
{
|
||||
private readonly Uri rawUri;
|
||||
|
||||
private DalamudUri(Uri uri)
|
||||
{
|
||||
if (uri.Scheme != "dalamud")
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(nameof(uri), "URI must be of scheme dalamud.");
|
||||
}
|
||||
|
||||
this.rawUri = uri;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the namespace that this URI should be routed to. Generally a high level component like "PluginInstaller".
|
||||
/// </summary>
|
||||
public string Namespace => this.rawUri.Authority;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the raw (untargeted) path and query params for this URI.
|
||||
/// </summary>
|
||||
public string Data =>
|
||||
this.rawUri.GetComponents(UriComponents.PathAndQuery | UriComponents.Fragment, UriFormat.UriEscaped);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the raw (untargeted) path for this URI.
|
||||
/// </summary>
|
||||
public string Path => this.rawUri.AbsolutePath;
|
||||
|
||||
/// <summary>
|
||||
/// Gets a list of segments based on the provided Data element.
|
||||
/// </summary>
|
||||
public string[] Segments => this.GetDataSegments();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the raw query parameters for this URI, if any.
|
||||
/// </summary>
|
||||
public string Query => this.rawUri.Query;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the query params (as a parsed NameValueCollection) in this URI.
|
||||
/// </summary>
|
||||
public NameValueCollection QueryParams => HttpUtility.ParseQueryString(this.Query);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the fragment (if one is specified) in this URI.
|
||||
/// </summary>
|
||||
public string Fragment => this.rawUri.Fragment;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override string ToString() => this.rawUri.ToString();
|
||||
|
||||
private string[] GetDataSegments()
|
||||
{
|
||||
// reimplementation of the System.URI#Segments, under MIT license.
|
||||
var path = this.Path;
|
||||
|
||||
var segments = new List<string>();
|
||||
var current = 0;
|
||||
while (current < path.Length)
|
||||
{
|
||||
var next = path.IndexOf('/', current);
|
||||
if (next == -1)
|
||||
{
|
||||
next = path.Length - 1;
|
||||
}
|
||||
|
||||
segments.Add(path.Substring(current, (next - current) + 1));
|
||||
current = next + 1;
|
||||
}
|
||||
|
||||
return segments.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Build a DalamudURI from a given URI.
|
||||
/// </summary>
|
||||
/// <param name="uri">The URI to convert to a Dalamud URI.</param>
|
||||
/// <returns>Returns a DalamudUri.</returns>
|
||||
public static DalamudUri FromUri(Uri uri)
|
||||
{
|
||||
return new DalamudUri(uri);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Build a DalamudURI from a URI in string format.
|
||||
/// </summary>
|
||||
/// <param name="uri">The URI to convert to a Dalamud URI.</param>
|
||||
/// <returns>Returns a DalamudUri.</returns>
|
||||
public static DalamudUri FromUri(string uri) => FromUri(new Uri(uri));
|
||||
}
|
||||
94
Dalamud/Networking/Pipes/Internal/ClientHelloService.cs
Normal file
94
Dalamud/Networking/Pipes/Internal/ClientHelloService.cs
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
using System.Threading.Tasks;
|
||||
|
||||
using Dalamud.Game;
|
||||
using Dalamud.Game.ClientState;
|
||||
using Dalamud.Networking.Pipes.Rpc;
|
||||
using Dalamud.Utility;
|
||||
|
||||
namespace Dalamud.Networking.Pipes.Internal;
|
||||
|
||||
/// <summary>
|
||||
/// A minimal service to respond with information about this client.
|
||||
/// </summary>
|
||||
[ServiceManager.EarlyLoadedService]
|
||||
internal sealed class ClientHelloService : IInternalDisposableService
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClientHelloService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="rpcHostService">Injected host service.</param>
|
||||
[ServiceManager.ServiceConstructor]
|
||||
public ClientHelloService(RpcHostService rpcHostService)
|
||||
{
|
||||
rpcHostService.AddMethod("hello", this.HandleHello);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handle a hello request.
|
||||
/// </summary>
|
||||
/// <param name="request">.</param>
|
||||
/// <returns>Respond with information.</returns>
|
||||
public async Task<ClientHelloResponse> HandleHello(ClientHelloRequest request)
|
||||
{
|
||||
var framework = await Service<Framework>.GetAsync();
|
||||
var dalamud = await Service<Dalamud>.GetAsync();
|
||||
var clientState = await Service<ClientState>.GetAsync();
|
||||
|
||||
var response = await framework.RunOnFrameworkThread(() => new ClientHelloResponse
|
||||
{
|
||||
ApiVersion = "1.0",
|
||||
DalamudVersion = Util.GetScmVersion(),
|
||||
GameVersion = dalamud.StartInfo.GameVersion?.ToString() ?? "Unknown",
|
||||
PlayerName = clientState.IsLoggedIn ? clientState.LocalPlayer?.Name.ToString() ?? "Unknown" : null,
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void DisposeService()
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A request from a client to say hello.
|
||||
/// </summary>
|
||||
internal record ClientHelloRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the API version this client is expecting.
|
||||
/// </summary>
|
||||
public string ApiVersion { get; init; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the user agent of the client.
|
||||
/// </summary>
|
||||
public string UserAgent { get; init; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A response from Dalamud to a hello request.
|
||||
/// </summary>
|
||||
internal record ClientHelloResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the API version this server has offered.
|
||||
/// </summary>
|
||||
public string? ApiVersion { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current Dalamud version.
|
||||
/// </summary>
|
||||
public string? DalamudVersion { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current game version.
|
||||
/// </summary>
|
||||
public string? GameVersion { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the player name, or null if the player isn't logged in.
|
||||
/// </summary>
|
||||
public string? PlayerName { get; set; }
|
||||
}
|
||||
129
Dalamud/Networking/Pipes/Internal/LinkHandlerService.cs
Normal file
129
Dalamud/Networking/Pipes/Internal/LinkHandlerService.cs
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Dalamud.Logging.Internal;
|
||||
using Dalamud.Networking.Pipes.Rpc;
|
||||
|
||||
namespace Dalamud.Networking.Pipes.Internal;
|
||||
|
||||
/// <summary>
|
||||
/// A service responsible for handling Dalamud URIs and dispatching them accordingly.
|
||||
/// </summary>
|
||||
[ServiceManager.EarlyLoadedService]
|
||||
internal class LinkHandlerService : IInternalDisposableService
|
||||
{
|
||||
private readonly ModuleLog log = new("LinkHandler");
|
||||
|
||||
// key: namespace (e.g. "plugin" or "PluginInstaller") -> list of handlers
|
||||
private readonly ConcurrentDictionary<string, List<Action<DalamudUri>>> handlers
|
||||
= new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LinkHandlerService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="rpcHostService">The injected RPC host service.</param>
|
||||
[ServiceManager.ServiceConstructor]
|
||||
public LinkHandlerService(RpcHostService rpcHostService)
|
||||
{
|
||||
rpcHostService.AddMethod("handleLink", this.HandleLinkCall);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void DisposeService()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register a handler for a namespace. All URIs with this namespace will be dispatched to the handler.
|
||||
/// </summary>
|
||||
/// <param name="ns">The namespace to use for this subscription.</param>
|
||||
/// <param name="handler">The command handler.</param>
|
||||
public void Register(string ns, Action<DalamudUri> handler)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(ns))
|
||||
throw new ArgumentNullException(nameof(ns));
|
||||
|
||||
var list = this.handlers.GetOrAdd(ns, _ => []);
|
||||
lock (list)
|
||||
{
|
||||
list.Add(handler);
|
||||
}
|
||||
|
||||
this.log.Verbose("Registered handler for {Namespace}", ns);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unregister a handler.
|
||||
/// </summary>
|
||||
/// <param name="ns">The namespace to use for this subscription.</param>
|
||||
/// <param name="handler">The command handler.</param>
|
||||
public void Unregister(string ns, Action<DalamudUri> handler)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(ns))
|
||||
return;
|
||||
|
||||
if (!this.handlers.TryGetValue(ns, out var list))
|
||||
return;
|
||||
|
||||
lock (list)
|
||||
{
|
||||
list.RemoveAll(x => x == handler);
|
||||
}
|
||||
|
||||
if (list.Count == 0)
|
||||
this.handlers.TryRemove(ns, out _);
|
||||
|
||||
this.log.Verbose("Unregistered handler for {Namespace}", ns);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Dispatch a URI to matching handlers.
|
||||
/// </summary>
|
||||
/// <param name="uri">The URI to parse and dispatch.</param>
|
||||
public void Dispatch(DalamudUri uri)
|
||||
{
|
||||
this.log.Information("Received URI: {Uri}", uri.ToString());
|
||||
|
||||
var ns = uri.Namespace;
|
||||
if (!this.handlers.TryGetValue(ns, out var list))
|
||||
return;
|
||||
|
||||
Action<DalamudUri>[] snapshot;
|
||||
lock (list)
|
||||
{
|
||||
snapshot = list.ToArray();
|
||||
}
|
||||
|
||||
foreach (var h in snapshot)
|
||||
{
|
||||
try
|
||||
{
|
||||
h(uri);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.log.Warning(e, "Link handler threw for {UriPath}", uri.Path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The RPC-invokable link handler.
|
||||
/// </summary>
|
||||
/// <param name="uri">A plain-text URI to parse.</param>
|
||||
public void HandleLinkCall(string uri)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(uri))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
var du = DalamudUri.FromUri(uri);
|
||||
this.Dispatch(du);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// swallow parse errors; clients shouldn't crash the host
|
||||
}
|
||||
}
|
||||
}
|
||||
167
Dalamud/Networking/Pipes/Rpc/PipeRpcHost.cs
Normal file
167
Dalamud/Networking/Pipes/Rpc/PipeRpcHost.cs
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Pipes;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Principal;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Dalamud.Logging.Internal;
|
||||
using Dalamud.Utility;
|
||||
|
||||
namespace Dalamud.Networking.Pipes.Rpc;
|
||||
|
||||
/// <summary>
|
||||
/// Simple multi-client JSON-RPC named pipe host using StreamJsonRpc.
|
||||
/// </summary>
|
||||
internal class PipeRpcHost : IDisposable
|
||||
{
|
||||
private readonly ModuleLog log = new("RPC/Host");
|
||||
|
||||
private readonly RpcServiceRegistry registry = new();
|
||||
private readonly CancellationTokenSource cts = new();
|
||||
private readonly ConcurrentDictionary<Guid, RpcConnection> sessions = new();
|
||||
private Task? acceptLoopTask;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PipeRpcHost"/> class.
|
||||
/// </summary>
|
||||
/// <param name="pipeName">The pipe name to create.</param>
|
||||
public PipeRpcHost(string? pipeName = null)
|
||||
{
|
||||
// Default pipe name based on current process ID for uniqueness per Dalamud instance.
|
||||
this.PipeName = pipeName ?? $"DalamudRPC.{Environment.ProcessId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the name of the named pipe this RPC host is using.
|
||||
/// </summary>
|
||||
public string PipeName { get; }
|
||||
|
||||
/// <summary>Adds a local object exposing RPC methods callable by clients.</summary>
|
||||
/// <param name="service">An arbitrary service object that will be introspected to add to RPC.</param>
|
||||
public void AddService(object service) => this.registry.AddService(service);
|
||||
|
||||
/// <summary>
|
||||
/// Adds a standalone JSON-RPC method callable by clients.
|
||||
/// </summary>
|
||||
/// <param name="name">The name to add.</param>
|
||||
/// <param name="handler">The delegate that acts as the handler.</param>
|
||||
public void AddMethod(string name, Delegate handler) => this.registry.AddMethod(name, handler);
|
||||
|
||||
/// <summary>Starts accepting client connections.</summary>
|
||||
public void Start()
|
||||
{
|
||||
if (this.acceptLoopTask != null) return;
|
||||
this.acceptLoopTask = Task.Run(this.AcceptLoopAsync);
|
||||
}
|
||||
|
||||
/// <summary>Invoke an RPC request on a specific client expecting a result.</summary>
|
||||
/// <param name="clientId">The client ID to invoke.</param>
|
||||
/// <param name="method">The method to invoke.</param>
|
||||
/// <param name="arguments">Any arguments to invoke.</param>
|
||||
/// <returns>An optional return based on the specified RPC.</returns>
|
||||
/// <typeparam name="T">The expected response type.</typeparam>
|
||||
public Task<T> InvokeClientAsync<T>(Guid clientId, string method, params object[] arguments)
|
||||
{
|
||||
if (!this.sessions.TryGetValue(clientId, out var session))
|
||||
throw new KeyNotFoundException($"No client {clientId}");
|
||||
|
||||
return session.Rpc.InvokeAsync<T>(method, arguments);
|
||||
}
|
||||
|
||||
/// <summary>Send a notification to all connected clients (no response expected).</summary>
|
||||
/// <param name="method">The method name to broadcast.</param>
|
||||
/// <param name="arguments">The arguments to broadcast.</param>
|
||||
/// <returns>Returns a Task when completed.</returns>
|
||||
public Task BroadcastNotifyAsync(string method, params object[] arguments)
|
||||
{
|
||||
var list = this.sessions.Values;
|
||||
var tasks = new List<Task>(list.Count);
|
||||
foreach (var s in list)
|
||||
{
|
||||
tasks.Add(s.Rpc.NotifyAsync(method, arguments));
|
||||
}
|
||||
|
||||
return Task.WhenAll(tasks);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a list of connected client IDs.
|
||||
/// </summary>
|
||||
/// <returns>Connected client IDs.</returns>
|
||||
public IReadOnlyCollection<Guid> GetClientIds() => this.sessions.Keys.AsReadOnlyCollection();
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
this.cts.Cancel();
|
||||
this.acceptLoopTask?.Wait(1000);
|
||||
|
||||
foreach (var kv in this.sessions)
|
||||
{
|
||||
kv.Value.Dispose();
|
||||
}
|
||||
|
||||
this.sessions.Clear();
|
||||
this.cts.Dispose();
|
||||
this.log.Information("PipeRpcHost disposed ({Pipe})", this.PipeName);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
private PipeSecurity BuildPipeSecurity()
|
||||
{
|
||||
var ps = new PipeSecurity();
|
||||
ps.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().User!, PipeAccessRights.FullControl, AccessControlType.Allow));
|
||||
|
||||
return ps;
|
||||
}
|
||||
|
||||
private async Task AcceptLoopAsync()
|
||||
{
|
||||
this.log.Information("PipeRpcHost starting on pipe {Pipe}", this.PipeName);
|
||||
var token = this.cts.Token;
|
||||
var security = this.BuildPipeSecurity();
|
||||
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
NamedPipeServerStream? server = null;
|
||||
try
|
||||
{
|
||||
server = NamedPipeServerStreamAcl.Create(
|
||||
this.PipeName,
|
||||
PipeDirection.InOut,
|
||||
NamedPipeServerStream.MaxAllowedServerInstances,
|
||||
PipeTransmissionMode.Message,
|
||||
PipeOptions.Asynchronous,
|
||||
65536,
|
||||
65536,
|
||||
security);
|
||||
|
||||
await server.WaitForConnectionAsync(token).ConfigureAwait(false);
|
||||
|
||||
var session = new RpcConnection(server, this.registry);
|
||||
this.sessions.TryAdd(session.Id, session);
|
||||
|
||||
this.log.Debug("RPC connection created: {Id}", session.Id);
|
||||
|
||||
_ = session.Completion.ContinueWith(t =>
|
||||
{
|
||||
this.sessions.TryRemove(session.Id, out _);
|
||||
this.log.Debug("RPC connection removed: {Id}", session.Id);
|
||||
}, TaskScheduler.Default);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
server?.Dispose();
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
server?.Dispose();
|
||||
this.log.Error(ex, "Error in pipe accept loop");
|
||||
await Task.Delay(500, token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
92
Dalamud/Networking/Pipes/Rpc/RpcConnection.cs
Normal file
92
Dalamud/Networking/Pipes/Rpc/RpcConnection.cs
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
using System.IO.Pipes;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using Serilog;
|
||||
using StreamJsonRpc;
|
||||
|
||||
namespace Dalamud.Networking.Pipes.Rpc;
|
||||
|
||||
/// <summary>
|
||||
/// A single RPC client session connected via named pipe.
|
||||
/// </summary>
|
||||
internal class RpcConnection : IDisposable
|
||||
{
|
||||
private readonly NamedPipeServerStream pipe;
|
||||
private readonly RpcServiceRegistry registry;
|
||||
private readonly CancellationTokenSource cts = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RpcConnection"/> class.
|
||||
/// </summary>
|
||||
/// <param name="pipe">The named pipe that this connection will handle.</param>
|
||||
/// <param name="registry">A registry of RPC services.</param>
|
||||
public RpcConnection(NamedPipeServerStream pipe, RpcServiceRegistry registry)
|
||||
{
|
||||
this.Id = Guid.CreateVersion7();
|
||||
this.pipe = pipe;
|
||||
this.registry = registry;
|
||||
|
||||
var formatter = new JsonMessageFormatter();
|
||||
var handler = new HeaderDelimitedMessageHandler(pipe, pipe, formatter);
|
||||
|
||||
this.Rpc = new JsonRpc(handler);
|
||||
this.Rpc.AllowModificationWhileListening = true;
|
||||
this.Rpc.Disconnected += this.OnDisconnected;
|
||||
this.registry.Attach(this.Rpc);
|
||||
|
||||
this.Rpc.StartListening();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the GUID for this connection.
|
||||
/// </summary>
|
||||
public Guid Id { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the JsonRpc instance for this connection.
|
||||
/// </summary>
|
||||
public JsonRpc Rpc { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets a task that's called on RPC completion.
|
||||
/// </summary>
|
||||
public Task Completion => this.Rpc.Completion;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void Dispose()
|
||||
{
|
||||
if (!this.cts.IsCancellationRequested)
|
||||
{
|
||||
this.cts.Cancel();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
this.Rpc.Dispose();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Debug(ex, "Error disposing JsonRpc for client {Id}", this.Id);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
this.pipe.Dispose();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Debug(ex, "Error disposing pipe for client {Id}", this.Id);
|
||||
}
|
||||
|
||||
this.cts.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
private void OnDisconnected(object? sender, JsonRpcDisconnectedEventArgs e)
|
||||
{
|
||||
Log.Debug("RPC client {Id} disconnected: {Reason}", this.Id, e.Description);
|
||||
this.registry.Detach(this.Rpc);
|
||||
this.Dispose();
|
||||
}
|
||||
}
|
||||
49
Dalamud/Networking/Pipes/Rpc/RpcHostService.cs
Normal file
49
Dalamud/Networking/Pipes/Rpc/RpcHostService.cs
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
using Dalamud.Logging.Internal;
|
||||
|
||||
namespace Dalamud.Networking.Pipes.Rpc;
|
||||
|
||||
/// <summary>
|
||||
/// The Dalamud service repsonsible for hosting the RPC.
|
||||
/// </summary>
|
||||
[ServiceManager.EarlyLoadedService]
|
||||
internal class RpcHostService : IServiceType, IInternalDisposableService
|
||||
{
|
||||
private readonly ModuleLog log = new("RPC");
|
||||
private readonly PipeRpcHost host;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RpcHostService"/> class.
|
||||
/// </summary>
|
||||
[ServiceManager.ServiceConstructor]
|
||||
public RpcHostService()
|
||||
{
|
||||
this.host = new PipeRpcHost();
|
||||
this.host.Start();
|
||||
|
||||
this.log.Information("RpcHostService started on pipe {Pipe}", this.host.PipeName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the RPC host to drill down.
|
||||
/// </summary>
|
||||
public PipeRpcHost Host => this.host;
|
||||
|
||||
/// <summary>
|
||||
/// Add a new service Object to the RPC host.
|
||||
/// </summary>
|
||||
/// <param name="service">The object to add.</param>
|
||||
public void AddService(object service) => this.host.AddService(service);
|
||||
|
||||
/// <summary>
|
||||
/// Add a new standalone method to the RPC host.
|
||||
/// </summary>
|
||||
/// <param name="name">The method name to add.</param>
|
||||
/// <param name="handler">The handler to add.</param>
|
||||
public void AddMethod(string name, Delegate handler) => this.host.AddMethod(name, handler);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public void DisposeService()
|
||||
{
|
||||
this.host.Dispose();
|
||||
}
|
||||
}
|
||||
85
Dalamud/Networking/Pipes/Rpc/RpcServiceRegistry.cs
Normal file
85
Dalamud/Networking/Pipes/Rpc/RpcServiceRegistry.cs
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
|
||||
using StreamJsonRpc;
|
||||
|
||||
namespace Dalamud.Networking.Pipes.Rpc;
|
||||
|
||||
/// <summary>
|
||||
/// Thread-safe registry of local RPC target objects that are exposed to every connected JsonRpc session.
|
||||
/// New sessions get all previously registered targets; newly added targets are attached to all active sessions.
|
||||
/// </summary>
|
||||
internal class RpcServiceRegistry
|
||||
{
|
||||
private readonly Lock sync = new();
|
||||
private readonly List<object> targets = [];
|
||||
private readonly List<(string Name, Delegate Handler)> methods = [];
|
||||
private readonly List<JsonRpc> activeRpcs = [];
|
||||
|
||||
/// <summary>
|
||||
/// Registers a new local RPC target object. Its public JSON-RPC methods become callable by clients.
|
||||
/// Adds <paramref name="service"/> to the registry and attaches it to all active RPC sessions.
|
||||
/// </summary>
|
||||
/// <param name="service">The service instance containing JSON-RPC callable methods to expose.</param>
|
||||
public void AddService(object service)
|
||||
{
|
||||
lock (this.sync)
|
||||
{
|
||||
this.targets.Add(service);
|
||||
foreach (var rpc in this.activeRpcs)
|
||||
{
|
||||
rpc.AddLocalRpcTarget(service);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a new standalone JSON-RPC method.
|
||||
/// </summary>
|
||||
/// <param name="name">The name of the method to add.</param>
|
||||
/// <param name="handler">The handler to add.</param>
|
||||
public void AddMethod(string name, Delegate handler)
|
||||
{
|
||||
lock (this.sync)
|
||||
{
|
||||
this.methods.Add((name, handler));
|
||||
foreach (var rpc in this.activeRpcs)
|
||||
{
|
||||
rpc.AddLocalRpcMethod(name, handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Attaches a JsonRpc instance <paramref name="rpc"/> to the registry so it receives all existing service targets.
|
||||
/// </summary>
|
||||
/// <param name="rpc">The JsonRpc instance to attach and populate with current targets.</param>
|
||||
internal void Attach(JsonRpc rpc)
|
||||
{
|
||||
lock (this.sync)
|
||||
{
|
||||
this.activeRpcs.Add(rpc);
|
||||
foreach (var t in this.targets)
|
||||
{
|
||||
rpc.AddLocalRpcTarget(t);
|
||||
}
|
||||
|
||||
foreach (var m in this.methods)
|
||||
{
|
||||
rpc.AddLocalRpcMethod(m.Name, m.Handler);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detaches a JsonRpc instance <paramref name="rpc"/> from the registry (e.g. when a client disconnects).
|
||||
/// </summary>
|
||||
/// <param name="rpc">The JsonRpc instance being detached.</param>
|
||||
internal void Detach(JsonRpc rpc)
|
||||
{
|
||||
lock (this.sync)
|
||||
{
|
||||
this.activeRpcs.Remove(rpc);
|
||||
}
|
||||
}
|
||||
}
|
||||
20
Dalamud/Plugin/Services/IPluginLinkHandler.cs
Normal file
20
Dalamud/Plugin/Services/IPluginLinkHandler.cs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
using Dalamud.Networking.Pipes;
|
||||
|
||||
namespace Dalamud.Plugin.Services;
|
||||
|
||||
/// <summary>
|
||||
/// A service to allow plugins to subscribe to dalamud:// URIs targeting them. Plugins will receive any URI sent to the
|
||||
/// <code>dalamud://plugin/{PLUGIN_INTERNAL_NAME}/...</code> namespace.
|
||||
/// </summary>
|
||||
public interface IPluginLinkHandler
|
||||
{
|
||||
/// <summary>
|
||||
/// A delegate containing the received URI.
|
||||
/// </summary>
|
||||
delegate void PluginUriReceived(DalamudUri uri);
|
||||
|
||||
/// <summary>
|
||||
/// The event fired when a URI targeting this plugin is received.
|
||||
/// </summary>
|
||||
event PluginUriReceived OnUriReceived;
|
||||
}
|
||||
|
|
@ -3,11 +3,13 @@
|
|||
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||
<CentralPackageVersionOverrideEnabled>false</CentralPackageVersionOverrideEnabled>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Analyzers -->
|
||||
<PackageVersion Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="3.3.4" />
|
||||
<PackageVersion Include="StyleCop.Analyzers" Version="1.2.0-beta.556" />
|
||||
<PackageVersion Include="JetBrains.Annotations" Version="2025.2.2" />
|
||||
|
||||
<!-- Misc Libraries -->
|
||||
<PackageVersion Include="BitFaster.Caching" Version="2.4.1" />
|
||||
<PackageVersion Include="CheapLoc" Version="1.1.8" />
|
||||
|
|
@ -22,26 +24,35 @@
|
|||
<PackageVersion Include="System.Resources.Extensions" Version="10.0.0" />
|
||||
<PackageVersion Include="DotNet.ReproducibleBuilds" Version="1.2.39" />
|
||||
<PackageVersion Include="sqlite-net-pcl" Version="1.8.116" />
|
||||
|
||||
<!-- DirectX / Win32 -->
|
||||
<PackageVersion Include="TerraFX.Interop.Windows" Version="10.0.22621.2" />
|
||||
<PackageVersion Include="SharpDX.Direct3D11" Version="4.2.0" />
|
||||
<PackageVersion Include="SharpDX.Mathematics" Version="4.2.0" />
|
||||
<PackageVersion Include="Microsoft.Windows.CsWin32" Version="0.3.183" />
|
||||
|
||||
<!-- Logging -->
|
||||
<PackageVersion Include="Serilog" Version="4.0.2" />
|
||||
<PackageVersion Include="Serilog.Sinks.Async" Version="2.0.0" />
|
||||
<PackageVersion Include="Serilog.Sinks.Console" Version="6.0.0" />
|
||||
<PackageVersion Include="Serilog.Sinks.File" Version="6.0.0" />
|
||||
|
||||
<!-- Injector Utilities -->
|
||||
<PackageVersion Include="Iced" Version="1.17.0" />
|
||||
<PackageVersion Include="PeNet" Version="2.6.4" />
|
||||
|
||||
<!-- HexaGen -->
|
||||
<PackageVersion Include="HexaGen.Runtime" Version="1.1.20" />
|
||||
|
||||
<!-- Reloaded -->
|
||||
<PackageVersion Include="goatcorp.Reloaded.Hooks" Version="4.2.0-goatcorp7" />
|
||||
<PackageVersion Include="goatcorp.Reloaded.Assembler" Version="1.0.14-goatcorp5" />
|
||||
<PackageVersion Include="Reloaded.Memory" Version="7.0.0" />
|
||||
<PackageVersion Include="Reloaded.Memory.Buffers" Version="2.0.0" />
|
||||
|
||||
<!-- Named Pipes / RPC -->
|
||||
<PackageVersion Include="StreamJsonRpc" Version="2.22.23" />
|
||||
|
||||
<!-- Unit Testing -->
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="16.10.0" />
|
||||
<PackageVersion Include="xunit" Version="2.4.1" />
|
||||
|
|
@ -54,4 +65,4 @@
|
|||
<PackageVersion Include="xunit.runner.console" Version="2.4.1" />
|
||||
<PackageVersion Include="xunit.runner.visualstudio" Version="2.4.3" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
</Project>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue