Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d2b5f14e78 | ||
|
|
116cbcdc7f | ||
|
|
4e1b7d4845 | ||
|
|
71acb35df9 | ||
|
|
67cc7346dc | ||
|
|
8627ae61fa | ||
|
|
02523028db | ||
|
|
7d39ab5e0b | ||
|
|
87fda473d3 | ||
|
|
4ae72d2e6b | ||
|
|
afea9c82bd | ||
|
|
e53048a980 | ||
|
|
bbc2806995 | ||
|
|
404a638d5e | ||
|
|
e27d5e1c77 | ||
|
|
6af68da3eb | ||
|
|
7dc2ac6a86 |
@@ -14,7 +14,7 @@ jobs:
|
|||||||
- name: Setup .NET Core
|
- name: Setup .NET Core
|
||||||
uses: actions/setup-dotnet@v1
|
uses: actions/setup-dotnet@v1
|
||||||
with:
|
with:
|
||||||
dotnet-version: "8.0.200"
|
dotnet-version: "9.0.305"
|
||||||
- name: Publish
|
- name: Publish
|
||||||
run: |
|
run: |
|
||||||
version=`git describe --tags`
|
version=`git describe --tags`
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace SimApi.Attributes;
|
||||||
|
|
||||||
|
[AttributeUsage(AttributeTargets.Method)]
|
||||||
|
public class OriginResponseAttribute : Attribute
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -1,14 +1,16 @@
|
|||||||
using System.Collections.Generic;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using SimApi.Attributes;
|
using SimApi.Attributes;
|
||||||
using SimApi.CoceSdk;
|
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
|
using SimApi.Controllers;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Controllers;
|
namespace SimApi.CoceSdk;
|
||||||
|
|
||||||
public class SimApiCoceController(CoceApp coce,SimApiAuth auth) : SimApiBaseController
|
public class CoceController(CoceApp coce, SimApiAuth auth, IServiceProvider sp) : SimApiBaseController
|
||||||
{
|
{
|
||||||
[HttpPost]
|
[HttpPost]
|
||||||
public SimApiBaseResponse<ConfigResponse> GetConfig()
|
public SimApiBaseResponse<ConfigResponse> GetConfig()
|
||||||
@@ -33,8 +35,9 @@ public class SimApiCoceController(CoceApp coce,SimApiAuth auth) : SimApiBaseCont
|
|||||||
{
|
{
|
||||||
Id = data.UserId,
|
Id = data.UserId,
|
||||||
Meta = meta,
|
Meta = meta,
|
||||||
Extra = groups
|
|
||||||
};
|
};
|
||||||
|
var processor = sp.GetService<ICoceLoginProcessor>();
|
||||||
|
processor?.Process(loginItem, groups.ToArray());
|
||||||
return new SimApiBaseResponse<string>(auth.Login(loginItem));
|
return new SimApiBaseResponse<string>(auth.Login(loginItem));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using SimApi.Communications;
|
||||||
|
|
||||||
|
namespace SimApi.CoceSdk;
|
||||||
|
|
||||||
|
public interface ICoceLoginProcessor
|
||||||
|
{
|
||||||
|
SimApiLoginItem Process(SimApiLoginItem loginItem, GroupInfo[] groups);
|
||||||
|
}
|
||||||
@@ -1,13 +1,11 @@
|
|||||||
using System.ComponentModel.DataAnnotations;
|
namespace SimApi.Communications;
|
||||||
|
|
||||||
namespace SimApi.Communications;
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 只有ID的请求
|
/// 只有ID的请求
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class SimApiIdOnlyRequest
|
public class SimApiIdOnlyRequest
|
||||||
{
|
{
|
||||||
[Required] public int Id { get; set; }
|
public required int Id { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -15,7 +13,7 @@ public class SimApiIdOnlyRequest
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class SimApiStringIdOnlyRequest
|
public class SimApiStringIdOnlyRequest
|
||||||
{
|
{
|
||||||
[Required] public string? Id { get; set; }
|
public required string Id { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -24,7 +22,7 @@ public class SimApiStringIdOnlyRequest
|
|||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
public class SimApiOneFieldRequest<T>
|
public class SimApiOneFieldRequest<T>
|
||||||
{
|
{
|
||||||
[Required] public T? Data { get; set; }
|
public required T Data { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -32,6 +30,6 @@ public class SimApiOneFieldRequest<T>
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class SimApiBasePageRequest
|
public class SimApiBasePageRequest
|
||||||
{
|
{
|
||||||
[Required] public int Page { get; set; }
|
public required int Page { get; set; }
|
||||||
[Required] public int Count { get; set; }
|
public required int Count { get; set; }
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Communications;
|
namespace SimApi.Communications;
|
||||||
|
|
||||||
@@ -36,15 +37,7 @@ public class SimApiBaseResponse(int code = 200, string message = "成功")
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public override string ToString()
|
public override string ToString()
|
||||||
{
|
{
|
||||||
return JsonSerializer.Serialize(this, new JsonSerializerOptions
|
return SimApiUtil.Json(this);
|
||||||
{
|
|
||||||
IgnoreReadOnlyProperties = true,
|
|
||||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
||||||
Converters =
|
|
||||||
{
|
|
||||||
new JsonStringEnumConverter()
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,8 +7,8 @@ namespace SimApi.Communications;
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class SimApiLoginItem
|
public class SimApiLoginItem
|
||||||
{
|
{
|
||||||
public string? Id { get; set; }
|
public string Id { get; set; } = null!;
|
||||||
public string[] Type { get; set; } = new[] { "user" };
|
public string[] Type { get; set; } = ["user"];
|
||||||
public Dictionary<string, string>? Meta { get; set; } = null;
|
public Dictionary<string, string> Meta { get; set; } = [];
|
||||||
public object? Extra { get; set; } = null;
|
public object? Extra { get; set; }
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
namespace SimApi.Configurations;
|
||||||
|
|
||||||
|
public class SimApiJobOptions
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// WebUi地址,设置为null表示不启用
|
||||||
|
/// </summary>
|
||||||
|
public string? DashboardUrl { get; set; } = "/jobs";
|
||||||
|
|
||||||
|
public string DashboardAuthUser { get; set; } = "admin";
|
||||||
|
public string DashboardAuthPass { get; set; } = "Admin@123!";
|
||||||
|
public string? RedisConfiguration { get; set; }
|
||||||
|
|
||||||
|
public int? Database { get; set; } = null;
|
||||||
|
public SimApiJobServerConfig[] Servers { get; set; } = [new()];
|
||||||
|
}
|
||||||
|
|
||||||
|
public class SimApiJobServerConfig()
|
||||||
|
{
|
||||||
|
public string[] Queues { get; set; } = ["default"];
|
||||||
|
public int WorkerNum { get; set; } = 50;
|
||||||
|
}
|
||||||
@@ -5,11 +5,12 @@ namespace SimApi.Configurations;
|
|||||||
|
|
||||||
public class SimApiOptions
|
public class SimApiOptions
|
||||||
{
|
{
|
||||||
|
public string? RedisConfiguration { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用全部Cors,对于开发前后分离的时候很有用。
|
/// 是否启用后台任务系统 *基于Hangfire
|
||||||
/// default: true
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableCors { get; set; } = true;
|
public bool EnableJob { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用SimApiAuth,一个简单的基于Header Token的认证方式。
|
/// 启用SimApiAuth,一个简单的基于Header Token的认证方式。
|
||||||
@@ -17,13 +18,16 @@ public class SimApiOptions
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiAuth { get; set; }
|
public bool EnableSimApiAuth { get; set; }
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 是否使用CoceSdk
|
/// 是否使用CoceSdk
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableCoceSdk { get; set; }
|
public bool EnableCoceSdk { get; set; }
|
||||||
|
|
||||||
public CoceAppSdkOption CoceSdkOptions { get; set; } = new();
|
/// <summary>
|
||||||
|
/// 开启S3兼容的存储系统。
|
||||||
|
/// default: false
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableSimApiStorage { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用在线文档,启用后 访问 /swagger 可以查看对应的api文档。
|
/// 启用在线文档,启用后 访问 /swagger 可以查看对应的api文档。
|
||||||
@@ -31,6 +35,20 @@ public class SimApiOptions
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiDoc { get; set; }
|
public bool EnableSimApiDoc { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否启用Synapse
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableSynapse { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 启用全部Cors,对于开发前后分离的时候很有用。
|
||||||
|
/// default: true
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableCors { get; set; } = true;
|
||||||
|
|
||||||
|
|
||||||
|
public CoceAppSdkOption CoceSdkOptions { get; set; } = new();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用异常拦截,启用后,所有的异常将被通过json反馈。
|
/// 启用异常拦截,启用后,所有的异常将被通过json反馈。
|
||||||
/// default: true
|
/// default: true
|
||||||
@@ -38,10 +56,10 @@ public class SimApiOptions
|
|||||||
public bool EnableSimApiException { get; set; } = true;
|
public bool EnableSimApiException { get; set; } = true;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 开启S3兼容的存储系统。
|
/// 启用返回结果拦截
|
||||||
/// default: false
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiStorage { get; set; }
|
public bool EnableSimApiResponseFilter { get; set; } = true;
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
|
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
|
||||||
@@ -55,17 +73,18 @@ public class SimApiOptions
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableLowerUrl { get; set; } = true;
|
public bool EnableLowerUrl { get; set; } = true;
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用格式化的 Console Logger
|
/// 启用格式化的 Console Logger
|
||||||
/// default: false
|
/// default: false
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableLogger { get; set; }
|
public bool EnableLogger { get; set; } = true;
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 是否启用Synapse
|
/// 配置Job
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSynapse { get; set; }
|
public SimApiJobOptions SimApiJobOptions { get; set; } = new();
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Swagger文档相关配置,需要启用 EnableSimApiDoc
|
/// Swagger文档相关配置,需要启用 EnableSimApiDoc
|
||||||
@@ -98,4 +117,9 @@ public class SimApiOptions
|
|||||||
{
|
{
|
||||||
options?.Invoke(SimApiStorageOptions);
|
options?.Invoke(SimApiStorageOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void ConfigureSimApiJob(Action<SimApiJobOptions>? options = null)
|
||||||
|
{
|
||||||
|
options?.Invoke(SimApiJobOptions);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,4 @@
|
|||||||
#nullable enable
|
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Microsoft.Extensions.Caching.Distributed;
|
using Microsoft.Extensions.Caching.Distributed;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
@@ -33,7 +31,7 @@ public class SimApiAuth(IDistributedCache cache)
|
|||||||
public SimApiLoginItem? GetLogin(string token)
|
public SimApiLoginItem? GetLogin(string token)
|
||||||
{
|
{
|
||||||
var login = cache.GetString(token);
|
var login = cache.GetString(token);
|
||||||
return login != null ? JsonSerializer.Deserialize<SimApiLoginItem>(login) : default;
|
return login != null ? JsonSerializer.Deserialize<SimApiLoginItem>(login) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -0,0 +1,32 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Caching.Distributed;
|
||||||
|
|
||||||
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
|
public class SimApiCache(IDistributedCache cache)
|
||||||
|
{
|
||||||
|
private const string Prefix = "SimApi:Cache:";
|
||||||
|
|
||||||
|
public void Set(string key, object value, DistributedCacheEntryOptions? options = null)
|
||||||
|
{
|
||||||
|
if (options is not null)
|
||||||
|
{
|
||||||
|
cache.SetString(Prefix + key, SimApiUtil.Json(value), options);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
cache.SetString(Prefix + key, SimApiUtil.Json(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public string? Get(string key)
|
||||||
|
{
|
||||||
|
return cache.GetString(Prefix + key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public T? Get<T>(string key)
|
||||||
|
{
|
||||||
|
var data = cache.GetString(Prefix + key);
|
||||||
|
return data == null ? default : JsonSerializer.Deserialize<T>(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using Hangfire.Dashboard;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
|
|
||||||
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
|
public class SimApiJobWebAuth(string user, string pass) : IDashboardAuthorizationFilter
|
||||||
|
{
|
||||||
|
public bool Authorize(DashboardContext context)
|
||||||
|
{
|
||||||
|
var httpContext = context.GetHttpContext();
|
||||||
|
var authHeader = httpContext.Request.Headers["Authorization"].FirstOrDefault();
|
||||||
|
if (authHeader != null && authHeader.StartsWith("Basic "))
|
||||||
|
{
|
||||||
|
var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1].Trim();
|
||||||
|
var decodedUsernamePassword = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword));
|
||||||
|
var username = decodedUsernamePassword.Split(':', 2)[0];
|
||||||
|
var password = decodedUsernamePassword.Split(':', 2)[1];
|
||||||
|
|
||||||
|
if (username == user && password == pass)
|
||||||
|
{
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
httpContext.Response.StatusCode = 401;
|
||||||
|
httpContext.Response.Headers.WWWAuthenticate = "Basic realm=\"SimApiBasicAuth\"";
|
||||||
|
httpContext.Response.WriteAsync("").Wait();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Filters;
|
||||||
|
using SimApi.Attributes;
|
||||||
|
using SimApi.Communications;
|
||||||
|
|
||||||
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
|
public class SimApiResponseFilter : IResultFilter
|
||||||
|
{
|
||||||
|
public void OnResultExecuting(ResultExecutingContext context)
|
||||||
|
{
|
||||||
|
if (context.ActionDescriptor.EndpointMetadata.Any(meta => meta is OriginResponseAttribute))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
context.Result = context.Result switch
|
||||||
|
{
|
||||||
|
// 检查结果是否为 null
|
||||||
|
null => new OkObjectResult(new SimApiBaseResponse()),
|
||||||
|
ObjectResult { Value: SimApiBaseResponse simApiBaseResponse } =>
|
||||||
|
new OkObjectResult(simApiBaseResponse),
|
||||||
|
ObjectResult objectResult => new OkObjectResult(new SimApiBaseResponse<object>(objectResult.Value!)),
|
||||||
|
EmptyResult => new OkObjectResult(new SimApiBaseResponse()),
|
||||||
|
_ => context.Result
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnResultExecuted(ResultExecutedContext context)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
+36
-2
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
@@ -7,6 +8,7 @@ using System.Text.Json;
|
|||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using System.Text.Unicode;
|
using System.Text.Unicode;
|
||||||
|
using System.Xml.Serialization;
|
||||||
|
|
||||||
namespace SimApi.Helpers;
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
@@ -22,9 +24,10 @@ public static class SimApiUtil
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public static JsonSerializerOptions JsonOption => new()
|
public static JsonSerializerOptions JsonOption => new()
|
||||||
{
|
{
|
||||||
|
// ReferenceHandler = ReferenceHandler.Preserve,
|
||||||
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
|
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
|
||||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
|
// DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -62,12 +65,43 @@ public static class SimApiUtil
|
|||||||
return stringBuilder.ToString();
|
return stringBuilder.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// sha1加密字符串
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source">源字符串</param>
|
||||||
|
/// <param name="mode">加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static string Sha1(string source, string mode = "x2")
|
||||||
|
{
|
||||||
|
var hash = SHA1.HashData(Encoding.UTF8.GetBytes(source));
|
||||||
|
var sb = new StringBuilder(hash.Length * 2);
|
||||||
|
foreach (var b in hash)
|
||||||
|
{
|
||||||
|
sb.Append(b.ToString(mode));
|
||||||
|
}
|
||||||
|
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将XML字符串序列化为对象
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="source"></param>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static T XmlDeserialize<T>(string source)
|
||||||
|
{
|
||||||
|
var xmlConvertor = new XmlSerializer(typeof(T));
|
||||||
|
using var reader = new StringReader(source);
|
||||||
|
return (T)xmlConvertor.Deserialize(reader)!;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 将对象序列化成JSON (控制台输出中文不会被编码)
|
/// 将对象序列化成JSON (控制台输出中文不会被编码)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="obj"></param>
|
/// <param name="obj"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static string Json(object obj)
|
public static string Json(object? obj)
|
||||||
{
|
{
|
||||||
return JsonSerializer.Serialize(obj, JsonOption);
|
return JsonSerializer.Serialize(obj, JsonOption);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Linq;
|
using System.IO;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
@@ -27,12 +27,11 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
|||||||
switch (context.Response.StatusCode)
|
switch (context.Response.StatusCode)
|
||||||
{
|
{
|
||||||
case 200:
|
case 200:
|
||||||
break;
|
|
||||||
case 404:
|
|
||||||
throw new SimApiException(context.Response.StatusCode, "请求的接口不存在");
|
|
||||||
case 301:
|
case 301:
|
||||||
case 302:
|
case 302:
|
||||||
break;
|
break;
|
||||||
|
case 404:
|
||||||
|
throw new SimApiException(context.Response.StatusCode, "请求的接口不存在");
|
||||||
default:
|
default:
|
||||||
throw new SimApiException(context.Response.StatusCode);
|
throw new SimApiException(context.Response.StatusCode);
|
||||||
}
|
}
|
||||||
@@ -42,7 +41,6 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
|||||||
response = string.IsNullOrEmpty(ex.Message)
|
response = string.IsNullOrEmpty(ex.Message)
|
||||||
? new SimApiBaseResponse(ex.Code)
|
? new SimApiBaseResponse(ex.Code)
|
||||||
: new SimApiBaseResponse(ex.Code, ex.Message);
|
: new SimApiBaseResponse(ex.Code, ex.Message);
|
||||||
|
|
||||||
ErrorResponse(context, response);
|
ErrorResponse(context, response);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -61,9 +59,8 @@ public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExcep
|
|||||||
/// <param name="response"></param>
|
/// <param name="response"></param>
|
||||||
private static void ErrorResponse(HttpContext context, SimApiBaseResponse response)
|
private static void ErrorResponse(HttpContext context, SimApiBaseResponse response)
|
||||||
{
|
{
|
||||||
if (context.Response.HasStarted) return;
|
|
||||||
context.Response.StatusCode = 200;
|
context.Response.StatusCode = 200;
|
||||||
context.Response.Headers.Append("Content-Type", "application/json");
|
context.Response.Headers.Append("Content-Type", "application/json");
|
||||||
context.Response.WriteAsync(response.ToString());
|
context.Response.WriteAsync(response.ToString()).Wait();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+10
-7
@@ -14,21 +14,24 @@
|
|||||||
<SynchReleaseVersion>false</SynchReleaseVersion>
|
<SynchReleaseVersion>false</SynchReleaseVersion>
|
||||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||||
<PackageVersion>5.0.2</PackageVersion>
|
<PackageVersion>5.0.2</PackageVersion>
|
||||||
<TargetFramework>net8.0</TargetFramework>
|
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
|
<TargetFrameworks>net8.0;net9.0</TargetFrameworks>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Folder Include="Helpers\"/>
|
|
||||||
<Folder Include="Communications\"/>
|
<Folder Include="Communications\"/>
|
||||||
<Folder Include="Middlewares\"/>
|
|
||||||
<Folder Include="Exceptions\"/>
|
<Folder Include="Exceptions\"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Minio" Version="6.0.3" />
|
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.18" />
|
||||||
<PackageReference Include="MQTTnet" Version="4.3.6.1152" />
|
<PackageReference Include="Hangfire.Console" Version="1.4.3" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.7.1" />
|
<PackageReference Include="Hangfire.Redis.StackExchange" Version="1.12.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.7.1" />
|
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="9.0.5" />
|
||||||
|
<PackageReference Include="Minio" Version="6.0.4" />
|
||||||
|
<PackageReference Include="MQTTnet" Version="5.0.1.1416" />
|
||||||
|
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="8.1.1" />
|
||||||
|
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="8.1.1" />
|
||||||
|
<PackageReference Include="System.Text.Json" Version="9.0.10" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ProjectExtensions>
|
<ProjectExtensions>
|
||||||
<MonoDevelop>
|
<MonoDevelop>
|
||||||
|
|||||||
+118
-24
@@ -1,4 +1,11 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Hangfire;
|
||||||
|
using Hangfire.Console;
|
||||||
|
using Hangfire.Redis.StackExchange;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
@@ -7,6 +14,7 @@ using SimApi.Middlewares;
|
|||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using SimApi.Attributes;
|
||||||
using SimApi.CoceSdk;
|
using SimApi.CoceSdk;
|
||||||
using SimApi.Configurations;
|
using SimApi.Configurations;
|
||||||
using SimApi.Logger;
|
using SimApi.Logger;
|
||||||
@@ -24,6 +32,12 @@ public static class SimApiExtensions
|
|||||||
{
|
{
|
||||||
var simApiOptions = new SimApiOptions();
|
var simApiOptions = new SimApiOptions();
|
||||||
options?.Invoke(simApiOptions);
|
options?.Invoke(simApiOptions);
|
||||||
|
if (simApiOptions.RedisConfiguration != null)
|
||||||
|
{
|
||||||
|
builder.AddStackExchangeRedisCache(x => x.Configuration = simApiOptions.RedisConfiguration);
|
||||||
|
builder.AddSingleton<SimApiCache>();
|
||||||
|
}
|
||||||
|
|
||||||
if (simApiOptions.EnableLogger)
|
if (simApiOptions.EnableLogger)
|
||||||
{
|
{
|
||||||
builder.AddLogging(logger =>
|
builder.AddLogging(logger =>
|
||||||
@@ -44,6 +58,30 @@ public static class SimApiExtensions
|
|||||||
builder.AddSingleton<CoceApp>();
|
builder.AddSingleton<CoceApp>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (simApiOptions.EnableJob)
|
||||||
|
{
|
||||||
|
builder.AddHangfire(x =>
|
||||||
|
{
|
||||||
|
var redisOption = new RedisStorageOptions();
|
||||||
|
if (simApiOptions.SimApiJobOptions.Database.HasValue)
|
||||||
|
{
|
||||||
|
redisOption.Db = simApiOptions.SimApiJobOptions.Database.Value;
|
||||||
|
}
|
||||||
|
|
||||||
|
x.UseRedisStorage(simApiOptions.SimApiJobOptions.RedisConfiguration ??
|
||||||
|
simApiOptions.RedisConfiguration, redisOption);
|
||||||
|
x.UseConsole();
|
||||||
|
});
|
||||||
|
foreach (var server in simApiOptions.SimApiJobOptions.Servers)
|
||||||
|
{
|
||||||
|
builder.AddHangfireServer(hfs =>
|
||||||
|
{
|
||||||
|
hfs.Queues = server.Queues;
|
||||||
|
hfs.WorkerCount = server.WorkerNum;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (simApiOptions.EnableCors)
|
if (simApiOptions.EnableCors)
|
||||||
{
|
{
|
||||||
builder.AddCors(cors => cors.AddPolicy("any",
|
builder.AddCors(cors => cors.AddPolicy("any",
|
||||||
@@ -53,6 +91,19 @@ public static class SimApiExtensions
|
|||||||
if (simApiOptions.EnableSynapse)
|
if (simApiOptions.EnableSynapse)
|
||||||
{
|
{
|
||||||
builder.AddSingleton<Synapse>();
|
builder.AddSingleton<Synapse>();
|
||||||
|
//自动依赖注入
|
||||||
|
var stackTrace = new StackTrace();
|
||||||
|
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
|
||||||
|
var assembly = callingMethod?.DeclaringType?.Assembly;
|
||||||
|
var types = assembly?.GetTypes() ?? [];
|
||||||
|
foreach (var type in types)
|
||||||
|
{
|
||||||
|
var methodsWithSynapse = type.GetMethods()
|
||||||
|
.Where(m => m.GetCustomAttribute<SynapseRpcAttribute>() != null ||
|
||||||
|
m.GetCustomAttribute<SynapseEventAttribute>() != null);
|
||||||
|
if (!methodsWithSynapse.Any()) continue;
|
||||||
|
builder.AddScoped(type);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用SimApiDoc
|
// 使用SimApiDoc
|
||||||
@@ -192,6 +243,16 @@ public static class SimApiExtensions
|
|||||||
builder.AddSingleton<SimApiStorage>();
|
builder.AddSingleton<SimApiStorage>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (simApiOptions.EnableSimApiResponseFilter)
|
||||||
|
{
|
||||||
|
builder.AddControllers(opt => opt.Filters.Add<SimApiResponseFilter>())
|
||||||
|
.AddXmlSerializerFormatters()
|
||||||
|
.AddJsonOptions(opt =>
|
||||||
|
{
|
||||||
|
opt.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
builder.AddSingleton(simApiOptions);
|
builder.AddSingleton(simApiOptions);
|
||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
@@ -204,6 +265,11 @@ public static class SimApiExtensions
|
|||||||
|
|
||||||
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
||||||
|
|
||||||
|
if (options.RedisConfiguration != null)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置 RedisCache ...");
|
||||||
|
}
|
||||||
|
|
||||||
//请求一下检测存储错误
|
//请求一下检测存储错误
|
||||||
if (options.EnableSimApiStorage)
|
if (options.EnableSimApiStorage)
|
||||||
{
|
{
|
||||||
@@ -218,17 +284,17 @@ public static class SimApiExtensions
|
|||||||
options.CoceSdkOptions.AppId);
|
options.CoceSdkOptions.AppId);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.EnableLowerUrl)
|
|
||||||
{
|
|
||||||
logger.LogInformation("开始配置使用URL小写...");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.EnableSynapse)
|
if (options.EnableSynapse)
|
||||||
{
|
{
|
||||||
var synapse = builder.Services.GetRequiredService<Synapse>();
|
var synapse = builder.Services.GetRequiredService<Synapse>();
|
||||||
synapse.Init();
|
synapse.Init();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (options.EnableJob)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置 SimApiJob ...");
|
||||||
|
}
|
||||||
|
|
||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -240,10 +306,8 @@ public static class SimApiExtensions
|
|||||||
public static WebApplication UseSimApi(this WebApplication builder)
|
public static WebApplication UseSimApi(this WebApplication builder)
|
||||||
{
|
{
|
||||||
var options = builder.Services.GetRequiredService<SimApiOptions>();
|
var options = builder.Services.GetRequiredService<SimApiOptions>();
|
||||||
|
|
||||||
var logger = builder.Services.GetRequiredService<ILogger<SimApiOptions>>();
|
var logger = builder.Services.GetRequiredService<ILogger<SimApiOptions>>();
|
||||||
|
UseSimApi((IHost)builder);
|
||||||
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
|
||||||
if (options.EnableForwardHeaders)
|
if (options.EnableForwardHeaders)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置ForwardedHeaders...");
|
logger.LogInformation("开始配置ForwardedHeaders...");
|
||||||
@@ -256,27 +320,57 @@ public static class SimApiExtensions
|
|||||||
builder.UseCors("any");
|
builder.UseCors("any");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (options.EnableSimApiResponseFilter)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置SimApiResponseFilter...");
|
||||||
|
builder.MapControllers();
|
||||||
|
}
|
||||||
|
|
||||||
if (options.EnableSimApiAuth)
|
if (options.EnableSimApiAuth)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置SimApiAuth...");
|
logger.LogInformation("开始配置SimApiAuth...");
|
||||||
builder.UseMiddleware<SimApiAuthMiddleware>();
|
builder.UseMiddleware<SimApiAuthMiddleware>();
|
||||||
builder.MapControllerRoute(name: "GetUserInfo", pattern: "/user/info",
|
builder.MapControllerRoute(name: "GetUserInfo", pattern: "/user/info",
|
||||||
defaults: new { controller = "SimApiCommon", action = "UserInfo" });
|
defaults: new
|
||||||
|
{
|
||||||
|
controller = "SimApiCommon",
|
||||||
|
action = "UserInfo"
|
||||||
|
});
|
||||||
builder.MapControllerRoute(name: "CheckLogin", pattern: "/auth/check",
|
builder.MapControllerRoute(name: "CheckLogin", pattern: "/auth/check",
|
||||||
defaults: new { controller = "SimApiCommon", action = "CheckLogin" });
|
defaults: new
|
||||||
|
{
|
||||||
|
controller = "SimApiCommon",
|
||||||
|
action = "CheckLogin"
|
||||||
|
});
|
||||||
builder.MapControllerRoute(name: "Logout", pattern: "/auth/logout",
|
builder.MapControllerRoute(name: "Logout", pattern: "/auth/logout",
|
||||||
defaults: new { controller = "SimApiCommon", action = "Logout" });
|
defaults: new
|
||||||
|
{
|
||||||
|
controller = "SimApiCommon",
|
||||||
|
action = "Logout"
|
||||||
|
});
|
||||||
if (options.EnableCoceSdk)
|
if (options.EnableCoceSdk)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}",
|
logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}",
|
||||||
options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint,
|
options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint,
|
||||||
options.CoceSdkOptions.AppId);
|
options.CoceSdkOptions.AppId);
|
||||||
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/login",
|
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/login",
|
||||||
defaults: new { controller = "SimApiCoce", action = "Login" });
|
defaults: new
|
||||||
|
{
|
||||||
|
controller = "Coce",
|
||||||
|
action = "Login"
|
||||||
|
});
|
||||||
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/user/groups",
|
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/user/groups",
|
||||||
defaults: new { controller = "SimApiCoce", action = "ListGroups" });
|
defaults: new
|
||||||
|
{
|
||||||
|
controller = "Coce",
|
||||||
|
action = "ListGroups"
|
||||||
|
});
|
||||||
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/config",
|
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/config",
|
||||||
defaults: new { controller = "SimApiCoce", action = "GetConfig" });
|
defaults: new
|
||||||
|
{
|
||||||
|
controller = "Coce",
|
||||||
|
action = "GetConfig"
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -304,22 +398,22 @@ public static class SimApiExtensions
|
|||||||
builder.UseMiddleware<SimApiExceptionMiddleware>();
|
builder.UseMiddleware<SimApiExceptionMiddleware>();
|
||||||
}
|
}
|
||||||
|
|
||||||
//请求一下检测存储错误
|
|
||||||
if (options.EnableSimApiStorage)
|
|
||||||
{
|
|
||||||
logger.LogInformation("开始配置SimApiStorage...");
|
|
||||||
builder.Services.GetService<SimApiStorage>();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.EnableLowerUrl)
|
if (options.EnableLowerUrl)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置使用URL小写...");
|
logger.LogInformation("开始配置使用URL小写...");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.EnableSynapse)
|
if (options is { EnableJob: true, SimApiJobOptions.DashboardUrl: not null })
|
||||||
{
|
{
|
||||||
var synapse = builder.Services.GetRequiredService<Synapse>();
|
logger.LogInformation("开始配置 SimApiJob Web控制台...");
|
||||||
synapse.Init();
|
builder.UseHangfireDashboard(options.SimApiJobOptions.DashboardUrl, new DashboardOptions
|
||||||
|
{
|
||||||
|
Authorization =
|
||||||
|
[
|
||||||
|
new SimApiJobWebAuth(options.SimApiJobOptions.DashboardAuthUser,
|
||||||
|
options.SimApiJobOptions.DashboardAuthPass)
|
||||||
|
]
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return builder;
|
return builder;
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ public partial class Synapse
|
|||||||
private void RunEventServer()
|
private void RunEventServer()
|
||||||
{
|
{
|
||||||
Client!.ApplicationMessageReceivedAsync += async e =>
|
Client!.ApplicationMessageReceivedAsync += async e =>
|
||||||
|
{
|
||||||
|
await Task.Run(async () =>
|
||||||
{
|
{
|
||||||
if (!e.ApplicationMessage.Topic.StartsWith(EventServerTopicPrefix)) return;
|
if (!e.ApplicationMessage.Topic.StartsWith(EventServerTopicPrefix)) return;
|
||||||
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
@@ -37,8 +39,8 @@ public partial class Synapse
|
|||||||
{
|
{
|
||||||
var pt = mt.GetParameters()[1].ParameterType;
|
var pt = mt.GetParameters()[1].ParameterType;
|
||||||
mt.Invoke(callClass, pt == typeof(string)
|
mt.Invoke(callClass, pt == typeof(string)
|
||||||
? new object?[] { eventName, reqBody }
|
? [eventName, reqBody]
|
||||||
: new object?[] { eventName, JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) });
|
: [eventName, JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption)]);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -52,6 +54,7 @@ public partial class Synapse
|
|||||||
}))
|
}))
|
||||||
.ToList();
|
.ToList();
|
||||||
await Task.WhenAll(tasks);
|
await Task.WhenAll(tasks);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
SubEventServerTopic();
|
SubEventServerTopic();
|
||||||
}
|
}
|
||||||
|
|||||||
+21
-12
@@ -7,12 +7,13 @@ using Microsoft.Extensions.Logging;
|
|||||||
using MQTTnet;
|
using MQTTnet;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
|
||||||
namespace SimApi;
|
namespace SimApi;
|
||||||
|
|
||||||
public partial class Synapse
|
public partial class Synapse
|
||||||
{
|
{
|
||||||
private Dictionary<string, TaskCompletionSource<string>> ResponseCompletionSources { get; } = new();
|
private ConcurrentDictionary<string, TaskCompletionSource<string>> ResponseCompletionSources { get; } = new();
|
||||||
|
|
||||||
private string EventClientTopicPrefix => $"{Options.SysName}/{Options.AppName}/rpc/client/{Options.AppId}/";
|
private string EventClientTopicPrefix => $"{Options.SysName}/{Options.AppName}/rpc/client/{Options.AppId}/";
|
||||||
|
|
||||||
@@ -25,7 +26,7 @@ public partial class Synapse
|
|||||||
var messageId = e.ApplicationMessage.Topic.Replace(EventClientTopicPrefix, string.Empty);
|
var messageId = e.ApplicationMessage.Topic.Replace(EventClientTopicPrefix, string.Empty);
|
||||||
if (!ResponseCompletionSources.TryGetValue(messageId, out var tcs)) return Task.CompletedTask;
|
if (!ResponseCompletionSources.TryGetValue(messageId, out var tcs)) return Task.CompletedTask;
|
||||||
tcs.SetResult(reqBody);
|
tcs.SetResult(reqBody);
|
||||||
ResponseCompletionSources.Remove(messageId);
|
ResponseCompletionSources.Remove(messageId, out _);
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
SubRpcClientTopic();
|
SubRpcClientTopic();
|
||||||
@@ -38,8 +39,10 @@ public partial class Synapse
|
|||||||
Client!.SubscribeAsync(rcSubOpts).Wait();
|
Client!.SubscribeAsync(rcSubOpts).Wait();
|
||||||
}
|
}
|
||||||
|
|
||||||
private string? FireRpc(string app, string action, object? param)
|
private string? FireRpc(string app, string action, object? param, Dictionary<string, string>? headers = null,
|
||||||
|
int? timeout = null)
|
||||||
{
|
{
|
||||||
|
// 移除锁语句
|
||||||
string paramJson;
|
string paramJson;
|
||||||
if (param is string strParam)
|
if (param is string strParam)
|
||||||
{
|
{
|
||||||
@@ -53,24 +56,30 @@ public partial class Synapse
|
|||||||
var topic = $"{Options.SysName}/{app}/rpc/server/{action}";
|
var topic = $"{Options.SysName}/{app}/rpc/server/{action}";
|
||||||
var messageId = Guid.NewGuid().ToString();
|
var messageId = Guid.NewGuid().ToString();
|
||||||
var tcs = new TaskCompletionSource<string>();
|
var tcs = new TaskCompletionSource<string>();
|
||||||
ResponseCompletionSources.Add(messageId, tcs);
|
ResponseCompletionSources.TryAdd(messageId, tcs);
|
||||||
var message = new MqttApplicationMessageBuilder()
|
var messageBuilder = new MqttApplicationMessageBuilder()
|
||||||
.WithTopic(topic)
|
.WithTopic(topic)
|
||||||
.WithPayload(paramJson)
|
.WithPayload(paramJson)
|
||||||
.WithResponseTopic($"{Options.AppName},{Options.AppId}")
|
.WithResponseTopic($"{Options.AppName},{Options.AppId},{messageId}")
|
||||||
.WithContentType(messageId)
|
.WithContentType("application/json")
|
||||||
.WithRetainFlag(false)
|
.WithRetainFlag(false);
|
||||||
.Build();
|
foreach (var h in headers ?? new Dictionary<string, string>())
|
||||||
|
{
|
||||||
|
messageBuilder.WithUserProperty(h.Key, h.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
var message = messageBuilder.Build();
|
||||||
if (!Client!.IsConnected) return null;
|
if (!Client!.IsConnected) return null;
|
||||||
Client.PublishAsync(message, CancellationToken.None).Wait();
|
Client.PublishAsync(message, CancellationToken.None).Wait();
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}", messageId,
|
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}\nHeaders: {Headers}",
|
||||||
Options.AppName, action, app, paramJson);
|
messageId, Options.AppName, action, app, paramJson, JsonSerializer.Serialize(headers));
|
||||||
|
|
||||||
string response;
|
string response;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (tcs.Task.Wait(Options.RpcTimeout * 1000))
|
timeout ??= Options.RpcTimeout;
|
||||||
|
if (tcs.Task.Wait(timeout.Value * 1000))
|
||||||
{
|
{
|
||||||
response = tcs.Task.Result;
|
response = tcs.Task.Result;
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
|
|||||||
+28
-15
@@ -20,16 +20,17 @@ public partial class Synapse
|
|||||||
|
|
||||||
private void RunRpcServer()
|
private void RunRpcServer()
|
||||||
{
|
{
|
||||||
Client!.ApplicationMessageReceivedAsync += e =>
|
Client!.ApplicationMessageReceivedAsync += async e =>
|
||||||
{
|
{
|
||||||
if (!e.ApplicationMessage.Topic.StartsWith(RpcServerTopicPrefix)) return Task.CompletedTask;
|
await Task.Run(() =>
|
||||||
|
{
|
||||||
|
if (!e.ApplicationMessage.Topic.StartsWith(RpcServerTopicPrefix)) return;
|
||||||
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
var action = e.ApplicationMessage.Topic.Replace(RpcServerTopicPrefix, string.Empty);
|
var action = e.ApplicationMessage.Topic.Replace(RpcServerTopicPrefix, string.Empty);
|
||||||
var appInfo = e.ApplicationMessage.ResponseTopic.Split(",");
|
var appInfo = e.ApplicationMessage.ResponseTopic.Split(",");
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
"Synapse RPC Server Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}",
|
"Synapse RPC Server Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}",
|
||||||
e.ApplicationMessage.ContentType, appInfo[0], action, Options.AppName,
|
appInfo[2], appInfo[0], action, Options.AppName, reqBody);
|
||||||
reqBody);
|
|
||||||
SimApiBaseResponse res;
|
SimApiBaseResponse res;
|
||||||
var method = RpcRegistry.FirstOrDefault(x => x.Key == action);
|
var method = RpcRegistry.FirstOrDefault(x => x.Key == action);
|
||||||
if (method == null)
|
if (method == null)
|
||||||
@@ -44,17 +45,30 @@ public partial class Synapse
|
|||||||
{
|
{
|
||||||
var methodParams = mt!.GetParameters();
|
var methodParams = mt!.GetParameters();
|
||||||
object? ret;
|
object? ret;
|
||||||
if (methodParams.Length == 0)
|
switch (methodParams.Length)
|
||||||
{
|
|
||||||
ret = mt.Invoke(callClass, []);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
{
|
||||||
|
case 1:
|
||||||
var pt = mt.GetParameters()[0].ParameterType;
|
var pt = mt.GetParameters()[0].ParameterType;
|
||||||
var param = pt == typeof(string)
|
var param = pt == typeof(string)
|
||||||
? [reqBody]
|
? [reqBody]
|
||||||
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) };
|
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) };
|
||||||
ret = mt.Invoke(callClass, param);
|
ret = mt.Invoke(callClass, param);
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
var headerData =
|
||||||
|
e.ApplicationMessage.UserProperties.ToDictionary(x => x.Name, x => x.Value);
|
||||||
|
var pt2 = mt.GetParameters()[0].ParameterType;
|
||||||
|
var param2 = pt2 == typeof(string)
|
||||||
|
? [reqBody]
|
||||||
|
: new[]
|
||||||
|
{
|
||||||
|
JsonSerializer.Deserialize(reqBody, pt2, SimApiUtil.JsonOption), headerData
|
||||||
|
};
|
||||||
|
ret = mt.Invoke(callClass, param2);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
ret = mt.Invoke(callClass, []);
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
res = new SimApiBaseResponse<object?>
|
res = new SimApiBaseResponse<object?>
|
||||||
@@ -71,7 +85,7 @@ public partial class Synapse
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
logger.LogError("Synapse RPC 方法异常: {Err}\n{Stack}", ex.Message,ex.StackTrace);
|
logger.LogError("Synapse RPC 方法异常: {Err}\n{Stack}", ex.Message, ex.StackTrace);
|
||||||
res = new SimApiBaseResponse(500, ex.Message);
|
res = new SimApiBaseResponse(500, ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -83,19 +97,18 @@ public partial class Synapse
|
|||||||
}
|
}
|
||||||
|
|
||||||
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
|
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
|
||||||
var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{e.ApplicationMessage.ContentType}";
|
var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{appInfo[2]}";
|
||||||
var message = new MqttApplicationMessageBuilder()
|
var message = new MqttApplicationMessageBuilder()
|
||||||
.WithTopic(reply)
|
.WithTopic(reply)
|
||||||
.WithPayload(returnJson)
|
.WithPayload(returnJson)
|
||||||
.WithRetainFlag(false)
|
.WithRetainFlag(false)
|
||||||
.Build();
|
.Build();
|
||||||
if (!Client.IsConnected) return Task.CompletedTask;
|
if (!Client.IsConnected) return;
|
||||||
Client.PublishAsync(message, CancellationToken.None).Wait();
|
Client.PublishAsync(message, CancellationToken.None).Wait();
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
"Synapse Rpc Server Return: ({BasicPropertiesMessageId}) {BasicPropertiesType}@{OptionsAppName} -> {BasicPropertiesReplyTo}\n{ReturnJson}",
|
"Synapse Rpc Server Return: ({BasicPropertiesMessageId}) {BasicPropertiesType}@{OptionsAppName} -> {BasicPropertiesReplyTo}\n{ReturnJson}",
|
||||||
e.ApplicationMessage.ContentType, action, Options.AppName, appInfo[0], returnJson);
|
appInfo[2], action, Options.AppName, appInfo[0], returnJson);
|
||||||
|
});
|
||||||
return Task.CompletedTask;
|
|
||||||
};
|
};
|
||||||
SubRpcServerTopic();
|
SubRpcServerTopic();
|
||||||
}
|
}
|
||||||
|
|||||||
+23
-9
@@ -8,7 +8,6 @@ using System.Threading.Tasks;
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using MQTTnet;
|
using MQTTnet;
|
||||||
using MQTTnet.Client;
|
|
||||||
using MQTTnet.Formatter;
|
using MQTTnet.Formatter;
|
||||||
using SimApi.Attributes;
|
using SimApi.Attributes;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
@@ -22,7 +21,7 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
{
|
{
|
||||||
private SimApiSynapseOptions Options { get; } = simApiOptions.SimApiSynapseOptions;
|
private SimApiSynapseOptions Options { get; } = simApiOptions.SimApiSynapseOptions;
|
||||||
|
|
||||||
private MqttFactory MqttFactory { get; } = new();
|
private MqttClientFactory MqttFactory { get; } = new();
|
||||||
public IMqttClient? Client { get; set; }
|
public IMqttClient? Client { get; set; }
|
||||||
|
|
||||||
private List<RegisterItem> EventRegistry { get; set; } = new();
|
private List<RegisterItem> EventRegistry { get; set; } = new();
|
||||||
@@ -87,9 +86,12 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
/// <param name="appName"></param>
|
/// <param name="appName"></param>
|
||||||
/// <param name="method"></param>
|
/// <param name="method"></param>
|
||||||
/// <param name="param"></param>
|
/// <param name="param"></param>
|
||||||
|
/// <param name="headers"></param>
|
||||||
|
/// <param name="timeout"></param>
|
||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic? param = null)
|
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic? param = null,
|
||||||
|
Dictionary<string, string>? headers = null, int? timeout = null)
|
||||||
{
|
{
|
||||||
var res = new SimApiBaseResponse(500, "Synapse Rpc Client Disabled!");
|
var res = new SimApiBaseResponse(500, "Synapse Rpc Client Disabled!");
|
||||||
if (Options.DisableRpcClient)
|
if (Options.DisableRpcClient)
|
||||||
@@ -98,7 +100,7 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
var data = FireRpc(appName, method, param);
|
var data = FireRpc(appName, method, param, headers, timeout);
|
||||||
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
|
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,10 +113,13 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
/// <param name="appName"></param>
|
/// <param name="appName"></param>
|
||||||
/// <param name="method"></param>
|
/// <param name="method"></param>
|
||||||
/// <param name="param"></param>
|
/// <param name="param"></param>
|
||||||
|
/// <param name="headers"></param>
|
||||||
|
/// <param name="timeout"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public SimApiBaseResponse<object> Rpc(string appName, string method, dynamic? param = null)
|
public SimApiBaseResponse<object> Rpc(string appName, string method, dynamic? param = null,
|
||||||
|
Dictionary<string, string>? headers = null, int? timeout = null)
|
||||||
{
|
{
|
||||||
return Rpc<object>(appName, method, param);
|
return Rpc<object>(appName, method, param, headers, timeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -141,7 +146,7 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 发送一个事件
|
/// 发送一个事件x
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="eventName"></param>
|
/// <param name="eventName"></param>
|
||||||
/// <param name="param"></param>
|
/// <param name="param"></param>
|
||||||
@@ -271,10 +276,19 @@ public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logge
|
|||||||
|
|
||||||
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(tmp.Class!);
|
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(tmp.Class!);
|
||||||
var mt = callClass.GetType().GetMethod(tmp.Method);
|
var mt = callClass.GetType().GetMethod(tmp.Method);
|
||||||
if (mt!.GetParameters().Length > 1)
|
if (mt!.GetParameters().Length > 2)
|
||||||
{
|
{
|
||||||
logger.LogError(
|
logger.LogError(
|
||||||
"Synapse Rpc Register Error: Only one or none parameter supported. {Key} -> {Method}@{Class}",
|
"Synapse Rpc Register Error: Only 1,2 or none parameter supported. {Key} -> {Method}@{Class}",
|
||||||
|
tmp.Key, tmp.Method, tmp.Class.Name);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mt.GetParameters().Length == 2 &&
|
||||||
|
mt.GetParameters()[1].ParameterType != typeof(Dictionary<string, string>))
|
||||||
|
{
|
||||||
|
logger.LogError(
|
||||||
|
"Synapse Rpc Register Error: RpcMethod Parameter 2 must be Dictionary<string, string>. {Key} -> {Method}@{Class}",
|
||||||
tmp.Key, tmp.Method, tmp.Class.Name);
|
tmp.Key, tmp.Method, tmp.Class.Name);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user