Compare commits

...
3 Commits
15 changed files with 130 additions and 42 deletions
+20 -5
View File
@@ -1,22 +1,37 @@
namespace SimApi.Communications; using System.ComponentModel.DataAnnotations;
namespace SimApi.Communications;
/// <summary> /// <summary>
/// 只有ID的请求 /// 只有ID的请求
/// </summary> /// </summary>
public record SimApiIdOnlyRequest(int Id); public class SimApiIdOnlyRequest
{
[Required] public int Id { get; set; }
}
/// <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; }
}
+29 -11
View File
@@ -7,8 +7,11 @@ namespace SimApi.Communications;
/// <summary> /// <summary>
/// 基础相应 /// 基础相应
/// </summary> /// </summary>
public record SimApiBaseResponse(int Code = 200, string Message = "成功") public class SimApiBaseResponse(int code = 200, string message = "成功")
{ {
public int Code { get; set; } = code;
public string Message { get; set; } = message;
/// <summary> /// <summary>
/// 默认错误代码对应提示信息 /// 默认错误代码对应提示信息
/// </summary> /// </summary>
@@ -23,7 +26,7 @@ public record SimApiBaseResponse(int Code = 200, string Message = "成功")
{ 500, "服务器错误" } { 500, "服务器错误" }
}; };
public SimApiBaseResponse(int code) : this(code, MsgBox.ContainsKey(code) ? MsgBox[code] : "未知错误") public SimApiBaseResponse(int code) : this(code, MsgBox.GetValueOrDefault(code, "未知错误"))
{ {
} }
@@ -49,17 +52,32 @@ public record SimApiBaseResponse(int Code = 200, string Message = "成功")
/// 动态内容分页 /// 动态内容分页
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public record SimApiBasePageResponse<T>( public class SimApiBasePageResponse<T>() : SimApiBaseResponse
T List, {
int Page = 1, public T List { get; set; }
int Count = 1, public int Page { get; set; } = 1;
int Total = 1, public int Count { get; set; } = 20;
int Code = 200, public int Total { get; set; }
string Message = "成功") : SimApiBaseResponse(Code, Message);
public SimApiBasePageResponse(T list, int page, int count, int total) : this()
{
List = list;
Page = page;
Count = count;
Total = total;
}
}
/// <summary> /// <summary>
/// 动态Data返回 /// 动态Data返回
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
public record SimApiBaseResponse<T>(T Data, int Code = 200, string Message = "成功") : SimApiBaseResponse(Code, public class SimApiBaseResponse<T>() : SimApiBaseResponse
Message); {
public T Data { get; set; }
public SimApiBaseResponse(T data) : this()
{
Data = data;
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using Swashbuckle.AspNetCore.SwaggerUI; using Swashbuckle.AspNetCore.SwaggerUI;
namespace SimApi.Configs; namespace SimApi.Configurations;
/// <summary> /// <summary>
/// 文档组配置 /// 文档组配置
+2 -2
View File
@@ -1,6 +1,6 @@
using System; using System;
namespace SimApi.Configs; namespace SimApi.Configurations;
public class SimApiOptions public class SimApiOptions
{ {
@@ -11,7 +11,7 @@ public class SimApiOptions
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; } = false;
+1 -1
View File
@@ -1,4 +1,4 @@
namespace SimApi.Configs; namespace SimApi.Configurations;
public class SimApiStorageOptions public class SimApiStorageOptions
{ {
+1 -1
View File
@@ -1,4 +1,4 @@
namespace SimApi.Configs; namespace SimApi.Configurations;
public class SimApiSynapseOptions public class SimApiSynapseOptions
{ {
+26 -2
View File
@@ -50,7 +50,7 @@ public class SimApiBaseController : Controller
} }
/// <summary> /// <summary>
/// 检测条件,根据条件返回报错 /// 检测条件,根据条件返回报错 如果condition是ture报错
/// </summary> /// </summary>
/// <param name="condition">检测条件</param> /// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param> /// <param name="code">错误代码</param>
@@ -63,6 +63,30 @@ public class SimApiBaseController : Controller
} }
} }
/// <summary>
/// 检测条件,根据条件返回报错 如果condition是ture报错
/// </summary>
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
protected static void ErrorWhenTrue(bool condition, int code = 500, 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 = 500, string message = "")
{
ErrorWhen(!condition, code, message);
}
/// <summary> /// <summary>
/// 检测给定的变量是否为NUll /// 检测给定的变量是否为NUll
/// </summary> /// </summary>
@@ -80,6 +104,6 @@ public class SimApiBaseController : Controller
/// <returns></returns> /// <returns></returns>
protected SimApiBaseResponse<string> UploadFile() protected SimApiBaseResponse<string> UploadFile()
{ {
return new SimApiBaseResponse<string>(null); return new SimApiBaseResponse<string>();
} }
} }
+5 -2
View File
@@ -28,7 +28,10 @@ public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
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>
@@ -45,7 +48,7 @@ public class SimApiCommonController(SimApiAuth auth) : SimApiBaseController
token = value; token = value;
} }
auth.Logout(token); auth.Logout(token!);
return new SimApiBaseResponse(); return new SimApiBaseResponse();
} }
} }
+3 -2
View File
@@ -2,7 +2,7 @@
using System.IO; using System.IO;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Minio; using Minio;
using SimApi.Configs; using SimApi.Configurations;
namespace SimApi.Helpers; namespace SimApi.Helpers;
@@ -14,7 +14,7 @@ public class SimApiStorage
private string ServeUrl { get; } private string ServeUrl { get; }
public string Bucket { get; } private string Bucket { get; }
private IHttpContextAccessor HttpContextAccessor { get; } private IHttpContextAccessor HttpContextAccessor { get; }
@@ -46,6 +46,7 @@ public class SimApiStorage
{ {
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;
+18
View File
@@ -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;
@@ -71,4 +72,21 @@ public static class SimApiUtil
{ {
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);
}
} }
+2 -1
View File
@@ -23,11 +23,12 @@ public class SimApiLogger(string name) : ILogger
_ => 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.ToString("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);
} }
} }
+4 -7
View File
@@ -7,14 +7,11 @@ namespace SimApi.Models;
public class SimApiBaseModel public class SimApiBaseModel
{ {
[Column(Order = 1)] [Column(Order = 1)] public string Id { get; set; } = Guid.NewGuid().ToString();
public string Id { get; set; } = Guid.NewGuid().ToString();
[Column(Order = 9998)] [Column(Order = 9998)] public DateTime UpdatedAt { get; set; } = DateTime.Now;
public DateTime UpdatedAt { get; set; } = SimApiUtil.CstNow;
[Column(Order = 9999)] [Column(Order = 9999)] public DateTime CreatedAt { get; set; } = DateTime.Now;
public DateTime CreatedAt { get; set; } = SimApiUtil.CstNow;
protected virtual string[] MapperIgnoreField { get; set; } = { "Id", "CreatedAt", "UpdatedAt" }; protected virtual string[] MapperIgnoreField { get; set; } = { "Id", "CreatedAt", "UpdatedAt" };
@@ -84,6 +81,6 @@ public class SimApiBaseModel
/// <returns></returns> /// <returns></returns>
public void UpdateTime() public void UpdateTime()
{ {
GetType().GetProperty(UpdatedTimeField)?.SetValue(this, SimApiUtil.CstNow); GetType().GetProperty(UpdatedTimeField)?.SetValue(this, DateTime.Now);
} }
} }
+3 -1
View File
@@ -6,7 +6,7 @@ using Microsoft.OpenApi.Models;
using SimApi.Middlewares; using SimApi.Middlewares;
using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SimApi.Configs; using SimApi.Configurations;
using SimApi.Logger; using SimApi.Logger;
namespace SimApi; namespace SimApi;
@@ -30,6 +30,7 @@ public static class SimApiExtensions
logger.AddProvider(new SimApiLoggerProvider()); logger.AddProvider(new SimApiLoggerProvider());
}); });
} }
// 是否使用 AUTH // 是否使用 AUTH
if (simApiOptions.EnableSimApiAuth) if (simApiOptions.EnableSimApiAuth)
{ {
@@ -199,6 +200,7 @@ public static class SimApiExtensions
var logger = builder.ApplicationServices.GetRequiredService<ILogger<SimApiOptions>>(); var logger = builder.ApplicationServices.GetRequiredService<ILogger<SimApiOptions>>();
logger.LogInformation("当前时区: {LocalId}", TimeZoneInfo.Local.Id);
if (options.EnableForwardHeaders) if (options.EnableForwardHeaders)
{ {
logger.LogInformation("开始配置ForwardedHeaders..."); logger.LogInformation("开始配置ForwardedHeaders...");
+5 -5
View File
@@ -2,10 +2,6 @@ using System;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Text.Encodings.Web;
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 RabbitMQ.Client.Events;
@@ -52,8 +48,12 @@ public partial class Synapse
var paramObj = JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption); var paramObj = JsonSerializer.Deserialize(reqBody, pt, SimApiUtil.JsonOption);
param = new[] { paramObj }; param = new[] { paramObj };
} }
var ret = mt.Invoke(callClass, param); var ret = mt.Invoke(callClass, param);
res = new SimApiBaseResponse<object>(ret); res = new SimApiBaseResponse<object>
{
Data = ret
};
} }
catch (TargetInvocationException e) catch (TargetInvocationException e)
{ {
+10 -1
View File
@@ -8,7 +8,7 @@ using RabbitMQ.Client;
using RabbitMQ.Client.Exceptions; using RabbitMQ.Client.Exceptions;
using SimApi.Attributes; using SimApi.Attributes;
using SimApi.Communications; using SimApi.Communications;
using SimApi.Configs; using SimApi.Configurations;
using SimApi.Helpers; using SimApi.Helpers;
namespace SimApi; namespace SimApi;
@@ -50,6 +50,7 @@ public partial class Synapse
{ {
Logger.LogCritical("Synapse初始化失败: AppName or SysName 错误"); Logger.LogCritical("Synapse初始化失败: AppName or 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("System Name: {SysName}\nApp Name: {AppName}\nAppId: {AppId}", Options.SysName,
Options.AppName, Options.AppId); Options.AppName, Options.AppId);
@@ -76,10 +77,12 @@ public partial class Synapse
RunRpcClient(); RunRpcClient();
Logger.LogInformation("Rpc Client Ready, Client Timeout: {OptionsRpcTimeout}s", Options.RpcTimeout); Logger.LogInformation("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();
@@ -99,6 +102,7 @@ public partial class Synapse
var data = FireRpc(appName, method, param); var data = FireRpc(appName, method, param);
res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption); res = JsonSerializer.Deserialize<SimApiBaseResponse<T>>(data, SimApiUtil.JsonOption);
} }
return res as SimApiBaseResponse<T>; return res as SimApiBaseResponse<T>;
} }
@@ -152,12 +156,14 @@ public partial class Synapse
channel.BasicQos(0, processNum, false); channel.BasicQos(0, processNum, false);
log += $"最大处理器数量: {processNum}"; log += $"最大处理器数量: {processNum}";
} }
Logger.LogInformation(log); Logger.LogInformation(log);
} }
catch (ConnectFailureException e) catch (ConnectFailureException e)
{ {
Logger.LogError("Channel [{{Desc}}] 创建失败...\n {0}", e); Logger.LogError("Channel [{{Desc}}] 创建失败...\n {0}", e);
} }
return channel; return channel;
} }
@@ -173,6 +179,7 @@ public partial class Synapse
{ {
Logger.LogError("Failed to declare Exchange.\n {Err}", e); Logger.LogError("Failed to declare Exchange.\n {Err}", e);
} }
channel.Close(); channel.Close();
Logger.LogDebug("Exchange Channel Closed"); Logger.LogDebug("Exchange Channel Closed");
} }
@@ -204,6 +211,7 @@ public partial class Synapse
}); });
} }
} }
if (method.IsDefined(typeof(SynapseRpcAttribute), false)) if (method.IsDefined(typeof(SynapseRpcAttribute), false))
{ {
var attribute = var attribute =
@@ -220,6 +228,7 @@ public partial class Synapse
} }
} }
} }
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,