Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bbc2806995 | ||
|
|
404a638d5e | ||
|
|
e27d5e1c77 | ||
|
|
6af68da3eb | ||
|
|
7dc2ac6a86 | ||
|
|
8f6b853b6c | ||
|
|
e876486c00 | ||
|
|
e71226be4a | ||
|
|
bd674dcc31 | ||
|
|
141846d79d | ||
|
|
a4bae0226e | ||
|
|
15f74b6570 | ||
|
|
ac4619a789 | ||
|
|
4d0f801f21 | ||
|
|
683cf9176a | ||
|
|
1ee8d941e9 | ||
|
|
1d474f596a | ||
|
|
929ddaced3 | ||
|
|
82f7e0fc00 | ||
|
|
f4bc6dc080 | ||
|
|
56b0490d1e | ||
|
|
45e19c3561 | ||
|
|
04b2be1bb7 | ||
|
|
f78c3a0e0d | ||
|
|
506704fd90 | ||
|
|
786051ddbf | ||
|
|
d9ff4ae422 | ||
|
|
986b4e74e6 | ||
|
|
2257ba5b2a | ||
|
|
c40f8d664d | ||
|
|
a1f10b9c09 | ||
|
|
6ef7aca8ae | ||
|
|
4171756c54 | ||
|
|
c68cfa6192 | ||
|
|
8344567ac6 | ||
|
|
99b26d99f6 | ||
|
|
cb291691d5 | ||
|
|
47a48d0103 | ||
|
|
4c50acc309 | ||
|
|
be9092bf3c | ||
|
|
345aaa261e |
@@ -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: "7.0.100"
|
dotnet-version: "8.0.200"
|
||||||
- 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
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -5,24 +5,21 @@ using Microsoft.AspNetCore.Mvc.Filters;
|
|||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Exceptions;
|
using SimApi.Exceptions;
|
||||||
|
|
||||||
namespace SimApi.Attributes
|
namespace SimApi.Attributes;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 检测登录中间件
|
||||||
|
/// </summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
||||||
|
public class SimApiAuthAttribute : ActionFilterAttribute
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// 检测登录中间件
|
|
||||||
/// </summary>
|
|
||||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
|
||||||
public class SimApiAuthAttribute : ActionFilterAttribute
|
|
||||||
{
|
|
||||||
private string[] Types { get; }
|
private string[] Types { get; }
|
||||||
|
|
||||||
|
|
||||||
//默认是user登录类型
|
//默认是user登录类型
|
||||||
public SimApiAuthAttribute()
|
public SimApiAuthAttribute()
|
||||||
{
|
{
|
||||||
Types = new[]
|
Types = new[] { "user" };
|
||||||
{
|
|
||||||
"user"
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//只检测一种用户类型的快捷方式
|
//只检测一种用户类型的快捷方式
|
||||||
@@ -40,16 +37,13 @@ namespace SimApi.Attributes
|
|||||||
//只检测一种用户类型的快捷方式
|
//只检测一种用户类型的快捷方式
|
||||||
public SimApiAuthAttribute(string type, string url)
|
public SimApiAuthAttribute(string type, string url)
|
||||||
{
|
{
|
||||||
Types = new[]
|
Types = new[] { type };
|
||||||
{
|
|
||||||
type
|
|
||||||
};
|
|
||||||
new HttpPostAttribute(url);
|
new HttpPostAttribute(url);
|
||||||
}
|
}
|
||||||
|
|
||||||
public override void OnActionExecuting(ActionExecutingContext context)
|
public override void OnActionExecuting(ActionExecutingContext context)
|
||||||
{
|
{
|
||||||
var loginInfo = (SimApiLoginItem)context.HttpContext.Items["LoginInfo"];
|
var loginInfo = (SimApiLoginItem)context.HttpContext.Items["LoginInfo"]!;
|
||||||
//检测是否登录
|
//检测是否登录
|
||||||
if (loginInfo == null)
|
if (loginInfo == null)
|
||||||
{
|
{
|
||||||
@@ -61,5 +55,4 @@ namespace SimApi.Attributes
|
|||||||
throw new SimApiException(403);
|
throw new SimApiException(403);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
using System;
|
using System;
|
||||||
using Swashbuckle.AspNetCore.Annotations;
|
using Swashbuckle.AspNetCore.Annotations;
|
||||||
|
|
||||||
namespace SimApi.Attributes
|
namespace SimApi.Attributes;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 快捷自定义接口文档类
|
||||||
|
/// </summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
|
||||||
|
public class SimApiDocAttribute : SwaggerOperationAttribute
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// 快捷自定义接口文档类
|
|
||||||
/// </summary>
|
|
||||||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
|
|
||||||
public class SimApiDocAttribute : SwaggerOperationAttribute
|
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 定义接口说明
|
/// 定义接口说明
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -21,5 +21,4 @@ namespace SimApi.Attributes
|
|||||||
// Consumes = new[] {"application/json"};
|
// Consumes = new[] {"application/json"};
|
||||||
// Produces = new[] {"application/json"};
|
// Produces = new[] {"application/json"};
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -3,12 +3,7 @@ using System;
|
|||||||
namespace SimApi.Attributes;
|
namespace SimApi.Attributes;
|
||||||
|
|
||||||
[AttributeUsage(AttributeTargets.Method)]
|
[AttributeUsage(AttributeTargets.Method)]
|
||||||
public class SynapseEventAttribute : Attribute
|
public class SynapseEventAttribute(string? name = null) : Attribute
|
||||||
{
|
{
|
||||||
public string Name { get; }
|
public string? Name { get; } = name;
|
||||||
|
|
||||||
public SynapseEventAttribute(string name)
|
|
||||||
{
|
|
||||||
Name = name;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,7 @@ namespace SimApi.Attributes;
|
|||||||
[AttributeUsage(AttributeTargets.Method)]
|
[AttributeUsage(AttributeTargets.Method)]
|
||||||
public class SynapseRpcAttribute : Attribute
|
public class SynapseRpcAttribute : Attribute
|
||||||
{
|
{
|
||||||
public string Name { get; }
|
public string? Name { get; }
|
||||||
|
|
||||||
public SynapseRpcAttribute()
|
public SynapseRpcAttribute()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Microsoft.Extensions.Caching.Distributed;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using SimApi.Communications;
|
||||||
|
using SimApi.Configurations;
|
||||||
|
using SimApi.Helpers;
|
||||||
|
|
||||||
|
namespace SimApi.CoceSdk;
|
||||||
|
|
||||||
|
public class CoceApp(SimApiOptions simApiOptions, ILogger<CoceApp> logger, IDistributedCache cache)
|
||||||
|
{
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取Level Token
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="lv1Token"></param>
|
||||||
|
/// <param name="level"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public LevelTokenResponse? GetLevelToken(string lv1Token, int level = 5)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "lv1Token", lv1Token },
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
{ "level", level }
|
||||||
|
};
|
||||||
|
return QueryAppApi<LevelTokenResponse>("/api/app/token", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 通过用户手机号搜索用户
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="phone"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public UserInfo? SearchUserByPhone(string phone)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "cell", phone },
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
};
|
||||||
|
return QueryAppApi<UserInfo>("/api/app/user/search-by-phone", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 通过给出的UserId列表获取用户信息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userIds"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public UserInfo[]? SearchUserByIds(IEnumerable<string> userIds)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "ids", string.Join(",", userIds) },
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
};
|
||||||
|
return QueryAppApi<UserInfo[]>("/api/app/user/search-by-ids", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 向用户发送消息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="userId"></param>
|
||||||
|
/// <param name="title"></param>
|
||||||
|
/// <param name="content"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public bool SendUserMessage(string userId, string title, string content)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
{ "userId", userId },
|
||||||
|
{ "type", "text" },
|
||||||
|
{ "title", title },
|
||||||
|
{ "text", content }
|
||||||
|
};
|
||||||
|
return QueryAppApiNoResp("/api/app/message", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 创建交易订单号
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="name"></param>
|
||||||
|
/// <param name="amount"></param>
|
||||||
|
/// <param name="ext"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public string? TradeCreate(string name, int amount, string ext)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
{ "amount", amount },
|
||||||
|
{ "ext", ext },
|
||||||
|
{ "name", name }
|
||||||
|
};
|
||||||
|
return QueryAppApi<string>("/api/app/trade/create", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 查询订单状态
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="tradeNo"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public CheckTradeResponse? TradeCheck(string tradeNo)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
{ "tradeNo", tradeNo }
|
||||||
|
};
|
||||||
|
return QueryAppApi<CheckTradeResponse>("/api/app/trade/result", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 对订单进行退款
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="tradeNo"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public bool TradeRefund(string tradeNo)
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object>
|
||||||
|
{
|
||||||
|
{ "time", (int)SimApiUtil.TimestampNow },
|
||||||
|
{ "appId", simApiOptions.CoceSdkOptions.AppId! },
|
||||||
|
{ "tradeNo", tradeNo }
|
||||||
|
};
|
||||||
|
return QueryAppApiNoResp("/api/app/trade/refund", dict);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private T? QueryAppApi<T>(string endpoint, Dictionary<string, object> request)
|
||||||
|
{
|
||||||
|
var response = QueryAppApi(endpoint, request);
|
||||||
|
var result = response.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result!;
|
||||||
|
if (result.Code == 200) return result.Data;
|
||||||
|
logger.LogDebug("发生错误: {Code} => {Message}", result.Code, result.Message);
|
||||||
|
return default;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool QueryAppApiNoResp(string endpoint, Dictionary<string, object> request)
|
||||||
|
{
|
||||||
|
var response = QueryAppApi(endpoint, request);
|
||||||
|
var result = response.Content.ReadFromJsonAsync<SimApiBaseResponse>().Result!;
|
||||||
|
return result.Code == 200;
|
||||||
|
}
|
||||||
|
|
||||||
|
private HttpResponseMessage QueryAppApi(string endpoint, Dictionary<string, object> request)
|
||||||
|
{
|
||||||
|
var platUrl = simApiOptions.CoceSdkOptions.ApiEndpoint + endpoint;
|
||||||
|
var sorted = request.OrderBy(x => x.Key);
|
||||||
|
var signStr = sorted.Aggregate("", (current, item) => current + $"{item.Key}={item.Value}&").TrimEnd('&');
|
||||||
|
logger.LogDebug("签名的字符串: {SignStr}", signStr);
|
||||||
|
var sign = SimApiUtil.Md5(signStr + simApiOptions.CoceSdkOptions.AppKey);
|
||||||
|
logger.LogDebug("签名: {Sign}", sign);
|
||||||
|
request.Add("sign", sign);
|
||||||
|
logger.LogDebug("请求地址: {PlatUrl} => {Data}", platUrl, JsonSerializer.Serialize(request));
|
||||||
|
var http = new HttpClient();
|
||||||
|
return http.PostAsJsonAsync(platUrl, request).Result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取用户的群组信息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="token">Level >=2 的Token</param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public IEnumerable<GroupInfo>? GetUserGroups(string token)
|
||||||
|
{
|
||||||
|
const string uri = "/api/lv2/user/groups";
|
||||||
|
var resp = ProxyQuery<GroupInfo[]>(uri, token,"{}");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取用户信息
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public UserInfo? GetUserInfo(string token)
|
||||||
|
{
|
||||||
|
const string uri = "/api/lv1/user/info";
|
||||||
|
return ProxyQuery<UserInfo>(uri, token);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SaveToken(string userId, string levelToken)
|
||||||
|
{
|
||||||
|
cache.SetString($"LEVEL:TOKEN:{userId}", levelToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string? GetToken(string userId)
|
||||||
|
{
|
||||||
|
return cache.GetString($"LEVEL:TOKEN:{userId}");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public dynamic? ProxyQuery(string uri, string token, string json) => ProxyQuery<dynamic>(uri, token, json);
|
||||||
|
|
||||||
|
public dynamic? ProxyQueue(string uri, string token, object data) =>
|
||||||
|
ProxyQuery<dynamic>(uri, token, JsonSerializer.Serialize(data));
|
||||||
|
|
||||||
|
public T? ProxyQueue<T>(string uri, string token, object data) =>
|
||||||
|
ProxyQuery<T>(uri, token, JsonSerializer.Serialize(data));
|
||||||
|
|
||||||
|
public T? ProxyQuery<T>(string uri, string token, string json = "{}")
|
||||||
|
{
|
||||||
|
var http = new HttpClient();
|
||||||
|
http.DefaultRequestHeaders.Add("Token", token);
|
||||||
|
var realUrl = simApiOptions.CoceSdkOptions.ApiEndpoint + uri;
|
||||||
|
var response = http.PostAsync(realUrl, new StringContent(json, Encoding.UTF8, "application/json"))
|
||||||
|
.Result;
|
||||||
|
var resp = response.Content.ReadFromJsonAsync<SimApiBaseResponse<T>>().Result!;
|
||||||
|
if (resp.Code != 200)
|
||||||
|
{
|
||||||
|
logger.LogDebug("请求发生错误: {RespCode} => {RespMessage}", resp.Code, resp.Message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return resp.Code == 200 ? resp.Data : default;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ConfigResponse GetConfig()
|
||||||
|
{
|
||||||
|
return new ConfigResponse(simApiOptions.CoceSdkOptions.AppId!, simApiOptions.CoceSdkOptions.AuthEndpoint);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace SimApi.CoceSdk;
|
||||||
|
|
||||||
|
public class CoceAppSdkOption
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* 中心API服务器地址
|
||||||
|
*/
|
||||||
|
public string ApiEndpoint { get; set; } = "https://api.coce.cc";
|
||||||
|
|
||||||
|
public string AuthEndpoint { get; set; } = "https://home.coce.cc";
|
||||||
|
|
||||||
|
public string? AppId { get; set; }
|
||||||
|
|
||||||
|
public string? AppKey { get; set; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace SimApi.CoceSdk;
|
||||||
|
|
||||||
|
public record ConfigResponse(string AppId, string AuthUrl);
|
||||||
|
|
||||||
|
public record LevelTokenResponse(string Token, string UserId, int TokenLevel);
|
||||||
|
|
||||||
|
public record GroupInfo(string Id, string Name, string Image, string Description, string Role);
|
||||||
|
|
||||||
|
public record UserInfo(string UserId, string Name, string Image);
|
||||||
|
|
||||||
|
public record CheckTradeResponse(
|
||||||
|
string TradeNo,
|
||||||
|
int Amount,
|
||||||
|
int Fee,
|
||||||
|
string Name,
|
||||||
|
string? Ext,
|
||||||
|
string Status,
|
||||||
|
DateTime CreatedAt,
|
||||||
|
DateTime? FinishedAt,
|
||||||
|
DateTime? RefundAt,
|
||||||
|
DateTime? CloseAt);
|
||||||
|
|
||||||
|
public class UserInfoWithGroup
|
||||||
|
{
|
||||||
|
public string? UserId { get; set; }
|
||||||
|
|
||||||
|
public string? Name { get; set; }
|
||||||
|
|
||||||
|
public string? LevelToken { get; set; }
|
||||||
|
|
||||||
|
public UserGroupItem[]? UserGroupItems { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class UserGroupItem
|
||||||
|
{
|
||||||
|
public string? GroupId { get; set; }
|
||||||
|
|
||||||
|
public string? GroupName { get; set; }
|
||||||
|
|
||||||
|
public string? GroupRole { get; set; }
|
||||||
|
}
|
||||||
@@ -1,23 +1,37 @@
|
|||||||
namespace SimApi.Communications
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
|
||||||
|
namespace SimApi.Communications;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 只有ID的请求
|
||||||
|
/// </summary>
|
||||||
|
public class SimApiIdOnlyRequest
|
||||||
{
|
{
|
||||||
/// <summary>
|
[Required] public int Id { get; set; }
|
||||||
/// 只有ID的请求
|
}
|
||||||
/// </summary>
|
|
||||||
public record SimApiIdOnlyRequest(int Id);
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 只有ID的请求(字符串)
|
/// 只有ID的请求(字符串)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public record SimApiStringIdOnlyRequest(string Id);
|
public class SimApiStringIdOnlyRequest
|
||||||
|
{
|
||||||
|
[Required] public string? Id { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 动态类型单字段请求
|
/// 动态类型单字段请求
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <typeparam name="T"></typeparam>
|
/// <typeparam name="T"></typeparam>
|
||||||
public record SimApiOneFieldRequest<T>(T Data);
|
public class SimApiOneFieldRequest<T>
|
||||||
|
{
|
||||||
|
[Required] public T? Data { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 基础分页请求
|
/// 基础分页请求
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public record SimApiBasePageRequest(int Page, int Count);
|
public class SimApiBasePageRequest
|
||||||
|
{
|
||||||
|
[Required] public int Page { get; set; }
|
||||||
|
[Required] public int Count { get; set; }
|
||||||
}
|
}
|
||||||
@@ -1,43 +1,33 @@
|
|||||||
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;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 基础相应
|
||||||
|
/// </summary>
|
||||||
|
public class SimApiBaseResponse(int code = 200, string message = "成功")
|
||||||
{
|
{
|
||||||
/// <summary>
|
public int Code { get; set; } = code;
|
||||||
/// 基础相应
|
public string Message { get; set; } = message;
|
||||||
/// </summary>
|
|
||||||
public record SimApiBaseResponse(int Code = 200, string Message = "成功")
|
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 默认错误代码对应提示信息
|
/// 默认错误代码对应提示信息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private static readonly Dictionary<int, string> MsgBox = new()
|
private static readonly Dictionary<int, string> MsgBox = new()
|
||||||
{
|
{
|
||||||
{
|
{ 200, "成功" },
|
||||||
200, "成功"
|
{ 204, "没有数据" },
|
||||||
},
|
{ 400, "参数错误" },
|
||||||
{
|
{ 401, "需要登录" },
|
||||||
204, "没有数据"
|
{ 403, "无权访问" },
|
||||||
},
|
{ 404, "接口不存在" },
|
||||||
{
|
{ 500, "服务器错误" }
|
||||||
400, "参数错误"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
401, "需要登录"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
403, "无权访问"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
404, "接口不存在"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
500, "服务器错误"
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
public SimApiBaseResponse(int code) : this(code, MsgBox.ContainsKey(code) ? MsgBox[code] : "未知错误")
|
public SimApiBaseResponse(int code) : this(code, MsgBox.GetValueOrDefault(code, "未知错误"))
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,30 +37,40 @@ namespace SimApi.Communications
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public override string ToString()
|
public override string ToString()
|
||||||
{
|
{
|
||||||
return JsonSerializer.Serialize(this, new JsonSerializerOptions
|
return SimApiUtil.Json(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 动态内容分页
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
public class SimApiBasePageResponse<T>() : SimApiBaseResponse
|
||||||
|
{
|
||||||
|
public T? List { get; set; }
|
||||||
|
public int Page { get; set; } = 1;
|
||||||
|
public int Count { get; set; } = 20;
|
||||||
|
public int Total { get; set; }
|
||||||
|
|
||||||
|
public SimApiBasePageResponse(T list, int page, int count, int total) : this()
|
||||||
{
|
{
|
||||||
IgnoreReadOnlyProperties = true,
|
List = list;
|
||||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
Page = page;
|
||||||
Converters =
|
Count = count;
|
||||||
|
Total = total;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 动态Data返回
|
||||||
|
/// </summary>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
public class SimApiBaseResponse<T>() : SimApiBaseResponse
|
||||||
|
{
|
||||||
|
public T? Data { get; set; }
|
||||||
|
|
||||||
|
public SimApiBaseResponse(T data) : this()
|
||||||
{
|
{
|
||||||
new JsonStringEnumConverter()
|
Data = data;
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 动态内容分页
|
|
||||||
/// </summary>
|
|
||||||
/// <typeparam name="T"></typeparam>
|
|
||||||
public record SimApiBasePageResponse<T>
|
|
||||||
(T List, int Page = 1, int Count = 1, int Total = 1, int Code = 200,
|
|
||||||
string Message = "成功") : SimApiBaseResponse(Code, Message);
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 动态Data返回
|
|
||||||
/// </summary>
|
|
||||||
/// <typeparam name="T"></typeparam>
|
|
||||||
public record SimApiBaseResponse<T>(T Data, int Code = 200, string Message = "成功") : SimApiBaseResponse(Code,
|
|
||||||
Message);
|
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,14 @@
|
|||||||
namespace SimApi.Communications
|
using System.Collections.Generic;
|
||||||
|
|
||||||
|
namespace SimApi.Communications;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 登录信息中间件
|
||||||
|
/// </summary>
|
||||||
|
public class SimApiLoginItem
|
||||||
{
|
{
|
||||||
/// <summary>
|
public string? Id { get; set; }
|
||||||
/// 登录信息中间件
|
public string[] Type { get; set; } = new[] { "user" };
|
||||||
/// </summary>
|
public Dictionary<string, string>? Meta { get; set; } = null;
|
||||||
public record SimApiLoginItem(string Id, string[] Type);
|
public object? Extra { get; set; } = null;
|
||||||
}
|
};
|
||||||
@@ -1,47 +1,50 @@
|
|||||||
using System;
|
using System.Collections.Generic;
|
||||||
using System.Collections.Generic;
|
|
||||||
using Swashbuckle.AspNetCore.SwaggerUI;
|
using Swashbuckle.AspNetCore.SwaggerUI;
|
||||||
|
|
||||||
namespace SimApi.Configs
|
namespace SimApi.Configurations;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 文档组配置
|
||||||
|
/// </summary>
|
||||||
|
public class SimApiDocGroupOption
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// 文档组配置
|
|
||||||
/// </summary>
|
|
||||||
public class SimApiDocGroupOption
|
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 文档标识
|
/// 文档标识
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string Id { get; set; }
|
public string Id { get; set; } = null!;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 文档名称
|
/// 文档名称
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string Name { get; set; }
|
public string Name { get; set; } = null!;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 文档描述
|
/// 文档描述
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string Description { get; set; }
|
public string Description { get; set; } = null!;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 授权配置, Type支持 "SimApiAuth","ClientCredentials","Implicit","AuthorizationCode"
|
||||||
|
/// </summary>
|
||||||
|
public class SimApiAuthOption
|
||||||
|
{
|
||||||
|
public string[] Type { get; set; } = new[] { "SimApiAuth" };
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 授权配置, Type支持 "SimApiAuth","ClientCredentials","Implicit","AuthorizationCode"
|
|
||||||
/// </summary>
|
|
||||||
public class SimApiAuthOption
|
|
||||||
{
|
|
||||||
public string[] Type { get; set; } = new[] {"SimApiAuth"};
|
|
||||||
public string Description { get; set; } = "认证服务器颁发的AccessToken";
|
public string Description { get; set; } = "认证服务器颁发的AccessToken";
|
||||||
public string AuthorizationUrl { get; set; }
|
|
||||||
public string TokenUrl { get; set; }
|
|
||||||
public Dictionary<string, string> Scopes { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
public string AuthorizationUrl { get; set; } = null!;
|
||||||
/// 文档配置
|
|
||||||
/// </summary>
|
public string TokenUrl { get; set; } = null!;
|
||||||
public class SimApiDocOptions
|
|
||||||
{
|
public Dictionary<string, string> Scopes { get; set; } = null!;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 文档配置
|
||||||
|
/// </summary>
|
||||||
|
public class SimApiDocOptions
|
||||||
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 文档组配置
|
/// 文档组配置
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -68,6 +71,5 @@ namespace SimApi.Configs
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// 接口支持的调用方式
|
/// 接口支持的调用方式
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public SubmitMethod[] SupportedMethod { get; set; } = new[] {SubmitMethod.Post};
|
public SubmitMethod[] SupportedMethod { get; set; } = new[] { SubmitMethod.Post };
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using SimApi.CoceSdk;
|
||||||
|
|
||||||
namespace SimApi.Configs
|
namespace SimApi.Configurations;
|
||||||
|
|
||||||
|
public class SimApiOptions
|
||||||
{
|
{
|
||||||
public class SimApiOptions
|
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用全部Cors,对于开发前后分离的时候很有用。
|
/// 启用全部Cors,对于开发前后分离的时候很有用。
|
||||||
/// default: true
|
/// default: true
|
||||||
@@ -11,16 +12,24 @@ namespace SimApi.Configs
|
|||||||
public bool EnableCors { get; set; } = true;
|
public bool EnableCors { get; set; } = true;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用SimapiAuth,一个简单的基于Header Token的认证方式。
|
/// 启用SimApiAuth,一个简单的基于Header Token的认证方式。
|
||||||
/// default: false
|
/// default: false
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiAuth { get; set; } = false;
|
public bool EnableSimApiAuth { get; set; }
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否使用CoceSdk
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableCoceSdk { get; set; }
|
||||||
|
|
||||||
|
public CoceAppSdkOption CoceSdkOptions { get; set; } = new();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用在线文档,启用后 访问 /swagger 可以查看对应的api文档。
|
/// 启用在线文档,启用后 访问 /swagger 可以查看对应的api文档。
|
||||||
/// default: false
|
/// default: false
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiDoc { get; set; } = false;
|
public bool EnableSimApiDoc { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 启用异常拦截,启用后,所有的异常将被通过json反馈。
|
/// 启用异常拦截,启用后,所有的异常将被通过json反馈。
|
||||||
@@ -28,11 +37,16 @@ namespace SimApi.Configs
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiException { get; set; } = true;
|
public bool EnableSimApiException { get; set; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 启用返回结果拦截
|
||||||
|
/// </summary>
|
||||||
|
public bool EnableSimApiResponseFilter { get; set; } = true;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 开启S3兼容的存储系统。
|
/// 开启S3兼容的存储系统。
|
||||||
/// default: false
|
/// default: false
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSimApiStorage { get; set; } = false;
|
public bool EnableSimApiStorage { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
|
/// 开启ForwardHeaders,开启后可以透传负载均衡的Headers
|
||||||
@@ -50,44 +64,43 @@ namespace SimApi.Configs
|
|||||||
/// 启用格式化的 Console Logger
|
/// 启用格式化的 Console Logger
|
||||||
/// default: false
|
/// default: false
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableLogger { get; set; } = false;
|
public bool EnableLogger { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 是否启用Synapse
|
/// 是否启用Synapse
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public bool EnableSynapse { get; set; } = false;
|
public bool EnableSynapse { get; set; }
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Swagger文档相关配置,需要启用 EnableSimApiDoc
|
/// Swagger文档相关配置,需要启用 EnableSimApiDoc
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public SimApiDocOptions SimApiDocOptions { get; set; } = new SimApiDocOptions();
|
public SimApiDocOptions SimApiDocOptions { get; set; } = new();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// S3兼容的存储系统配置,需要启用 EnableSimApiStorage
|
/// S3兼容的存储系统配置,需要启用 EnableSimApiStorage
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public SimApiStorageOptions SimApiStorageOptions { get; set; } = new SimApiStorageOptions();
|
public SimApiStorageOptions SimApiStorageOptions { get; set; } = new();
|
||||||
|
|
||||||
public SimApiSynapseOptions SimApiSynapseOptions { get; set; } = new SimApiSynapseOptions();
|
public SimApiSynapseOptions SimApiSynapseOptions { get; set; } = new();
|
||||||
|
|
||||||
public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions> options = null)
|
public void ConfigureSimApiSynapse(Action<SimApiSynapseOptions>? options = null)
|
||||||
{
|
{
|
||||||
options?.Invoke(SimApiSynapseOptions);
|
options?.Invoke(SimApiSynapseOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ConfigureSimApiSynapse(SimApiSynapseOptions options)
|
public void ConfigureCoceSdk(Action<CoceAppSdkOption>? options = null)
|
||||||
{
|
{
|
||||||
SimApiSynapseOptions = options;
|
options?.Invoke(CoceSdkOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ConfigureSimApiDoc(Action<SimApiDocOptions> options = null)
|
public void ConfigureSimApiDoc(Action<SimApiDocOptions>? options = null)
|
||||||
{
|
{
|
||||||
options?.Invoke(SimApiDocOptions);
|
options?.Invoke(SimApiDocOptions);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void ConfigureSimApiStorage(Action<SimApiStorageOptions> options = null)
|
public void ConfigureSimApiStorage(Action<SimApiStorageOptions>? options = null)
|
||||||
{
|
{
|
||||||
options?.Invoke(SimApiStorageOptions);
|
options?.Invoke(SimApiStorageOptions);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,24 +1,23 @@
|
|||||||
namespace SimApi.Configs
|
namespace SimApi.Configurations;
|
||||||
|
|
||||||
|
public class SimApiStorageOptions
|
||||||
{
|
{
|
||||||
public class SimApiStorageOptions
|
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// S3 服务器入口地址
|
/// S3 服务器入口地址
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string Endpoint { get; set; }
|
public string? Endpoint { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// S3 服务器文件访问地址
|
/// S3 服务器文件访问地址
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string ServeUrl { get; set; }
|
public string? ServeUrl { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// S3服务 Bucket
|
/// S3服务 Bucket
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string Bucket { get; set; }
|
public string? Bucket { get; set; }
|
||||||
|
|
||||||
public string AccessKey { get; set; }
|
public string? AccessKey { get; set; }
|
||||||
|
|
||||||
public string SecretKey { get; set; }
|
public string? SecretKey { get; set; }
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,30 +1,25 @@
|
|||||||
namespace SimApi.Configs;
|
namespace SimApi.Configurations;
|
||||||
|
|
||||||
public class SimApiSynapseOptions
|
public class SimApiSynapseOptions
|
||||||
{
|
{
|
||||||
public string MqHost { get; set; }
|
/// <summary>
|
||||||
|
/// Mqtt服务器的Websocket地址
|
||||||
public int MqPort { get; set; }
|
/// </summary>
|
||||||
|
public string? Websocket { get; set; }
|
||||||
public string MqUser { get; set; }
|
public string? Username { get; set; }
|
||||||
|
public string? Password { get; set; }
|
||||||
public string MqPass { get; set; }
|
public string? SysName { get; set; }
|
||||||
|
public string? AppName { get; set; }
|
||||||
public string MqVHost { get; set; } = "/";
|
public string? AppId { get; set; }
|
||||||
|
|
||||||
public string SysName { get; set; }
|
|
||||||
|
|
||||||
public string AppName { get; set; }
|
|
||||||
|
|
||||||
public string AppId { get; set; }
|
|
||||||
|
|
||||||
public int RpcTimeout { get; set; } = 3;
|
public int RpcTimeout { get; set; } = 3;
|
||||||
|
|
||||||
public ushort EventProcessorNum { get; set; } = 20;
|
/// <summary>
|
||||||
|
/// Event是否使用负载均衡
|
||||||
public ushort RpcProcessorNum { get; set; } = 20;
|
/// 也就是订阅$queue主题,消息会分发给不同的AppId
|
||||||
|
/// 如果false,多个AppId都可以同时收到消息
|
||||||
|
/// </summary>
|
||||||
|
public bool EventLoadBalancing { get; set; } = false;
|
||||||
|
public bool EnableConfigStore { get; set; } = true;
|
||||||
public bool DisableEventClient { get; set; } = false;
|
public bool DisableEventClient { get; set; } = false;
|
||||||
|
|
||||||
public bool DisableRpcClient { get; set; } = false;
|
public bool DisableRpcClient { get; set; } = false;
|
||||||
}
|
}
|
||||||
@@ -4,22 +4,21 @@ using Microsoft.AspNetCore.Mvc.Filters;
|
|||||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using SimApi.Exceptions;
|
using SimApi.Exceptions;
|
||||||
using SimApi.Attributes;
|
|
||||||
|
|
||||||
namespace SimApi.Controllers
|
namespace SimApi.Controllers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 基础控制器,所有控制器均继承本控制器
|
||||||
|
/// 1. 自动验证请求参数
|
||||||
|
/// 2. 报错返回
|
||||||
|
/// 3. 错误回馈页面
|
||||||
|
/// </summary>
|
||||||
|
public class SimApiBaseController : Controller
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// 基础控制器,所有控制器均继承本控制器
|
|
||||||
/// 1. 自动验证请求参数
|
|
||||||
/// 2. 报错返回
|
|
||||||
/// 3. 错误回馈页面
|
|
||||||
/// </summary>
|
|
||||||
public class SimApiBaseController : Controller
|
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 当前登录用户的ID
|
/// 当前登录用户的ID
|
||||||
/// </summary>
|
/// </summary>
|
||||||
protected SimApiLoginItem LoginInfo => (SimApiLoginItem)HttpContext.Items["LoginInfo"];
|
protected SimApiLoginItem LoginInfo => (SimApiLoginItem)HttpContext.Items["LoginInfo"]!;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 验证请求参数
|
/// 验证请求参数
|
||||||
@@ -27,8 +26,7 @@ namespace SimApi.Controllers
|
|||||||
/// <param name="context"></param>
|
/// <param name="context"></param>
|
||||||
public override void OnActionExecuting(ActionExecutingContext context)
|
public override void OnActionExecuting(ActionExecutingContext context)
|
||||||
{
|
{
|
||||||
if (!context.ModelState.IsValid)
|
if (context.ModelState.IsValid) return;
|
||||||
{
|
|
||||||
foreach (var item in context.ModelState.Values.Where(item =>
|
foreach (var item in context.ModelState.Values.Where(item =>
|
||||||
item.ValidationState == ModelValidationState.Invalid))
|
item.ValidationState == ModelValidationState.Invalid))
|
||||||
{
|
{
|
||||||
@@ -36,7 +34,6 @@ namespace SimApi.Controllers
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -51,12 +48,12 @@ namespace SimApi.Controllers
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 检测条件,根据条件返回报错
|
/// 检测条件,根据条件返回报错 如果condition是ture报错
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="condition">检测条件</param>
|
/// <param name="condition">检测条件</param>
|
||||||
/// <param name="code">错误代码</param>
|
/// <param name="code">错误代码</param>
|
||||||
/// <param name="message">错误描述</param>
|
/// <param name="message">错误描述</param>
|
||||||
protected static void ErrorWhen(bool condition, int code = 500, string message = "")
|
protected static void ErrorWhen(bool condition, int code = 400, string message = "")
|
||||||
{
|
{
|
||||||
if (condition)
|
if (condition)
|
||||||
{
|
{
|
||||||
@@ -64,13 +61,37 @@ namespace SimApi.Controllers
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 检测条件,根据条件返回报错 如果condition是ture报错
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="condition">检测条件</param>
|
||||||
|
/// <param name="code">错误代码</param>
|
||||||
|
/// <param name="message">错误描述</param>
|
||||||
|
protected static void ErrorWhenTrue(bool condition, int code = 400, string message = "")
|
||||||
|
{
|
||||||
|
ErrorWhen(condition, code, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 如果condition是false 报错
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="condition"></param>
|
||||||
|
/// <param name="code"></param>
|
||||||
|
/// <param name="message"></param>
|
||||||
|
protected static void ErrorWhenFalse(bool condition, int code = 400, string message = "")
|
||||||
|
{
|
||||||
|
ErrorWhen(!condition, code, message);
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 检测给定的变量是否为NUll
|
/// 检测给定的变量是否为NUll
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="condition">检测条件</param>
|
/// <param name="condition">检测条件</param>
|
||||||
/// <param name="code">错误代码</param>
|
/// <param name="code">错误代码</param>
|
||||||
/// <param name="message">错误描述</param>
|
/// <param name="message">错误描述</param>
|
||||||
protected static void ErrorWhenNull(object condition, int code = 404, string message = "")
|
protected static void ErrorWhenNull(object? condition, int code = 404, string message = "请求的资源不存在")
|
||||||
{
|
{
|
||||||
ErrorWhen(condition == null, code, message);
|
ErrorWhen(condition == null, code, message);
|
||||||
}
|
}
|
||||||
@@ -81,7 +102,6 @@ namespace SimApi.Controllers
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
protected SimApiBaseResponse<string> UploadFile()
|
protected SimApiBaseResponse<string> UploadFile()
|
||||||
{
|
{
|
||||||
return new SimApiBaseResponse<string>(null);
|
return new SimApiBaseResponse<string>();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using SimApi.Attributes;
|
||||||
|
using SimApi.CoceSdk;
|
||||||
|
using SimApi.Communications;
|
||||||
|
using SimApi.Helpers;
|
||||||
|
|
||||||
|
namespace SimApi.Controllers;
|
||||||
|
|
||||||
|
public class SimApiCoceController(CoceApp coce,SimApiAuth auth) : SimApiBaseController
|
||||||
|
{
|
||||||
|
[HttpPost]
|
||||||
|
public SimApiBaseResponse<ConfigResponse> GetConfig()
|
||||||
|
{
|
||||||
|
return new SimApiBaseResponse<ConfigResponse>(coce.GetConfig());
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost]
|
||||||
|
public SimApiBaseResponse<string> Login([FromBody] SimApiOneFieldRequest<string> request)
|
||||||
|
{
|
||||||
|
var data = coce.GetLevelToken(request.Data!);
|
||||||
|
ErrorWhenNull(data, 400);
|
||||||
|
coce.SaveToken(data!.UserId, data.Token);
|
||||||
|
var userinfo = coce.GetUserInfo(data!.Token);
|
||||||
|
var meta = new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
{ "name", userinfo!.Name },
|
||||||
|
{ "image", userinfo.Image }
|
||||||
|
};
|
||||||
|
var groups = coce.GetUserGroups(data.Token!)!;
|
||||||
|
var loginItem = new SimApiLoginItem
|
||||||
|
{
|
||||||
|
Id = data.UserId,
|
||||||
|
Meta = meta,
|
||||||
|
Extra = groups
|
||||||
|
};
|
||||||
|
return new SimApiBaseResponse<string>(auth.Login(loginItem));
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost, SimApiAuth]
|
||||||
|
public SimApiBaseResponse<GroupInfo[]> ListGroups()
|
||||||
|
{
|
||||||
|
var levelToken = coce.GetToken(LoginInfo.Id!);
|
||||||
|
var groups = coce.GetUserGroups(levelToken!)!;
|
||||||
|
return new SimApiBaseResponse<GroupInfo[]>(groups.ToArray());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,21 +1,11 @@
|
|||||||
using System;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using SimApi.Attributes;
|
using SimApi.Attributes;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Controllers
|
namespace SimApi.Controllers;
|
||||||
|
public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
|
||||||
{
|
{
|
||||||
[ApiExplorerSettings(GroupName = "api")]
|
|
||||||
public class YYCommonController : SimApiBaseController
|
|
||||||
{
|
|
||||||
private SimApiAuth Auth { get; }
|
|
||||||
|
|
||||||
public YYCommonController(SimApiAuth auth)
|
|
||||||
{
|
|
||||||
Auth = auth;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 错误回馈页面
|
/// 错误回馈页面
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -32,29 +22,37 @@ namespace SimApi.Controllers
|
|||||||
/// 检测用户登陆的控制器
|
/// 检测用户登陆的控制器
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost("/auth/check"), SimApiDoc("认证", "检测登陆")]
|
[HttpPost, SimApiDoc("认证", "检测登陆")]
|
||||||
public SimApiBaseResponse<string> CheckLogin()
|
public SimApiBaseResponse<string> CheckLogin()
|
||||||
{
|
{
|
||||||
ErrorWhenNull(LoginInfo, 401);
|
ErrorWhenNull(LoginInfo, 401,"未登录");
|
||||||
return new SimApiBaseResponse<string>(LoginInfo.Id);
|
return new SimApiBaseResponse<string>
|
||||||
|
{
|
||||||
|
Data = LoginInfo.Id
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 退出登陆
|
/// 退出登陆
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
[HttpPost("/auth/logout"), SimApiDoc("认证", "退出登陆")]
|
[HttpPost, SimApiDoc("认证", "退出登陆")]
|
||||||
public SimApiBaseResponse Logout()
|
public SimApiBaseResponse Logout()
|
||||||
{
|
{
|
||||||
string token = null;
|
string? token = null;
|
||||||
|
|
||||||
if (Request.Headers.ContainsKey("Token"))
|
if (Request.Headers.TryGetValue("Token", out var value))
|
||||||
{
|
{
|
||||||
token = Request.Headers["Token"];
|
token = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
Auth.Logout(token);
|
auth.Logout(token!);
|
||||||
return new SimApiBaseResponse();
|
return new SimApiBaseResponse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpPost,SimApiAuth]
|
||||||
|
public SimApiBaseResponse<SimApiLoginItem> UserInfo()
|
||||||
|
{
|
||||||
|
return new SimApiBaseResponse<SimApiLoginItem>(LoginInfo);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,11 @@
|
|||||||
using System;
|
using System;
|
||||||
namespace SimApi.Exceptions
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Api错误捕获异常
|
|
||||||
/// </summary>
|
|
||||||
public class SimApiException : Exception
|
|
||||||
{
|
|
||||||
public int Code { get; }
|
|
||||||
|
|
||||||
public SimApiException(int code, string message = "") : base(message)
|
namespace SimApi.Exceptions;
|
||||||
{
|
|
||||||
Code = code;
|
/// <summary>
|
||||||
}
|
/// Api错误捕获异常
|
||||||
}
|
/// </summary>
|
||||||
|
public class SimApiException(int code, string message = "") : Exception(message)
|
||||||
|
{
|
||||||
|
public int Code { get; } = code;
|
||||||
}
|
}
|
||||||
+22
-32
@@ -1,48 +1,39 @@
|
|||||||
|
#nullable enable
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using Microsoft.AspNetCore.Http;
|
|
||||||
using Microsoft.Extensions.Caching.Distributed;
|
using Microsoft.Extensions.Caching.Distributed;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
|
|
||||||
namespace SimApi.Helpers
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 认证助手
|
||||||
|
/// </summary>
|
||||||
|
public class SimApiAuth(IDistributedCache cache)
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 认证助手
|
/// 登录信息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class SimApiAuth
|
/// <param name="loginItem"></param>
|
||||||
|
/// <param name="token"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public string Login(SimApiLoginItem loginItem, string? token = null)
|
||||||
{
|
{
|
||||||
private IDistributedCache Cache { get; }
|
token ??= Guid.NewGuid().ToString();
|
||||||
|
cache.SetString(token, JsonSerializer.Serialize(loginItem));
|
||||||
public SimApiAuth(IDistributedCache cache)
|
return token;
|
||||||
{
|
|
||||||
Cache = cache;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 产生一个Token记录并返回Token
|
/// 获取登陆信息
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="id"></param>
|
/// <param name="token"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public string Login(string id, string type = "user", string token = null)
|
public SimApiLoginItem? GetLogin(string token)
|
||||||
{
|
{
|
||||||
return Login(id, new[]
|
var login = cache.GetString(token);
|
||||||
{
|
return login != null ? JsonSerializer.Deserialize<SimApiLoginItem>(login) : default;
|
||||||
type
|
|
||||||
}, token);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// 产生一个Token并记录用户ID角色[多角色]
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="id"></param>
|
|
||||||
/// <param name="type"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public string Login(string id, string[] type, string uuid = null)
|
|
||||||
{
|
|
||||||
uuid ??= Guid.NewGuid().ToString();
|
|
||||||
var loginItem = new SimApiLoginItem(id, type);
|
|
||||||
Cache.SetString(uuid, JsonSerializer.Serialize(loginItem));
|
|
||||||
return uuid;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -53,8 +44,7 @@ namespace SimApi.Helpers
|
|||||||
{
|
{
|
||||||
if (!string.IsNullOrEmpty(uuid))
|
if (!string.IsNullOrEmpty(uuid))
|
||||||
{
|
{
|
||||||
Cache.Remove(uuid);
|
cache.Remove(uuid);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
+82
-18
@@ -1,20 +1,23 @@
|
|||||||
using System;
|
#nullable enable
|
||||||
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Minio;
|
using Minio;
|
||||||
using Minio.Exceptions;
|
using Minio.DataModel.Args;
|
||||||
using SimApi.Configs;
|
using SimApi.Configurations;
|
||||||
|
|
||||||
namespace SimApi.Helpers
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
|
public class SimApiStorage
|
||||||
{
|
{
|
||||||
public class SimApiStorage
|
private IMinioClient Mc { get; }
|
||||||
{
|
|
||||||
private MinioClient Mc { get; }
|
|
||||||
|
|
||||||
public MinioClient Client => Mc;
|
public IMinioClient Client => Mc;
|
||||||
|
|
||||||
private string ServeUrl { get; }
|
private string ServeUrl { get; }
|
||||||
|
|
||||||
|
private string Endpoint { get; }
|
||||||
|
|
||||||
public string Bucket { get; }
|
public string Bucket { get; }
|
||||||
|
|
||||||
private IHttpContextAccessor HttpContextAccessor { get; }
|
private IHttpContextAccessor HttpContextAccessor { get; }
|
||||||
@@ -23,9 +26,10 @@ namespace SimApi.Helpers
|
|||||||
{
|
{
|
||||||
var options = apiOptions.SimApiStorageOptions;
|
var options = apiOptions.SimApiStorageOptions;
|
||||||
HttpContextAccessor = httpContextAccessor;
|
HttpContextAccessor = httpContextAccessor;
|
||||||
|
Endpoint = options.Endpoint!;
|
||||||
var useSsl = false;
|
var useSsl = false;
|
||||||
string endpoint;
|
string endpoint;
|
||||||
if (options.Endpoint.StartsWith("http://"))
|
if (options.Endpoint!.StartsWith("http://"))
|
||||||
{
|
{
|
||||||
endpoint = options.Endpoint.Replace("http://", string.Empty);
|
endpoint = options.Endpoint.Replace("http://", string.Empty);
|
||||||
}
|
}
|
||||||
@@ -39,14 +43,16 @@ namespace SimApi.Helpers
|
|||||||
throw new Exception("SimApiStorage: Error Endpoint");
|
throw new Exception("SimApiStorage: Error Endpoint");
|
||||||
}
|
}
|
||||||
|
|
||||||
ServeUrl = options.ServeUrl;
|
ServeUrl = options.ServeUrl!;
|
||||||
Bucket = options.Bucket;
|
if (ServeUrl.EndsWith('/')) throw new Exception("SimApiStorage: ServeUrl must not end with /");
|
||||||
|
Bucket = options.Bucket!;
|
||||||
var mcb = new MinioClient().WithEndpoint(endpoint)
|
var mcb = new MinioClient().WithEndpoint(endpoint)
|
||||||
.WithCredentials(options.AccessKey, options.SecretKey);
|
.WithCredentials(options.AccessKey, options.SecretKey);
|
||||||
if (useSsl)
|
if (useSsl)
|
||||||
{
|
{
|
||||||
mcb = mcb.WithSSL();
|
mcb = mcb.WithSSL();
|
||||||
}
|
}
|
||||||
|
|
||||||
Mc = mcb.Build();
|
Mc = mcb.Build();
|
||||||
|
|
||||||
var found = Mc.BucketExistsAsync(new BucketExistsArgs().WithBucket(Bucket)).Result;
|
var found = Mc.BucketExistsAsync(new BucketExistsArgs().WithBucket(Bucket)).Result;
|
||||||
@@ -62,10 +68,13 @@ namespace SimApi.Helpers
|
|||||||
/// <param name="path"></param>
|
/// <param name="path"></param>
|
||||||
/// <param name="expire"></param>
|
/// <param name="expire"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public string GetUploadUrl(string path, int expire = 7200)
|
public GetUploadUrlResponse GetUploadUrl(string path, int expire = 7200)
|
||||||
{
|
{
|
||||||
return Mc.PresignedPutObjectAsync(new PresignedPutObjectArgs().WithBucket(Bucket)
|
CheckPath(path);
|
||||||
.WithObject(path).WithExpiry(expire)).Result;
|
var obj = path.TrimStart('/');
|
||||||
|
var uploadUrl = Mc.PresignedPutObjectAsync(new PresignedPutObjectArgs().WithBucket(Bucket)
|
||||||
|
.WithObject(obj).WithExpiry(expire)).Result;
|
||||||
|
return new GetUploadUrlResponse(uploadUrl, $"{ServeUrl}{path}", path);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -76,20 +85,38 @@ namespace SimApi.Helpers
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public string GetDownloadUrl(string path, int expire = 600)
|
public string GetDownloadUrl(string path, int expire = 600)
|
||||||
{
|
{
|
||||||
|
CheckPath(path);
|
||||||
|
path = path.TrimStart('/');
|
||||||
return Mc.PresignedGetObjectAsync(new PresignedGetObjectArgs().WithBucket(Bucket).WithObject(path)
|
return Mc.PresignedGetObjectAsync(new PresignedGetObjectArgs().WithBucket(Bucket).WithObject(path)
|
||||||
.WithExpiry(expire)).Result;
|
.WithExpiry(expire)).Result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public string UploadFile(string path, Stream stream, string contentType = "image/png")
|
/// <summary>
|
||||||
|
/// 直接上传文件
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="path"></param>
|
||||||
|
/// <param name="stream"></param>
|
||||||
|
/// <param name="contentType"></param>
|
||||||
|
public void UploadFile(string path, Stream stream, string contentType = "image/png")
|
||||||
{
|
{
|
||||||
|
CheckPath(path);
|
||||||
|
path = path.TrimStart('/');
|
||||||
Mc.PutObjectAsync(new PutObjectArgs().WithBucket(Bucket).WithObject(path).WithObjectSize(stream.Length)
|
Mc.PutObjectAsync(new PutObjectArgs().WithBucket(Bucket).WithObject(path).WithObjectSize(stream.Length)
|
||||||
.WithStreamData(stream).WithContentType(contentType)).Wait();
|
.WithStreamData(stream).WithContentType(contentType)).Wait();
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public string FullUrl(string path)
|
/// <summary>
|
||||||
|
/// 使用path获取完整的访问URL
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="path"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
/// <exception cref="Exception"></exception>
|
||||||
|
public string? FullUrl(string? path)
|
||||||
{
|
{
|
||||||
|
if (string.IsNullOrEmpty(path)) return path;
|
||||||
|
if(path.StartsWith("http://") || path.StartsWith("https://")) return path;
|
||||||
|
if (!(path.StartsWith('/') || path.StartsWith("~/"))) return path;
|
||||||
var httpRequest = HttpContextAccessor.HttpContext?.Request;
|
var httpRequest = HttpContextAccessor.HttpContext?.Request;
|
||||||
var url = $"{httpRequest?.Scheme}://{httpRequest?.Host}";
|
var url = $"{httpRequest?.Scheme}://{httpRequest?.Host}";
|
||||||
if (string.IsNullOrEmpty(path))
|
if (string.IsNullOrEmpty(path))
|
||||||
@@ -97,7 +124,44 @@ namespace SimApi.Helpers
|
|||||||
return path;
|
return path;
|
||||||
}
|
}
|
||||||
|
|
||||||
return path.StartsWith("~") ? url + path.Substring(1, path.Length - 1) : $"{ServeUrl}{path}";
|
return path.StartsWith('~') ? string.Concat(url, path.AsSpan(1, path.Length - 1)) : $"{ServeUrl}{path}";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取一个Path得访问URL
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="path"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public string? GetUrl(string? path)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(path)) return path;
|
||||||
|
if (path.StartsWith("~/"))
|
||||||
|
{
|
||||||
|
var httpRequest = HttpContextAccessor.HttpContext?.Request;
|
||||||
|
var url = $"{httpRequest?.Scheme}://{httpRequest?.Host}";
|
||||||
|
return string.Concat(url, path.AsSpan(1, path.Length - 1));
|
||||||
|
}
|
||||||
|
if (path.StartsWith('/'))
|
||||||
|
{
|
||||||
|
return $"{ServeUrl}{path}";
|
||||||
|
}
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 从URL中获取相对路径 (如果url不是当前服务器的url,则原样返回)
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="url"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public string? GetPath(string? url)
|
||||||
|
{
|
||||||
|
return url?.Replace($"{Endpoint}/{Bucket}", string.Empty).Replace(ServeUrl,string.Empty);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CheckPath(string path)
|
||||||
|
{
|
||||||
|
if (!path.StartsWith('/')) throw new Exception("path must start with /");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public record GetUploadUrlResponse(string UploadUrl, string DownloadUrl, string Path);
|
||||||
+25
-9
@@ -1,4 +1,5 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Linq;
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Encodings.Web;
|
using System.Text.Encodings.Web;
|
||||||
@@ -7,10 +8,10 @@ using System.Text.Json.Serialization;
|
|||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
using System.Text.Unicode;
|
using System.Text.Unicode;
|
||||||
|
|
||||||
namespace SimApi.Helpers
|
namespace SimApi.Helpers;
|
||||||
|
|
||||||
|
public static class SimApiUtil
|
||||||
{
|
{
|
||||||
public static class SimApiUtil
|
|
||||||
{
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 当前CST时间
|
/// 当前CST时间
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -50,16 +51,15 @@ namespace SimApi.Helpers
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static string Md5(string source, string mode = "x2")
|
public static string Md5(string source, string mode = "x2")
|
||||||
{
|
{
|
||||||
var sor = Encoding.UTF8.GetBytes(source);
|
var sourceBytes = Encoding.UTF8.GetBytes(source);
|
||||||
var md5 = MD5.Create();
|
var result = MD5.HashData(sourceBytes);
|
||||||
var result = md5.ComputeHash(sor);
|
var stringBuilder = new StringBuilder(40);
|
||||||
var strbul = new StringBuilder(40);
|
|
||||||
foreach (var t in result)
|
foreach (var t in result)
|
||||||
{
|
{
|
||||||
strbul.Append(t.ToString(mode));
|
stringBuilder.Append(t.ToString(mode));
|
||||||
}
|
}
|
||||||
|
|
||||||
return strbul.ToString();
|
return stringBuilder.ToString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -71,5 +71,21 @@ namespace SimApi.Helpers
|
|||||||
{
|
{
|
||||||
return JsonSerializer.Serialize(obj, JsonOption);
|
return JsonSerializer.Serialize(obj, JsonOption);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 分页
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="query"></param>
|
||||||
|
/// <param name="page">页码</param>
|
||||||
|
/// <param name="count">每页数量</param>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
|
public static IQueryable<T> Paginate<T>(this IQueryable<T> query, int page, int count)
|
||||||
|
{
|
||||||
|
if (page < 1)
|
||||||
|
page = 1;
|
||||||
|
if (count <= 0)
|
||||||
|
count = 10;
|
||||||
|
return query.Skip((page - 1) * count).Take(count);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+16
-15
@@ -1,23 +1,14 @@
|
|||||||
using System;
|
using System;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using SimApi.Helpers;
|
|
||||||
|
|
||||||
namespace SimApi.Logger
|
namespace SimApi.Logger;
|
||||||
|
|
||||||
|
public class SimApiLogger(string name) : ILogger
|
||||||
{
|
{
|
||||||
public class SimApiLogger : ILogger
|
public IDisposable BeginScope<TState>(TState state) where TState : notnull => default!;
|
||||||
{
|
|
||||||
private string Name { get; }
|
|
||||||
|
|
||||||
public SimApiLogger(string name)
|
|
||||||
{
|
|
||||||
Name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IDisposable BeginScope<TState>(TState state) => default!;
|
|
||||||
|
|
||||||
public bool IsEnabled(LogLevel logLevel) => true;
|
public bool IsEnabled(LogLevel logLevel) => true;
|
||||||
|
|
||||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception,
|
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
|
||||||
Func<TState, Exception, string> formatter)
|
Func<TState, Exception, string> formatter)
|
||||||
{
|
{
|
||||||
Console.ForegroundColor = logLevel switch
|
Console.ForegroundColor = logLevel switch
|
||||||
@@ -30,12 +21,22 @@ namespace SimApi.Logger
|
|||||||
_ => ConsoleColor.White
|
_ => ConsoleColor.White
|
||||||
};
|
};
|
||||||
var message =
|
var message =
|
||||||
$"[ {Name} ][ {SimApiUtil.CstNow.ToString("yyyy-MM-dd HH:mm:ss:ffff")} ][ {logLevel.ToString()} ]\n{state}\n";
|
$"[ {name} ][ {DateTime.Now:yyyy-MM-dd HH:mm:ss:ffff} ][ {logLevel.ToString()} ]\n{state}\n";
|
||||||
if (exception != null)
|
if (exception != null)
|
||||||
{
|
{
|
||||||
message += $"{exception}\n";
|
message += $"{exception}\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
Console.WriteLine(message);
|
Console.WriteLine(message);
|
||||||
|
Console.ResetColor();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class EmptyDisposable : IDisposable
|
||||||
|
{
|
||||||
|
public static EmptyDisposable Instance { get; } = new EmptyDisposable();
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
|
|
||||||
namespace SimApi.Logger;
|
|
||||||
|
|
||||||
public class SimApiLoggerConfiguration
|
|
||||||
{
|
|
||||||
public int EventId { get; set; }
|
|
||||||
|
|
||||||
public Dictionary<LogLevel, ConsoleColor> LogLevels { get; set; } = new()
|
|
||||||
{
|
|
||||||
[LogLevel.Information] = ConsoleColor.Green
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace SimApi.Logger
|
namespace SimApi.Logger;
|
||||||
|
|
||||||
|
public class SimApiLoggerProvider : ILoggerProvider
|
||||||
{
|
{
|
||||||
public class SimApiLoggerProvider : ILoggerProvider
|
private readonly ConcurrentDictionary<string, SimApiLogger> _loggers = new();
|
||||||
{
|
|
||||||
private readonly ConcurrentDictionary<string, SimApiLogger> _loggers =
|
|
||||||
new ConcurrentDictionary<string, SimApiLogger>();
|
|
||||||
|
|
||||||
|
|
||||||
public ILogger CreateLogger(string categoryName)
|
public ILogger CreateLogger(string categoryName)
|
||||||
@@ -18,5 +17,4 @@ namespace SimApi.Logger
|
|||||||
{
|
{
|
||||||
_loggers.Clear();
|
_loggers.Clear();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -3,39 +3,29 @@ using System.Threading.Tasks;
|
|||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.Extensions.Caching.Distributed;
|
using Microsoft.Extensions.Caching.Distributed;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Middlewares
|
namespace SimApi.Middlewares;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 认证信息获取中间件
|
||||||
|
/// </summary>
|
||||||
|
public class SimApiAuthMiddleware(RequestDelegate next)
|
||||||
{
|
{
|
||||||
/// <summary>
|
public Task Invoke(HttpContext httpContext, IDistributedCache cache, SimApiAuth auth)
|
||||||
/// 认证信息获取中间件
|
|
||||||
/// </summary>
|
|
||||||
public class SimApiAuthMiddleware
|
|
||||||
{
|
{
|
||||||
private RequestDelegate Next { get; }
|
string? token = null;
|
||||||
|
if (httpContext.Request.Headers.TryGetValue("Token", out var header))
|
||||||
public SimApiAuthMiddleware(RequestDelegate next)
|
|
||||||
{
|
{
|
||||||
Next = next;
|
token = header;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task Invoke(HttpContext httpContext, IDistributedCache cache)
|
if (string.IsNullOrEmpty(token)) return next(httpContext);
|
||||||
{
|
var login = auth.GetLogin(token);
|
||||||
string token = null;
|
|
||||||
if (httpContext.Request.Headers.ContainsKey("Token"))
|
|
||||||
{
|
|
||||||
token = httpContext.Request.Headers["Token"];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!string.IsNullOrEmpty(token))
|
|
||||||
{
|
|
||||||
var login = cache.GetString(token);
|
|
||||||
if (login != null)
|
if (login != null)
|
||||||
{
|
{
|
||||||
httpContext.Items.Add("LoginInfo", JsonSerializer.Deserialize<SimApiLoginItem>(login));
|
httpContext.Items.Add("LoginInfo", login);
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return Next(httpContext);
|
|
||||||
}
|
}
|
||||||
|
return next(httpContext);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,62 +1,52 @@
|
|||||||
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;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using SimApi.Exceptions;
|
using SimApi.Exceptions;
|
||||||
|
|
||||||
namespace SimApi.Middlewares
|
namespace SimApi.Middlewares;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 异常处理中间件
|
||||||
|
/// </summary>
|
||||||
|
public class SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExceptionMiddleware> log)
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// 异常处理中间件
|
|
||||||
/// </summary>
|
|
||||||
public class SimApiExceptionMiddleware
|
|
||||||
{
|
|
||||||
private RequestDelegate Next { get; }
|
|
||||||
|
|
||||||
private ILogger<SimApiExceptionMiddleware> Log { get; }
|
|
||||||
|
|
||||||
public SimApiExceptionMiddleware(RequestDelegate next, ILogger<SimApiExceptionMiddleware> log)
|
|
||||||
{
|
|
||||||
Log = log;
|
|
||||||
Next = next;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task InvokeAsync(HttpContext context)
|
public async Task InvokeAsync(HttpContext context)
|
||||||
{
|
{
|
||||||
if (context.Request.Headers.ContainsKey("Query-Id"))
|
if (context.Request.Headers.TryGetValue("Query-Id", out var header))
|
||||||
{
|
{
|
||||||
context.Response.Headers["Query-Id"] = context.Request.Headers["Query-Id"];
|
context.Response.Headers["Query-Id"] = header;
|
||||||
}
|
}
|
||||||
|
|
||||||
var response = new SimApiBaseResponse();
|
SimApiBaseResponse response;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await Next(context);
|
await next(context);
|
||||||
if (context.Response.StatusCode != 200)
|
switch (context.Response.StatusCode)
|
||||||
{
|
|
||||||
if (!new[]
|
|
||||||
{
|
|
||||||
301, 302
|
|
||||||
}.Contains(context.Response.StatusCode))
|
|
||||||
{
|
{
|
||||||
|
case 200:
|
||||||
|
case 301:
|
||||||
|
case 302:
|
||||||
|
break;
|
||||||
|
case 404:
|
||||||
|
throw new SimApiException(context.Response.StatusCode, "请求的接口不存在");
|
||||||
|
default:
|
||||||
throw new SimApiException(context.Response.StatusCode);
|
throw new SimApiException(context.Response.StatusCode);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (SimApiException ex)
|
catch (SimApiException ex)
|
||||||
{
|
{
|
||||||
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)
|
||||||
{
|
{
|
||||||
Log.LogError(ex.Message);
|
log.LogError("{Msg}", ex.Message);
|
||||||
Log.LogError(ex.StackTrace);
|
log.LogError("{Msg}", ex.StackTrace);
|
||||||
response = new SimApiBaseResponse(500, ex.Message);
|
response = new SimApiBaseResponse(500, ex.Message);
|
||||||
ErrorResponse(context, response);
|
ErrorResponse(context, response);
|
||||||
}
|
}
|
||||||
@@ -67,14 +57,10 @@ namespace SimApi.Middlewares
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="context"></param>
|
/// <param name="context"></param>
|
||||||
/// <param name="response"></param>
|
/// <param name="response"></param>
|
||||||
private void ErrorResponse(HttpContext context, SimApiBaseResponse response)
|
private static void ErrorResponse(HttpContext context, SimApiBaseResponse response)
|
||||||
{
|
|
||||||
if (!context.Response.HasStarted)
|
|
||||||
{
|
{
|
||||||
context.Response.StatusCode = 200;
|
context.Response.StatusCode = 200;
|
||||||
context.Response.Headers.Add("Content-Type", "application/json");
|
context.Response.Headers.Append("Content-Type", "application/json");
|
||||||
context.Response.WriteAsync(response.ToString());
|
context.Response.WriteAsync(response.ToString()).Wait();
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+14
-12
@@ -1,23 +1,26 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.ComponentModel.DataAnnotations.Schema;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.Json;
|
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi.Models
|
namespace SimApi.Models;
|
||||||
|
|
||||||
|
public class SimApiBaseModel
|
||||||
{
|
{
|
||||||
public class SimApiBaseModel
|
[Column(Order = 1)] public string Id { get; set; } = Guid.NewGuid().ToString();
|
||||||
{
|
|
||||||
protected virtual string[] MapperIgnoreField { get; set; } =
|
[Column(Order = 9998)] public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||||||
{
|
|
||||||
"Id", "CreatedAt", "UpdatedAt"
|
[Column(Order = 9999)] public DateTime CreatedAt { get; set; } = DateTime.Now;
|
||||||
};
|
|
||||||
|
protected virtual string[] MapperIgnoreField { get; set; } = { "Id", "CreatedAt", "UpdatedAt" };
|
||||||
|
|
||||||
protected virtual string UpdatedTimeField { get; set; } = "UpdatedAt";
|
protected virtual string UpdatedTimeField { get; set; } = "UpdatedAt";
|
||||||
|
|
||||||
public void MapData<TS>(TS source, bool mapAll = false)
|
public void MapData<TS>(TS source, bool mapAll = false)
|
||||||
{
|
{
|
||||||
//获取要赋值的源数据不为null的项目
|
//获取要赋值的源数据不为null的项目
|
||||||
var sourceProps = source.GetType().GetProperties().Where(x => x.GetValue(source) != null)
|
var sourceProps = source!.GetType().GetProperties().Where(x => x.GetValue(source) != null)
|
||||||
.Select(x => new
|
.Select(x => new
|
||||||
{
|
{
|
||||||
x.Name,
|
x.Name,
|
||||||
@@ -46,7 +49,7 @@ namespace SimApi.Models
|
|||||||
public void MapData<TS>(TS source, string[] mapFields)
|
public void MapData<TS>(TS source, string[] mapFields)
|
||||||
{
|
{
|
||||||
//获取要赋值的源数据不为null的项目
|
//获取要赋值的源数据不为null的项目
|
||||||
var sourceProps = source.GetType().GetProperties().Where(x => x.GetValue(source) != null)
|
var sourceProps = source!.GetType().GetProperties().Where(x => x.GetValue(source) != null)
|
||||||
.Select(x => new
|
.Select(x => new
|
||||||
{
|
{
|
||||||
x.Name,
|
x.Name,
|
||||||
@@ -78,7 +81,6 @@ namespace SimApi.Models
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public void UpdateTime()
|
public void UpdateTime()
|
||||||
{
|
{
|
||||||
GetType().GetProperty(UpdatedTimeField)?.SetValue(this, SimApiUtil.CstNow);
|
GetType().GetProperty(UpdatedTimeField)?.SetValue(this, DateTime.Now);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# YYApi 基于Asp.net Core 3/5的一个基础辅助包
|
# SimApi 基于.Net的一个基础辅助包
|
||||||
|
|
||||||
[](https://github.com/simcu/simapi-net/actions/workflows/nuget-publish.yml)
|
[](https://github.com/simcu/simapi-net/actions/workflows/nuget-publish.yml)
|
||||||
### 包含了以下组件:
|
### 包含了以下组件:
|
||||||
@@ -52,3 +52,4 @@ services.AddSimApi(options =>
|
|||||||
options.SimApiStorageOptions = Configuration.GetSection("S3").Get<SimApiStorageOptions>();
|
options.SimApiStorageOptions = Configuration.GetSection("S3").Get<SimApiStorageOptions>();
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
基于S3的存储,基于RabbitMq的事件RPC调用,自定义Logger格式,自定义响应格式
|
||||||
|
|||||||
+9
-11
@@ -14,27 +14,25 @@
|
|||||||
<SynchReleaseVersion>false</SynchReleaseVersion>
|
<SynchReleaseVersion>false</SynchReleaseVersion>
|
||||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||||
<PackageVersion>5.0.2</PackageVersion>
|
<PackageVersion>5.0.2</PackageVersion>
|
||||||
<TargetFramework>net7.0</TargetFramework>
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Folder Include="Helpers\" />
|
<Folder Include="Communications\"/>
|
||||||
<Folder Include="Communications\" />
|
<Folder Include="Exceptions\"/>
|
||||||
<Folder Include="Controllers\" />
|
|
||||||
<Folder Include="Middlewares\" />
|
|
||||||
<Folder Include="Exceptions\" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Minio" Version="4.0.7" />
|
<PackageReference Include="Minio" Version="6.0.3" />
|
||||||
<PackageReference Include="RabbitMQ.Client" Version="6.6.0" />
|
<PackageReference Include="MQTTnet" Version="4.3.6.1152" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" />
|
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.7.1" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.5.0" />
|
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.7.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ProjectExtensions>
|
<ProjectExtensions>
|
||||||
<MonoDevelop>
|
<MonoDevelop>
|
||||||
<Properties>
|
<Properties>
|
||||||
<Policies>
|
<Policies>
|
||||||
<DotNetNamingPolicy ResourceNamePolicy="FileFormatDefault" DirectoryNamespaceAssociation="PrefixedHierarchical" />
|
<DotNetNamingPolicy ResourceNamePolicy="FileFormatDefault" DirectoryNamespaceAssociation="PrefixedHierarchical"/>
|
||||||
</Policies>
|
</Policies>
|
||||||
</Properties>
|
</Properties>
|
||||||
</MonoDevelop>
|
</MonoDevelop>
|
||||||
|
|||||||
+102
-16
@@ -1,24 +1,31 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Text.Json;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.OpenApi.Models;
|
using Microsoft.OpenApi.Models;
|
||||||
using SimApi.Middlewares;
|
using SimApi.Middlewares;
|
||||||
using Microsoft.AspNetCore.HttpOverrides;
|
using Microsoft.AspNetCore.HttpOverrides;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using SimApi.Configs;
|
using SimApi.Attributes;
|
||||||
|
using SimApi.CoceSdk;
|
||||||
|
using SimApi.Configurations;
|
||||||
using SimApi.Logger;
|
using SimApi.Logger;
|
||||||
|
|
||||||
namespace SimApi
|
namespace SimApi;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 加入系统的扩展信息
|
||||||
|
/// </summary>
|
||||||
|
public static class SimApiExtensions
|
||||||
{
|
{
|
||||||
/// <summary>
|
|
||||||
/// 加入系统的扩展信息
|
|
||||||
/// </summary>
|
|
||||||
public static class SimApiExtensions
|
|
||||||
{
|
|
||||||
//**********快捷添加**************
|
//**********快捷添加**************
|
||||||
public static IServiceCollection AddSimApi(this IServiceCollection builder,
|
public static IServiceCollection AddSimApi(this IServiceCollection builder,
|
||||||
Action<SimApiOptions> options = null)
|
Action<SimApiOptions>? options = null)
|
||||||
{
|
{
|
||||||
var simApiOptions = new SimApiOptions();
|
var simApiOptions = new SimApiOptions();
|
||||||
options?.Invoke(simApiOptions);
|
options?.Invoke(simApiOptions);
|
||||||
@@ -30,10 +37,16 @@ namespace SimApi
|
|||||||
logger.AddProvider(new SimApiLoggerProvider());
|
logger.AddProvider(new SimApiLoggerProvider());
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 是否使用 AUTH
|
// 是否使用 AUTH
|
||||||
if (simApiOptions.EnableSimApiAuth)
|
if (simApiOptions.EnableSimApiAuth)
|
||||||
{
|
{
|
||||||
builder.AddScoped<SimApiAuth>();
|
builder.AddSingleton<SimApiAuth>();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (simApiOptions.EnableCoceSdk)
|
||||||
|
{
|
||||||
|
builder.AddSingleton<CoceApp>();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (simApiOptions.EnableCors)
|
if (simApiOptions.EnableCors)
|
||||||
@@ -45,6 +58,19 @@ namespace SimApi
|
|||||||
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
|
||||||
@@ -145,7 +171,7 @@ namespace SimApi
|
|||||||
Id = "oauth2"
|
Id = "oauth2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
new[] { "SimApiAuth" }
|
["SimApiAuth"]
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -184,21 +210,64 @@ namespace SimApi
|
|||||||
builder.AddSingleton<SimApiStorage>();
|
builder.AddSingleton<SimApiStorage>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (simApiOptions.EnableSimApiException)
|
||||||
|
{
|
||||||
|
builder.AddControllers(opt => opt.Filters.Add<SimApiResponseFilter>())
|
||||||
|
.AddJsonOptions(opt => opt.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase);
|
||||||
|
}
|
||||||
|
|
||||||
builder.AddSingleton(simApiOptions);
|
builder.AddSingleton(simApiOptions);
|
||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static IHost UseSimApi(this IHost builder)
|
||||||
|
{
|
||||||
|
var options = builder.Services.GetRequiredService<SimApiOptions>();
|
||||||
|
|
||||||
|
var logger = builder.Services.GetRequiredService<ILogger<SimApiOptions>>();
|
||||||
|
|
||||||
|
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
||||||
|
|
||||||
|
//请求一下检测存储错误
|
||||||
|
if (options.EnableSimApiStorage)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置SimApiStorage...");
|
||||||
|
builder.Services.GetService<SimApiStorage>();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.EnableCoceSdk)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}",
|
||||||
|
options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint,
|
||||||
|
options.CoceSdkOptions.AppId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.EnableLowerUrl)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置使用URL小写...");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.EnableSynapse)
|
||||||
|
{
|
||||||
|
var synapse = builder.Services.GetRequiredService<Synapse>();
|
||||||
|
synapse.Init();
|
||||||
|
}
|
||||||
|
|
||||||
|
return builder;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 使用所有SimApi自定义中间件
|
/// 使用所有SimApi自定义中间件
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="builder"></param>
|
/// <param name="builder"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static IApplicationBuilder UseSimApi(this IApplicationBuilder builder)
|
public static WebApplication UseSimApi(this WebApplication builder)
|
||||||
{
|
{
|
||||||
var options = builder.ApplicationServices.GetRequiredService<SimApiOptions>();
|
var options = builder.Services.GetRequiredService<SimApiOptions>();
|
||||||
|
|
||||||
var logger = builder.ApplicationServices.GetRequiredService<ILogger<SimApiOptions>>();
|
var logger = builder.Services.GetRequiredService<ILogger<SimApiOptions>>();
|
||||||
|
|
||||||
|
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
|
||||||
if (options.EnableForwardHeaders)
|
if (options.EnableForwardHeaders)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置ForwardedHeaders...");
|
logger.LogInformation("开始配置ForwardedHeaders...");
|
||||||
@@ -215,6 +284,24 @@ namespace SimApi
|
|||||||
{
|
{
|
||||||
logger.LogInformation("开始配置SimApiAuth...");
|
logger.LogInformation("开始配置SimApiAuth...");
|
||||||
builder.UseMiddleware<SimApiAuthMiddleware>();
|
builder.UseMiddleware<SimApiAuthMiddleware>();
|
||||||
|
builder.MapControllerRoute(name: "GetUserInfo", pattern: "/user/info",
|
||||||
|
defaults: new { controller = "SimApiCommon", action = "UserInfo" });
|
||||||
|
builder.MapControllerRoute(name: "CheckLogin", pattern: "/auth/check",
|
||||||
|
defaults: new { controller = "SimApiCommon", action = "CheckLogin" });
|
||||||
|
builder.MapControllerRoute(name: "Logout", pattern: "/auth/logout",
|
||||||
|
defaults: new { controller = "SimApiCommon", action = "Logout" });
|
||||||
|
if (options.EnableCoceSdk)
|
||||||
|
{
|
||||||
|
logger.LogInformation("开始配置CoceAppSdk...\nApi入口: {ApiUrl}\nAuth入口:{AuthUrl}n\nAppId: {AppId}",
|
||||||
|
options.CoceSdkOptions.ApiEndpoint, options.CoceSdkOptions.AuthEndpoint,
|
||||||
|
options.CoceSdkOptions.AppId);
|
||||||
|
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/login",
|
||||||
|
defaults: new { controller = "SimApiCoce", action = "Login" });
|
||||||
|
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/user/groups",
|
||||||
|
defaults: new { controller = "SimApiCoce", action = "ListGroups" });
|
||||||
|
builder.MapControllerRoute(name: "LoginUseCoce", pattern: "/auth/config",
|
||||||
|
defaults: new { controller = "SimApiCoce", action = "GetConfig" });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.EnableSimApiDoc)
|
if (options.EnableSimApiDoc)
|
||||||
@@ -245,7 +332,7 @@ namespace SimApi
|
|||||||
if (options.EnableSimApiStorage)
|
if (options.EnableSimApiStorage)
|
||||||
{
|
{
|
||||||
logger.LogInformation("开始配置SimApiStorage...");
|
logger.LogInformation("开始配置SimApiStorage...");
|
||||||
builder.ApplicationServices.GetService<SimApiStorage>();
|
builder.Services.GetService<SimApiStorage>();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.EnableLowerUrl)
|
if (options.EnableLowerUrl)
|
||||||
@@ -255,11 +342,10 @@ namespace SimApi
|
|||||||
|
|
||||||
if (options.EnableSynapse)
|
if (options.EnableSynapse)
|
||||||
{
|
{
|
||||||
var synapse = builder.ApplicationServices.GetRequiredService<Synapse>();
|
var synapse = builder.Services.GetRequiredService<Synapse>();
|
||||||
synapse.Init();
|
synapse.Init();
|
||||||
}
|
}
|
||||||
|
|
||||||
return builder;
|
return builder;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using MQTTnet;
|
||||||
|
using MQTTnet.Protocol;
|
||||||
|
|
||||||
|
namespace SimApi;
|
||||||
|
|
||||||
|
public partial class Synapse
|
||||||
|
{
|
||||||
|
public event EventHandler<ConfigStoreItem>? OnConfigChanged;
|
||||||
|
private Dictionary<string, string> CurrentConfig { get; } = new();
|
||||||
|
|
||||||
|
private string ConfigStoreTopicPrefix => $"{Options.SysName}/synapse-config-store/";
|
||||||
|
|
||||||
|
private bool FireSetConfig(string key, string value)
|
||||||
|
{
|
||||||
|
if (key.Contains('#') || key.Contains('+')) return false;
|
||||||
|
var topic = $"{Options.SysName}/synapse-config-store/{key}";
|
||||||
|
var message = new MqttApplicationMessageBuilder()
|
||||||
|
.WithTopic(topic)
|
||||||
|
.WithPayload(value)
|
||||||
|
.WithRetainFlag()
|
||||||
|
.Build();
|
||||||
|
if (!Client!.IsConnected) return false;
|
||||||
|
Client!.PublishAsync(message, CancellationToken.None).Wait();
|
||||||
|
logger.LogDebug("Synapse Config Set: {Config} => {Data}", key, value);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private string? FireGetConfig(string key)
|
||||||
|
{
|
||||||
|
return CurrentConfig.GetValueOrDefault(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void RunConfigStoreServer()
|
||||||
|
{
|
||||||
|
Client!.ApplicationMessageReceivedAsync += e =>
|
||||||
|
{
|
||||||
|
if (!e.ApplicationMessage.Topic.StartsWith(ConfigStoreTopicPrefix)) return Task.CompletedTask;
|
||||||
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
|
var eventName = e.ApplicationMessage.Topic.Replace(ConfigStoreTopicPrefix, string.Empty);
|
||||||
|
CurrentConfig[eventName] = reqBody;
|
||||||
|
OnConfigChanged?.Invoke(this, new ConfigStoreItem(eventName, reqBody));
|
||||||
|
logger.LogDebug("Synapse Config Changed: {Config} => {Data}", eventName, reqBody);
|
||||||
|
return Task.CompletedTask;
|
||||||
|
};
|
||||||
|
SubConfigStoreServerTopic();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubConfigStoreServerTopic()
|
||||||
|
{
|
||||||
|
var csSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||||
|
.WithTopicFilter(o =>
|
||||||
|
o.WithTopic($"{ConfigStoreTopicPrefix}#").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
|
||||||
|
.Build();
|
||||||
|
Client!.SubscribeAsync(csSubOpts).Wait();
|
||||||
|
}
|
||||||
|
|
||||||
|
public record ConfigStoreItem(string Key, string Value);
|
||||||
|
}
|
||||||
+20
-18
@@ -1,31 +1,33 @@
|
|||||||
using System;
|
|
||||||
using System.Text;
|
|
||||||
using System.Text.Encodings.Web;
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Unicode;
|
using System.Threading;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using MQTTnet;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi;
|
namespace SimApi;
|
||||||
|
|
||||||
public partial class Synapse
|
public partial class Synapse
|
||||||
{
|
{
|
||||||
private void RunEventClient()
|
private bool FireEvent(string eventName, object? param)
|
||||||
{
|
{
|
||||||
EventClientChannel = CreateChannel(0, "EventClient");
|
string paramJson;
|
||||||
|
if (param is string strParam)
|
||||||
|
{
|
||||||
|
paramJson = strParam;
|
||||||
}
|
}
|
||||||
|
else
|
||||||
private void FireEvent(string eventName, object param)
|
|
||||||
{
|
{
|
||||||
var paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
|
paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
|
||||||
var router = $"event.{Options.AppName}.{eventName}";
|
}
|
||||||
var props = EventClientChannel.CreateBasicProperties();
|
var topic = $"{Options.SysName}/event/{Options.AppName}/{eventName}";
|
||||||
props.AppId = Options.AppId;
|
var message = new MqttApplicationMessageBuilder()
|
||||||
props.MessageId = Guid.NewGuid().ToString();
|
.WithTopic(topic)
|
||||||
props.ReplyTo = Options.AppName;
|
.WithPayload(paramJson)
|
||||||
props.Type = eventName;
|
.WithRetainFlag(false)
|
||||||
EventClientChannel.BasicPublish(Options.SysName, router, false, props, Encoding.UTF8.GetBytes(paramJson));
|
.Build();
|
||||||
Logger.LogDebug("Event Publish: {OptionsAppName}.{EventName}\n{ParamJson}", Options.AppName, eventName,
|
if (!Client!.IsConnected) return false;
|
||||||
paramJson);
|
Client.PublishAsync(message, CancellationToken.None).Wait();
|
||||||
|
logger.LogDebug("Synapse Event Publish: {Event}@{App} {Json}", eventName, Options.AppName, paramJson);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+53
-28
@@ -1,50 +1,75 @@
|
|||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using RabbitMQ.Client.Events;
|
using MQTTnet;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi;
|
namespace SimApi;
|
||||||
|
|
||||||
public partial class Synapse
|
public partial class Synapse
|
||||||
{
|
{
|
||||||
|
private string EventServerTopicPrefix => $"{Options.SysName}/event/";
|
||||||
|
|
||||||
private void RunEventServer()
|
private void RunEventServer()
|
||||||
{
|
{
|
||||||
EventServerChannel = CreateChannel(Options.EventProcessorNum, "EventServer");
|
Client!.ApplicationMessageReceivedAsync += async e =>
|
||||||
var queue = $"{Options.SysName}_{Options.AppName}_event";
|
|
||||||
EventServerChannel.QueueDeclare(queue, true, false, true, null);
|
|
||||||
foreach (var ev in EventRegistry.Where(ev => !ev.Key.Contains('*') && !ev.Key.Contains('#')))
|
|
||||||
{
|
{
|
||||||
EventServerChannel.QueueBind(queue, Options.SysName, $"event.{ev.Key}", null);
|
if (!e.ApplicationMessage.Topic.StartsWith(EventServerTopicPrefix)) return;
|
||||||
}
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
var consumer = new EventingBasicConsumer(EventServerChannel);
|
var eventName = e.ApplicationMessage.Topic.Replace(EventServerTopicPrefix, string.Empty);
|
||||||
consumer.Received += (ch, ea) =>
|
logger.LogDebug("Synapse Event Receive: {EventName}\n{Body}", eventName, reqBody);
|
||||||
|
var methods = EventRegistry
|
||||||
|
.Where(x => Regex.IsMatch(eventName,
|
||||||
|
"^" + Regex.Escape(x.Key!).Replace("\\+", "[^/]+").Replace("\\#", ".*") + "$"))
|
||||||
|
.ToArray();
|
||||||
|
var tasks = methods.Select(method => Task.Run(() =>
|
||||||
{
|
{
|
||||||
var reqBody = Encoding.UTF8.GetString(ea.Body.ToArray());
|
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(method.Class!);
|
||||||
Logger.LogDebug("Event Receive: {BasicPropertiesReplyTo}.{BasicPropertiesType}\n{S}",
|
var mt = callClass.GetType().GetMethod(method.Method!);
|
||||||
ea.BasicProperties.ReplyTo, ea.BasicProperties.Type, reqBody);
|
|
||||||
|
|
||||||
var key = ea.RoutingKey.Replace("event.", string.Empty);
|
|
||||||
var method = EventRegistry.FirstOrDefault(x => x.Key == key);
|
|
||||||
var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method.Class);
|
|
||||||
var mt = callClass.GetType().GetMethod(method.Method);
|
|
||||||
var pt = mt.GetParameters()[0].ParameterType;
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
mt.Invoke(callClass, pt == typeof(string)
|
if (mt!.GetParameters().Length == 2)
|
||||||
? new object[] { reqBody }
|
|
||||||
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) });
|
|
||||||
EventServerChannel.BasicAck(ea.DeliveryTag, false);
|
|
||||||
}
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
{
|
||||||
Logger.LogError("Event Processor Error: {Err}", e.InnerException);
|
var pt = mt.GetParameters()[1].ParameterType;
|
||||||
EventServerChannel.BasicNack(ea.DeliveryTag, false, false);
|
mt.Invoke(callClass, pt == typeof(string)
|
||||||
|
? new object?[] { eventName, reqBody }
|
||||||
|
: new object?[] { eventName, JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) });
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
mt.Invoke(callClass, new object[] { eventName });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError("Synapse Event Processor Error: {Err}\n{Stack}", ex.Message, ex.StackTrace);
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.ToList();
|
||||||
|
await Task.WhenAll(tasks);
|
||||||
};
|
};
|
||||||
EventServerChannel.BasicConsume(queue, false, "", false, false, null, consumer);
|
SubEventServerTopic();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubEventServerTopic()
|
||||||
|
{
|
||||||
|
foreach (var ev in EventRegistry)
|
||||||
|
{
|
||||||
|
var topic = $"{EventServerTopicPrefix}{ev.Key}";
|
||||||
|
if (Options.EventLoadBalancing)
|
||||||
|
{
|
||||||
|
topic = "$queue/" + topic;
|
||||||
|
}
|
||||||
|
|
||||||
|
var evSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||||
|
.WithTopicFilter(o => o.WithTopic(topic)).Build();
|
||||||
|
Client!.SubscribeAsync(evSubOpts).Wait();
|
||||||
|
logger.LogDebug("Synapse Event Register Event Success: {EventName}\nFull Topic: {Topic}", ev.Key, topic);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+76
-45
@@ -1,12 +1,12 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Text;
|
using System.Linq;
|
||||||
using System.Text.Encodings.Web;
|
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System.Text.Unicode;
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Newtonsoft.Json.Serialization;
|
using MQTTnet;
|
||||||
using RabbitMQ.Client.Events;
|
using MQTTnet.Packets;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
@@ -14,58 +14,89 @@ namespace SimApi;
|
|||||||
|
|
||||||
public partial class Synapse
|
public partial class Synapse
|
||||||
{
|
{
|
||||||
private Dictionary<string, byte[]> ResponseCache { get; } = new();
|
private Dictionary<string, TaskCompletionSource<string>> ResponseCompletionSources { get; } = new();
|
||||||
|
|
||||||
|
private string EventClientTopicPrefix => $"{Options.SysName}/{Options.AppName}/rpc/client/{Options.AppId}/";
|
||||||
|
|
||||||
private void RunRpcClient()
|
private void RunRpcClient()
|
||||||
{
|
{
|
||||||
RpcClientChannel = CreateChannel(0, "RpcClient");
|
Client!.ApplicationMessageReceivedAsync += e =>
|
||||||
var queue = $"{Options.SysName}_{Options.AppName}_client_{Options.AppId}";
|
|
||||||
var router = $"client.{Options.AppName}.{Options.AppId}";
|
|
||||||
RpcClientChannel.QueueDeclare(queue, true, false, true, null);
|
|
||||||
RpcClientChannel.QueueBind(queue, Options.SysName, router, null);
|
|
||||||
var consumer = new EventingBasicConsumer(RpcClientChannel);
|
|
||||||
consumer.Received += (ch, ea) =>
|
|
||||||
{
|
{
|
||||||
ResponseCache.Add(ea.BasicProperties.CorrelationId, ea.Body.ToArray());
|
if (!e.ApplicationMessage.Topic.StartsWith(EventClientTopicPrefix)) return Task.CompletedTask;
|
||||||
RpcClientChannel.BasicAck(ea.DeliveryTag, false);
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
Logger.LogDebug(
|
var messageId = e.ApplicationMessage.Topic.Replace(EventClientTopicPrefix, string.Empty);
|
||||||
"RPC Response: ({BasicPropertiesCorrelationId}) {BasicPropertiesType}@{BasicPropertiesReplyTo} -> {OptionsAppName}\n{S}",
|
if (!ResponseCompletionSources.TryGetValue(messageId, out var tcs)) return Task.CompletedTask;
|
||||||
ea.BasicProperties.CorrelationId, ea.BasicProperties.Type, ea.BasicProperties.ReplyTo, Options.AppName,
|
tcs.SetResult(reqBody);
|
||||||
Encoding.UTF8.GetString(ea.Body.ToArray()));
|
ResponseCompletionSources.Remove(messageId);
|
||||||
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
RpcClientChannel.BasicConsume(queue, false, "", false, false, null, consumer);
|
SubRpcClientTopic();
|
||||||
}
|
}
|
||||||
|
|
||||||
private object FireRpc(string app, string action, object param)
|
private void SubRpcClientTopic()
|
||||||
{
|
{
|
||||||
var paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
|
var rcSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||||
var router = $"server.{app}";
|
.WithTopicFilter(o => o.WithTopic($"{EventClientTopicPrefix}+")).Build();
|
||||||
SimApiBaseResponse response;
|
Client!.SubscribeAsync(rcSubOpts).Wait();
|
||||||
var props = RpcClientChannel.CreateBasicProperties();
|
|
||||||
props.AppId = Options.AppId;
|
|
||||||
props.MessageId = Guid.NewGuid().ToString();
|
|
||||||
props.Type = action;
|
|
||||||
props.ReplyTo = Options.AppName;
|
|
||||||
RpcClientChannel.BasicPublish(Options.SysName, router, false, props, Encoding.UTF8.GetBytes(paramJson));
|
|
||||||
Logger.LogDebug("RPC Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}",
|
|
||||||
props.MessageId,
|
|
||||||
Options.AppName, action, app, paramJson);
|
|
||||||
var ts = SimApiUtil.TimestampNow;
|
|
||||||
while (true)
|
|
||||||
{
|
|
||||||
if (SimApiUtil.TimestampNow - ts > Options.RpcTimeout)
|
|
||||||
{
|
|
||||||
response = new SimApiBaseResponse(502, "timeout");
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
if (ResponseCache.TryGetValue(props.MessageId, out var value))
|
|
||||||
|
private string? FireRpc(string app, string action, object? param, Dictionary<string, string>? headers = null,
|
||||||
|
int? timeout = null)
|
||||||
{
|
{
|
||||||
response = JsonSerializer.Deserialize<SimApiBaseResponse<object>>(
|
string paramJson;
|
||||||
Encoding.UTF8.GetString(value), SimApiUtil.JsonOption);
|
if (param is string strParam)
|
||||||
ResponseCache.Remove(props.MessageId);
|
{
|
||||||
break;
|
paramJson = strParam;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
paramJson = JsonSerializer.Serialize(param, SimApiUtil.JsonOption);
|
||||||
|
}
|
||||||
|
|
||||||
|
var topic = $"{Options.SysName}/{app}/rpc/server/{action}";
|
||||||
|
var messageId = Guid.NewGuid().ToString();
|
||||||
|
var tcs = new TaskCompletionSource<string>();
|
||||||
|
ResponseCompletionSources.Add(messageId, tcs);
|
||||||
|
var messageBuilder = new MqttApplicationMessageBuilder()
|
||||||
|
.WithTopic(topic)
|
||||||
|
.WithPayload(paramJson)
|
||||||
|
.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();
|
||||||
|
if (!Client!.IsConnected) return null;
|
||||||
|
Client.PublishAsync(message, CancellationToken.None).Wait();
|
||||||
|
logger.LogDebug(
|
||||||
|
"Synapse RPC Client Request: ({PropsMessageId}) {OptionsAppName} -> {Action}@{App}\n{ParamJson}\nHeaders: {Headers}",
|
||||||
|
messageId, Options.AppName, action, app, paramJson, JsonSerializer.Serialize(headers));
|
||||||
|
|
||||||
|
string response;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
timeout ??= Options.RpcTimeout;
|
||||||
|
if (tcs.Task.Wait(timeout.Value * 1000))
|
||||||
|
{
|
||||||
|
response = tcs.Task.Result;
|
||||||
|
logger.LogDebug(
|
||||||
|
"Synapse RPC Client Response: ({BasicPropertiesCorrelationId}) {BasicPropertiesType}@{BasicPropertiesReplyTo} -> {OptionsAppName}\n{S}",
|
||||||
|
messageId, action, app, Options.AppName, response);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
response = JsonSerializer.Serialize(new SimApiBaseResponse(502, "timeout"), SimApiUtil.JsonOption);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
response = JsonSerializer.Serialize(new SimApiBaseResponse(500, "Synapse RPC Client Error"),
|
||||||
|
SimApiUtil.JsonOption);
|
||||||
|
}
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+83
-56
@@ -1,14 +1,12 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using System.Text;
|
using System.Threading;
|
||||||
using System.Text.Encodings.Web;
|
using System.Threading.Tasks;
|
||||||
using System.Text.Json;
|
|
||||||
using System.Text.Json.Serialization;
|
|
||||||
using System.Text.Unicode;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using RabbitMQ.Client.Events;
|
using MQTTnet;
|
||||||
|
using MQTTnet.Protocol;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Exceptions;
|
using SimApi.Exceptions;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
@@ -18,76 +16,105 @@ namespace SimApi;
|
|||||||
|
|
||||||
public partial class Synapse
|
public partial class Synapse
|
||||||
{
|
{
|
||||||
|
private string RpcServerTopicPrefix => $"{Options.SysName}/{Options.AppName}/rpc/server/";
|
||||||
|
|
||||||
private void RunRpcServer()
|
private void RunRpcServer()
|
||||||
{
|
{
|
||||||
RpcServerChannel = CreateChannel(Options.RpcProcessorNum, "RpcServer");
|
Client!.ApplicationMessageReceivedAsync += e =>
|
||||||
var queue = $"{Options.SysName}_{Options.AppName}_server";
|
|
||||||
var router = $"server.{Options.AppName}";
|
|
||||||
RpcServerChannel.QueueDeclare(queue, true, false, true, null);
|
|
||||||
RpcServerChannel.QueueBind(queue, Options.SysName, router, null);
|
|
||||||
var consumer = new EventingBasicConsumer(RpcServerChannel);
|
|
||||||
consumer.Received += (ch, ea) =>
|
|
||||||
{
|
{
|
||||||
var reqBody = Encoding.UTF8.GetString(ea.Body.ToArray());
|
if (!e.ApplicationMessage.Topic.StartsWith(RpcServerTopicPrefix)) return Task.CompletedTask;
|
||||||
Logger.LogDebug(
|
var reqBody = e.ApplicationMessage.ConvertPayloadToString();
|
||||||
"RPC Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}",
|
var action = e.ApplicationMessage.Topic.Replace(RpcServerTopicPrefix, string.Empty);
|
||||||
ea.BasicProperties.MessageId, ea.BasicProperties.ReplyTo, ea.BasicProperties.Type, Options.AppName,
|
var appInfo = e.ApplicationMessage.ResponseTopic.Split(",");
|
||||||
reqBody);
|
logger.LogDebug(
|
||||||
var res = new SimApiBaseResponse(404, "method not found");
|
"Synapse RPC Server Receive: ({BasicPropertiesMessageId}) {BasicPropertiesReplyTo} -> {BasicPropertiesType}@{OptionsAppName}\n{S}",
|
||||||
var method = RpcRegistry.FirstOrDefault(x => x.Key == ea.BasicProperties.Type);
|
appInfo[2], appInfo[0], action, Options.AppName, reqBody);
|
||||||
if (method != null)
|
SimApiBaseResponse res;
|
||||||
|
var method = RpcRegistry.FirstOrDefault(x => x.Key == action);
|
||||||
|
if (method == null)
|
||||||
{
|
{
|
||||||
var callClass = Sp.CreateScope().ServiceProvider.GetRequiredService(method.Class);
|
res = new SimApiBaseResponse(404, "method not found");
|
||||||
var mt = callClass.GetType().GetMethod(method.Method);
|
|
||||||
var param = Array.Empty<object>();
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var pt = mt.GetParameters()[0].ParameterType;
|
|
||||||
if (pt == typeof(string))
|
|
||||||
{
|
|
||||||
param = new[] { reqBody };
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
var paramObj = JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption);
|
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(method.Class!);
|
||||||
param = new[] { paramObj };
|
var mt = callClass.GetType().GetMethod(method.Method!);
|
||||||
}
|
try
|
||||||
var ret = mt.Invoke(callClass, param);
|
|
||||||
res = new SimApiBaseResponse<object>(ret);
|
|
||||||
}
|
|
||||||
catch (TargetInvocationException e)
|
|
||||||
{
|
{
|
||||||
if (e.InnerException is SimApiException ie)
|
var methodParams = mt!.GetParameters();
|
||||||
|
object? ret;
|
||||||
|
switch (methodParams.Length)
|
||||||
{
|
{
|
||||||
Logger.LogDebug("RPC调用错误: {Err}", ie.Message);
|
case 1:
|
||||||
|
var pt = mt.GetParameters()[0].ParameterType;
|
||||||
|
var param = pt == typeof(string)
|
||||||
|
? [reqBody]
|
||||||
|
: new[] { JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption) };
|
||||||
|
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?>
|
||||||
|
{
|
||||||
|
Data = ret
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (TargetInvocationException ex)
|
||||||
|
{
|
||||||
|
if (ex.InnerException is SimApiException ie)
|
||||||
|
{
|
||||||
|
logger.LogDebug("Synapse RPC调用错误: {Err}", ie.Message);
|
||||||
res = new SimApiBaseResponse(ie.Code, ie.Message);
|
res = new SimApiBaseResponse(ie.Code, ie.Message);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
res = new SimApiBaseResponse(500, e.Message);
|
logger.LogError("Synapse RPC 方法异常: {Err}\n{Stack}", ex.Message, ex.StackTrace);
|
||||||
|
res = new SimApiBaseResponse(500, ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Logger.LogDebug("RPC调用失败: {Err}", e.Message);
|
logger.LogDebug("Synapse RPC调用失败: {Err}", ex.Message);
|
||||||
res = new SimApiBaseResponse(500, e.Message);
|
res = new SimApiBaseResponse(500, ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
|
var returnJson = JsonSerializer.Serialize((object)res, SimApiUtil.JsonOption);
|
||||||
var reply = $"client.{ea.BasicProperties.ReplyTo}.{ea.BasicProperties.AppId}";
|
var reply = $"{Options.SysName}/{appInfo[0]}/rpc/client/{appInfo[1]}/{appInfo[2]}";
|
||||||
var props = RpcServerChannel.CreateBasicProperties();
|
var message = new MqttApplicationMessageBuilder()
|
||||||
props.AppId = Options.AppId;
|
.WithTopic(reply)
|
||||||
props.CorrelationId = ea.BasicProperties.MessageId;
|
.WithPayload(returnJson)
|
||||||
props.MessageId = Guid.NewGuid().ToString();
|
.WithRetainFlag(false)
|
||||||
props.ReplyTo = Options.AppName;
|
.Build();
|
||||||
props.Type = ea.BasicProperties.Type;
|
if (!Client.IsConnected) return Task.CompletedTask;
|
||||||
RpcServerChannel.BasicPublish(Options.SysName, reply, false, props, Encoding.UTF8.GetBytes(returnJson));
|
Client.PublishAsync(message, CancellationToken.None).Wait();
|
||||||
Logger.LogDebug(
|
logger.LogDebug(
|
||||||
"Rpc Return: ({BasicPropertiesMessageId}) {BasicPropertiesType}@{OptionsAppName} -> {BasicPropertiesReplyTo}\n{ReturnJson}",
|
"Synapse Rpc Server Return: ({BasicPropertiesMessageId}) {BasicPropertiesType}@{OptionsAppName} -> {BasicPropertiesReplyTo}\n{ReturnJson}",
|
||||||
ea.BasicProperties.MessageId, ea.BasicProperties.Type, Options.AppName, ea.BasicProperties.ReplyTo,
|
appInfo[2], action, Options.AppName, appInfo[0], returnJson);
|
||||||
returnJson);
|
|
||||||
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
RpcServerChannel.BasicConsume(queue, true, "", false, false, null, consumer);
|
SubRpcServerTopic();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubRpcServerTopic()
|
||||||
|
{
|
||||||
|
var rsSubOpts = MqttFactory.CreateSubscribeOptionsBuilder()
|
||||||
|
.WithTopicFilter(o =>
|
||||||
|
o.WithTopic($"$queue/{RpcServerTopicPrefix}+").WithRetainHandling(MqttRetainHandling.SendAtSubscribe))
|
||||||
|
.Build();
|
||||||
|
Client!.SubscribeAsync(rsSubOpts).Wait();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+209
-121
@@ -3,187 +3,228 @@ using System.Collections.Generic;
|
|||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using RabbitMQ.Client;
|
using MQTTnet;
|
||||||
using RabbitMQ.Client.Exceptions;
|
using MQTTnet.Client;
|
||||||
|
using MQTTnet.Formatter;
|
||||||
using SimApi.Attributes;
|
using SimApi.Attributes;
|
||||||
using SimApi.Communications;
|
using SimApi.Communications;
|
||||||
using SimApi.Configs;
|
using SimApi.Configurations;
|
||||||
|
using SimApi.Exceptions;
|
||||||
using SimApi.Helpers;
|
using SimApi.Helpers;
|
||||||
|
|
||||||
namespace SimApi;
|
namespace SimApi;
|
||||||
|
|
||||||
public partial class Synapse
|
public partial class Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logger, IServiceProvider sp)
|
||||||
{
|
{
|
||||||
private IServiceProvider Sp { get; }
|
private SimApiSynapseOptions Options { get; } = simApiOptions.SimApiSynapseOptions;
|
||||||
|
|
||||||
private SimApiSynapseOptions Options { get; }
|
private MqttFactory MqttFactory { get; } = new();
|
||||||
|
public IMqttClient? Client { get; set; }
|
||||||
|
|
||||||
private ILogger<Synapse> Logger { get; }
|
private List<RegisterItem> EventRegistry { get; set; } = new();
|
||||||
|
|
||||||
private IConnection Connection { get; set; }
|
private List<RegisterItem> RpcRegistry { get; set; } = new();
|
||||||
|
|
||||||
private IModel EventClientChannel { get; set; }
|
|
||||||
|
|
||||||
private IModel EventServerChannel { get; set; }
|
|
||||||
|
|
||||||
private IModel RpcClientChannel { get; set; }
|
|
||||||
|
|
||||||
private IModel RpcServerChannel { get; set; }
|
|
||||||
|
|
||||||
private List<RegisterItem> EventRegistry { get; set; }
|
|
||||||
|
|
||||||
private List<RegisterItem> RpcRegistry { get; set; }
|
|
||||||
|
|
||||||
public Synapse(SimApiOptions simApiOptions, ILogger<Synapse> logger, IServiceProvider sp)
|
|
||||||
{
|
|
||||||
Logger = logger;
|
|
||||||
Sp = sp;
|
|
||||||
Options = simApiOptions.SimApiSynapseOptions;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Init()
|
public void Init()
|
||||||
{
|
{
|
||||||
ProcessAttribute();
|
logger.LogDebug("Synapse初始化配置信息: {Json}", SimApiUtil.Json(Options));
|
||||||
Logger.LogDebug("Synapse初始化配置信息: {Json}", SimApiUtil.Json(Options));
|
|
||||||
if (string.IsNullOrEmpty(Options.AppName) || string.IsNullOrEmpty(Options.SysName))
|
if (string.IsNullOrEmpty(Options.AppName) || string.IsNullOrEmpty(Options.SysName))
|
||||||
{
|
{
|
||||||
Logger.LogCritical("Synapse初始化失败: AppName or SysName 错误");
|
logger.LogCritical("Synapse初始化失败: AppName 和 SysName 不能为空");
|
||||||
}
|
}
|
||||||
|
|
||||||
Options.AppId ??= Guid.NewGuid().ToString();
|
Options.AppId ??= Guid.NewGuid().ToString();
|
||||||
Logger.LogInformation("System Name: {SysName}\nApp Name: {AppName}\nAppId: {AppId}", Options.SysName,
|
logger.LogInformation("Synapse Sys Name: {SysName}\nSynapse App Name: {AppName}\nSynapse App Id: {AppId}",
|
||||||
Options.AppName, Options.AppId);
|
Options.SysName, Options.AppName, Options.AppId);
|
||||||
CreateConnection();
|
CreateConnection();
|
||||||
CheckAndCreateExchange();
|
ProcessAttribute();
|
||||||
//事件客户端
|
//事件客户端
|
||||||
if (Options.DisableEventClient)
|
if (Options.DisableEventClient)
|
||||||
{
|
{
|
||||||
Logger.LogWarning("Event Client Disabled: DisableEventClient set true");
|
logger.LogWarning("Synapse Event Client Disabled: DisableEventClient set true");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
RunEventClient();
|
logger.LogInformation("Synapse Event Client Ready");
|
||||||
Logger.LogInformation("Event Client Ready");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
//RPC客户端
|
//RPC客户端
|
||||||
if (Options.DisableRpcClient)
|
if (Options.DisableRpcClient)
|
||||||
{
|
{
|
||||||
Logger.LogWarning("Rpc Client Disabled: DisableEventClient set true");
|
logger.LogWarning("Synapse Rpc Client Disabled: DisableEventClient set true");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
RunRpcClient();
|
RunRpcClient();
|
||||||
Logger.LogInformation("Rpc Client Ready, Client Timeout: {OptionsRpcTimeout}s", Options.RpcTimeout);
|
logger.LogInformation("Synapse Rpc Client Ready, Client Timeout: {OptionsRpcTimeout}s", Options.RpcTimeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (RpcRegistry.Count > 0)
|
if (RpcRegistry.Count > 0)
|
||||||
{
|
{
|
||||||
RunRpcServer();
|
RunRpcServer();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (EventRegistry.Count > 0)
|
if (EventRegistry.Count > 0)
|
||||||
{
|
{
|
||||||
RunEventServer();
|
RunEventServer();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (Options.EnableConfigStore)
|
||||||
|
{
|
||||||
|
RunConfigStoreServer();
|
||||||
|
logger.LogInformation("Synapse Config Store Ready [{SysName}] ...", Options.SysName);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public SimApiBaseResponse<T> Rpc<T>(string appName, string method, dynamic param)
|
/// <summary>
|
||||||
|
/// 调用RPC使用明确的返回值类型
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="appName"></param>
|
||||||
|
/// <param name="method"></param>
|
||||||
|
/// <param name="param"></param>
|
||||||
|
/// <param name="headers"></param>
|
||||||
|
/// <param name="timeout"></param>
|
||||||
|
/// <typeparam name="T"></typeparam>
|
||||||
|
/// <returns></returns>
|
||||||
|
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, "Rpc Client Disabled!");
|
var res = new SimApiBaseResponse(500, "Synapse Rpc Client Disabled!");
|
||||||
if (Options.DisableRpcClient)
|
if (Options.DisableRpcClient)
|
||||||
{
|
{
|
||||||
Logger.LogError("Rpc Client Disabled!");
|
logger.LogError("Synapse Rpc Client Disabled!");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
res = FireRpc(appName, method, param);
|
var data = FireRpc(appName, method, param, headers, timeout);
|
||||||
}
|
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
|
||||||
return res as SimApiBaseResponse<T>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public SimApiBaseResponse<object> Rpc(string appName, string method, dynamic param)
|
return (res as SimApiBaseResponse<T>)!;
|
||||||
{
|
|
||||||
return Rpc<object>(appName, method, param);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Event(string eventName, dynamic param)
|
/// <summary>
|
||||||
|
/// 调用RPC使用object作为返回值类型
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="appName"></param>
|
||||||
|
/// <param name="method"></param>
|
||||||
|
/// <param name="param"></param>
|
||||||
|
/// <param name="headers"></param>
|
||||||
|
/// <param name="timeout"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public SimApiBaseResponse<object> Rpc(string appName, string method, dynamic? param = null,
|
||||||
|
Dictionary<string, string>? headers = null, int? timeout = null)
|
||||||
{
|
{
|
||||||
if (Options.DisableEventClient)
|
return Rpc<object>(appName, method, param, headers, timeout);
|
||||||
{
|
|
||||||
Logger.LogError("Event Client Disabled!");
|
|
||||||
}
|
}
|
||||||
else
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 只能在Rpc方法中使用,快捷抛出异常返回
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="code"></param>
|
||||||
|
/// <param name="message"></param>
|
||||||
|
/// <exception cref="SimApiException"></exception>
|
||||||
|
public void RpcError(int code, string message = "")
|
||||||
{
|
{
|
||||||
FireEvent(eventName, param);
|
throw new SimApiException(code, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 如果条件成立,则爆出错误
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="condition"></param>
|
||||||
|
/// <param name="code"></param>
|
||||||
|
/// <param name="message"></param>
|
||||||
|
public void RpcErrorWhen(bool condition, int code, string message = "")
|
||||||
|
{
|
||||||
|
if (condition) RpcError(code, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 发送一个事件x
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="eventName"></param>
|
||||||
|
/// <param name="param"></param>
|
||||||
|
public bool Event(string eventName, dynamic? param = null)
|
||||||
|
{
|
||||||
|
if (!Options.DisableEventClient) return FireEvent(eventName, param);
|
||||||
|
logger.LogError("Synapse Event Client Disabled!");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 设置一个系统配置项
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <param name="value"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public bool SetConfig(string key, string value)
|
||||||
|
{
|
||||||
|
if (Options.EnableConfigStore) return FireSetConfig(key, value);
|
||||||
|
logger.LogError("Synapse Config Store Disabled!");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 读取一个配置项,如果没有则为空
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="key"></param>
|
||||||
|
/// <returns></returns>
|
||||||
|
public string? GetConfig(string key)
|
||||||
|
{
|
||||||
|
if (Options.EnableConfigStore) return FireGetConfig(key);
|
||||||
|
logger.LogError("Synapse Config Store Disabled!");
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void CreateConnection()
|
private void CreateConnection()
|
||||||
{
|
{
|
||||||
var factory = new ConnectionFactory
|
Client = MqttFactory.CreateMqttClient();
|
||||||
|
var clientOpts = new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500)
|
||||||
|
.WithWebSocketServer(o => o.WithUri(Options.Websocket))
|
||||||
|
.WithCredentials(Options.Username, Options.Password)
|
||||||
|
.WithClientId($"{Options.AppName}:{Options.AppId}")
|
||||||
|
.Build();
|
||||||
|
Client!.ConnectAsync(clientOpts, CancellationToken.None).Wait();
|
||||||
|
Client.ConnectedAsync += _ =>
|
||||||
{
|
{
|
||||||
HostName = Options.MqHost,
|
logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 连接成功...", Options.AppName, Options.AppId);
|
||||||
Port = Options.MqPort,
|
//RPC客户端
|
||||||
VirtualHost = Options.MqVHost,
|
if (!Options.DisableRpcClient) SubRpcClientTopic();
|
||||||
UserName = Options.MqUser,
|
if (RpcRegistry.Count > 0) SubRpcServerTopic();
|
||||||
Password = Options.MqPass
|
if (EventRegistry.Count > 0) SubEventServerTopic();
|
||||||
|
if (Options.EnableConfigStore) SubConfigStoreServerTopic();
|
||||||
|
return Task.CompletedTask;
|
||||||
};
|
};
|
||||||
|
//重连
|
||||||
|
Client.DisconnectedAsync += async _ =>
|
||||||
|
{
|
||||||
|
logger.LogError("Synapse MQTT[{AppName}:{AppId}] 断开连接,开始重连...", Options.AppName, Options.AppId);
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Connection = factory.CreateConnection();
|
logger.LogInformation("Synapse MQTT[{AppName}:{AppId}] 开始连接MQTT服务器...", Options.AppName, Options.AppId);
|
||||||
Logger.LogInformation("连接RabbitMQ服务器成功");
|
Client.ConnectAsync(clientOpts).Wait();
|
||||||
}
|
}
|
||||||
catch (BrokerUnreachableException e)
|
catch
|
||||||
{
|
{
|
||||||
Logger.LogError("连接RabbitMQ失败: \n{Err}", e);
|
logger.LogError("Synapse MQTT[{AppName}:{AppId}] 重连失败...", Options.AppName, Options.AppId);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
private IModel CreateChannel(ushort processNum = 0, string desc = "unknow")
|
|
||||||
{
|
|
||||||
IModel channel = null;
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var log = $"Channel [{desc}] 创建成功...";
|
|
||||||
channel = Connection.CreateModel();
|
|
||||||
if (processNum != 0)
|
|
||||||
{
|
|
||||||
channel.BasicQos(0, processNum, false);
|
|
||||||
log += $"最大处理器数量: {processNum}";
|
|
||||||
}
|
|
||||||
Logger.LogInformation(log);
|
|
||||||
}
|
|
||||||
catch (ConnectFailureException e)
|
|
||||||
{
|
|
||||||
Logger.LogError("Channel [{{Desc}}] 创建失败...\n {0}", e);
|
|
||||||
}
|
|
||||||
return channel;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void CheckAndCreateExchange()
|
|
||||||
{
|
|
||||||
var channel = CreateChannel(0, "Exchange");
|
|
||||||
try
|
|
||||||
{
|
|
||||||
channel.ExchangeDeclare(Options.SysName, ExchangeType.Topic, true, true, null);
|
|
||||||
Logger.LogDebug("Register Exchange Success");
|
|
||||||
}
|
|
||||||
catch (ConnectFailureException e)
|
|
||||||
{
|
|
||||||
Logger.LogError("Failed to declare Exchange.\n {Err}", e);
|
|
||||||
}
|
|
||||||
channel.Close();
|
|
||||||
Logger.LogDebug("Exchange Channel Closed");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ProcessAttribute()
|
private void ProcessAttribute()
|
||||||
{
|
{
|
||||||
EventRegistry = new List<RegisterItem>();
|
|
||||||
RpcRegistry = new List<RegisterItem>();
|
|
||||||
var stackTrace = new StackTrace();
|
var stackTrace = new StackTrace();
|
||||||
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1).GetMethod();
|
var callingMethod = stackTrace.GetFrame(stackTrace.FrameCount - 1)?.GetMethod();
|
||||||
var assembly = callingMethod.DeclaringType.Assembly;
|
var assembly = callingMethod?.DeclaringType?.Assembly;
|
||||||
var types = assembly.GetTypes(); // 获取程序集中的所有类型
|
var types = assembly!.GetTypes(); // 获取程序集中的所有类型
|
||||||
foreach (var type in types)
|
foreach (var type in types)
|
||||||
{
|
{
|
||||||
var methods = type.GetMethods(); // 获取类型中的所有方法
|
var methods = type.GetMethods(); // 获取类型中的所有方法
|
||||||
@@ -192,46 +233,93 @@ public partial class Synapse
|
|||||||
if (method.IsDefined(typeof(SynapseEventAttribute), false))
|
if (method.IsDefined(typeof(SynapseEventAttribute), false))
|
||||||
{
|
{
|
||||||
var attribute =
|
var attribute =
|
||||||
(SynapseEventAttribute)Attribute.GetCustomAttribute(method, typeof(SynapseEventAttribute));
|
(SynapseEventAttribute)Attribute.GetCustomAttribute(method, typeof(SynapseEventAttribute))!;
|
||||||
if (attribute != null)
|
var tmp = new RegisterItem
|
||||||
{
|
|
||||||
EventRegistry.Add(new RegisterItem
|
|
||||||
{
|
{
|
||||||
Key = attribute.Name ?? method.Name,
|
Key = attribute.Name ?? method.Name,
|
||||||
Class = type,
|
Class = type,
|
||||||
Method = method.Name
|
Method = method.Name
|
||||||
});
|
};
|
||||||
|
if (tmp.Key.StartsWith('/') || tmp.Key.EndsWith('/'))
|
||||||
|
{
|
||||||
|
logger.LogError("Synapse Event Register Error: {Key} Can't start or end of '/'", tmp.Key);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(tmp.Class!);
|
||||||
|
var mt = callClass.GetType().GetMethod(tmp.Method);
|
||||||
|
if (mt!.GetParameters().Length > 2 || mt.GetParameters().Length < 1)
|
||||||
|
{
|
||||||
|
logger.LogError(
|
||||||
|
"Synapse Event Register Error: Only one or two parameter supported. {Key} -> {Method}@{Class}",
|
||||||
|
tmp.Key, tmp.Method, tmp.Class.Name);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
EventRegistry.Add(tmp);
|
||||||
|
}
|
||||||
|
|
||||||
if (method.IsDefined(typeof(SynapseRpcAttribute), false))
|
if (method.IsDefined(typeof(SynapseRpcAttribute), false))
|
||||||
{
|
{
|
||||||
var attribute =
|
var attribute =
|
||||||
(SynapseRpcAttribute)Attribute.GetCustomAttribute(method, typeof(SynapseRpcAttribute));
|
(SynapseRpcAttribute)Attribute.GetCustomAttribute(method, typeof(SynapseRpcAttribute))!;
|
||||||
if (attribute != null)
|
var tmp = new RegisterItem
|
||||||
{
|
|
||||||
RpcRegistry.Add(new RegisterItem
|
|
||||||
{
|
{
|
||||||
Key = attribute.Name ?? $"{type.Name}.{method.Name}",
|
Key = attribute.Name ?? $"{type.Name}.{method.Name}",
|
||||||
Class = type,
|
Class = type,
|
||||||
Method = method.Name
|
Method = method.Name
|
||||||
});
|
};
|
||||||
|
if (tmp.Key.Contains('/') || tmp.Key.Contains('#') || tmp.Key.Contains('+'))
|
||||||
|
{
|
||||||
|
logger.LogError("Synapse Rpc Register Error: {Key} contains '/' , '#' , '+'", tmp.Key);
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var callClass = sp.CreateScope().ServiceProvider.GetRequiredService(tmp.Class!);
|
||||||
|
var mt = callClass.GetType().GetMethod(tmp.Method);
|
||||||
|
if (mt!.GetParameters().Length > 2)
|
||||||
|
{
|
||||||
|
logger.LogError(
|
||||||
|
"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);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (RpcRegistry.Any(x => x.Key == tmp.Key))
|
||||||
|
{
|
||||||
|
logger.LogError("Synapse Rpc Register Error: {Key} Already Exists -> {Method}@{Class}", tmp.Key,
|
||||||
|
tmp.Method, tmp.Class.Name);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
RpcRegistry.Add(tmp);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var events = EventRegistry.Aggregate(string.Empty,
|
var events = EventRegistry.Aggregate(string.Empty,
|
||||||
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
|
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class!.Name}");
|
||||||
var rpcList = RpcRegistry.Aggregate(string.Empty,
|
var rpcList = RpcRegistry.Aggregate(string.Empty,
|
||||||
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class.Name}");
|
(current, ev) => current + $"\n |- {ev.Key} -> {ev.Method}@{ev.Class!.Name}");
|
||||||
Logger.LogInformation(">>> Synapse System 读取Event方法:{Event}\n>>>Synapse System 读取RPC方法:{Rpc}", events, rpcList);
|
if (EventRegistry.Count > 0) logger.LogInformation(" >> Synapse System 读取Event方法:{Event}", events);
|
||||||
|
if (RpcRegistry.Count > 0) logger.LogInformation(" >> Synapse System 读取RPC方法:{Rpc}", rpcList);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class RegisterItem
|
public class RegisterItem
|
||||||
{
|
{
|
||||||
public string Key { get; set; }
|
public string? Key { get; init; }
|
||||||
|
|
||||||
public Type Class { get; set; }
|
public Type? Class { get; init; }
|
||||||
|
|
||||||
public string Method { get; set; }
|
public string? Method { get; init; }
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user