Files
simapi-net/Synapse/RpcClient.cs
T

100 lines
3.6 KiB
C#
Raw Normal View History

2023-10-20 12:33:18 +08:00
using System;
using System.Collections.Generic;
2024-09-05 12:59:57 +08:00
using System.Linq;
2023-10-20 12:33:18 +08:00
using System.Text.Json;
2024-07-26 05:03:28 +08:00
using System.Threading;
using System.Threading.Tasks;
2023-10-20 12:33:18 +08:00
using Microsoft.Extensions.Logging;
2024-07-26 05:03:28 +08:00
using MQTTnet;
2024-09-05 12:59:57 +08:00
using MQTTnet.Packets;
2023-10-20 12:33:18 +08:00
using SimApi.Communications;
using SimApi.Helpers;
namespace SimApi;
public partial class Synapse
{
private Dictionary<string, TaskCompletionSource<string>> ResponseCompletionSources { get; } = new();
2023-10-20 12:33:18 +08:00
2024-08-03 19:19:42 +08:00
private string EventClientTopicPrefix => $"{Options.SysName}/{Options.AppName}/rpc/client/{Options.AppId}/";
2023-10-20 12:33:18 +08:00
private void RunRpcClient()
{
2024-07-26 08:11:21 +08:00
Client!.ApplicationMessageReceivedAsync += e =>
2023-10-20 12:33:18 +08:00
{
2024-08-03 19:19:42 +08:00
if (!e.ApplicationMessage.Topic.StartsWith(EventClientTopicPrefix)) return Task.CompletedTask;
2024-07-26 05:03:28 +08:00
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
2024-08-03 19:19:42 +08:00
var messageId = e.ApplicationMessage.Topic.Replace(EventClientTopicPrefix, string.Empty);
if (!ResponseCompletionSources.TryGetValue(messageId, out var tcs)) return Task.CompletedTask;
tcs.SetResult(reqBody);
ResponseCompletionSources.Remove(messageId);
2024-07-26 05:03:28 +08:00
return Task.CompletedTask;
2023-10-20 12:33:18 +08:00
};
2024-08-03 19:19:42 +08:00
SubRpcClientTopic();
}
private void SubRpcClientTopic()
{
var rcSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
.WithTopicFilter(o => o.WithTopic($"{EventClientTopicPrefix}+")).Build();
Client!.SubscribeAsync(rcSubOpts).Wait();
2023-10-20 12:33:18 +08:00
}
2024-09-05 12:59:57 +08:00
private string? FireRpc(string app, string action, object? param, Dictionary<string, string>? headers = null)
2023-10-20 12:33:18 +08:00
{
2024-07-26 08:11:21 +08:00
string paramJson;
if (param is string strParam)
{
paramJson = strParam;
}
else
{
paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
}
2024-07-26 05:03:28 +08:00
var topic = $"{Options.SysName}/{app}/rpc/server/{action}";
var messageId = Guid.NewGuid().ToString();
var tcs = new TaskCompletionSource<string>();
ResponseCompletionSources.Add(messageId, tcs);
2024-09-05 12:59:57 +08:00
var messageBuilder = new MqttApplicationMessageBuilder()
2024-07-26 05:03:28 +08:00
.WithTopic(topic)
.WithPayload(paramJson)
2024-09-05 12:59:57 +08:00
.WithResponseTopic($"{Options.AppName},{Options.AppId},{messageId}")
.WithContentType("application/json")
.WithRetainFlag(false);
foreach (var h in headers ?? new Dictionary<string, string>())
{
messageBuilder.WithUserProperty(h.Key, h.Value);
}
var message = messageBuilder.Build();
2024-07-26 05:03:28 +08:00
if (!Client!.IsConnected) return null;
2024-07-26 08:11:21 +08:00
Client.PublishAsync(message, CancellationToken.None).Wait();
2024-07-26 05:03:28 +08:00
logger.LogDebug(
2024-09-05 12:59:57 +08:00
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}\nHeaders: {Headers}",
messageId, Options.AppName, action, app, paramJson, JsonSerializer.Serialize(headers));
string response;
try
2023-10-20 12:33:18 +08:00
{
if (tcs.Task.Wait(Options.RpcTimeout * 1000))
{
response = tcs.Task.Result;
logger.LogDebug(
"Synapse RPC Client Response: ({BasicPropertiesCorrelationId}) {BasicPropertiesType}@{BasicPropertiesReplyTo} -> {OptionsAppName}\n{S}",
messageId, action, app, Options.AppName, response);
}
else
2023-10-20 12:33:18 +08:00
{
2023-10-30 03:45:15 +08:00
response = JsonSerializer.Serialize(new SimApiBaseResponse(502, "timeout"), SimApiUtil.JsonOption);
2023-10-20 12:33:18 +08:00
}
}
catch
{
response = JsonSerializer.Serialize(new SimApiBaseResponse(500, "Synapse RPC Client Error"),
SimApiUtil.JsonOption);
2023-10-20 12:33:18 +08:00
}
2024-07-26 05:03:28 +08:00
2023-10-20 12:33:18 +08:00
return response;
}
}