MdpSourceConfigService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.Extensions.Logging;
  4. using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
  5. namespace Admin.NET.Plugin.AiDOP.DataPlatform;
  6. /// <summary>数据源配置 API(供配置中心 sources 页读取与保存)。</summary>
  7. [ApiDescriptionSettings(Order = 324, Description = "数据中台数据源")]
  8. [Route("api/DataPlatform")]
  9. [NonUnify]
  10. public class MdpSourceConfigService : IDynamicApiController, ITransient
  11. {
  12. private readonly ISqlSugarClient _db;
  13. private readonly UserManager _user;
  14. private readonly MdpSourceScopeFactory _scopes;
  15. private readonly MdpSourcePasswordResolver _passwords;
  16. private readonly ILogger<MdpSourceConfigService> _logger;
  17. private readonly MdpApiPullEgress _egress;
  18. public MdpSourceConfigService(
  19. ISqlSugarClient db,
  20. UserManager user,
  21. MdpSourceScopeFactory scopes,
  22. MdpSourcePasswordResolver passwords,
  23. ILogger<MdpSourceConfigService> logger,
  24. MdpApiPullEgress egress)
  25. {
  26. _db = db;
  27. _user = user;
  28. _scopes = scopes;
  29. _passwords = passwords;
  30. _logger = logger;
  31. _egress = egress;
  32. }
  33. [DisplayName("数据源列表")]
  34. [HttpGet("sources")]
  35. public async Task<object> GetList([FromQuery] string? keyword, [FromQuery] string? type)
  36. {
  37. var q = VisibleSources();
  38. if (!string.IsNullOrWhiteSpace(keyword))
  39. {
  40. var kw = keyword.Trim();
  41. q = q.Where(x => x.SourceCode.Contains(kw) || x.SourceName.Contains(kw));
  42. }
  43. if (!string.IsNullOrWhiteSpace(type))
  44. q = q.Where(x => x.SourceType == type.Trim());
  45. var list = await q.OrderBy(x => x.SourceCode).ToListAsync();
  46. // 租户名称映射:SysTenant 表名是 PascalCase(EnableUnderLine=false),勿写成 sys_tenant
  47. var tenantIds = list.Where(x => x.TenantId != 0).Select(x => x.TenantId).Distinct().ToList();
  48. var tenantNameById = tenantIds.Count == 0
  49. ? new Dictionary<long, string>()
  50. : (await _db.Queryable<SysTenant>()
  51. .Where(x => tenantIds.Contains(x.Id))
  52. .Select(x => new { x.Id, x.Title })
  53. .ToListAsync())
  54. .ToDictionary(t => t.Id, t => t.Title ?? string.Empty);
  55. return new
  56. {
  57. list = list.Select(x => new
  58. {
  59. id = x.Id,
  60. tenantId = x.TenantId,
  61. tenantName = x.TenantId == 0
  62. ? "系统内置"
  63. : tenantNameById.TryGetValue(x.TenantId, out var name) && !string.IsNullOrWhiteSpace(name)
  64. ? name
  65. : x.TenantId.ToString(),
  66. sourceCode = x.SourceCode,
  67. systemCode = string.IsNullOrWhiteSpace(x.SystemCode) ? x.SourceCode : x.SystemCode,
  68. connMode = string.IsNullOrWhiteSpace(x.ConnMode) ? "EXTERNAL" : x.ConnMode,
  69. sourceName = x.SourceName,
  70. sourceType = x.SourceType,
  71. status = x.Status,
  72. direction = string.Equals(x.SourceType, "API", StringComparison.OrdinalIgnoreCase) ? "拉取"
  73. : string.Equals(x.SourceType, "FILE_EXCEL", StringComparison.OrdinalIgnoreCase) ? "文件入站" : "入站",
  74. dbType = x.DbType ?? "-",
  75. dbHost = x.DbHost,
  76. dbPort = x.DbPort,
  77. dbName = x.DbName,
  78. dbUser = x.DbUser,
  79. apiBaseUrl = x.ApiBaseUrl,
  80. host = string.Equals(x.SourceType, "API", StringComparison.OrdinalIgnoreCase)
  81. ? (x.ApiBaseUrl ?? "-")
  82. : string.Equals(x.SourceType, "FILE_EXCEL", StringComparison.OrdinalIgnoreCase)
  83. ? "-"
  84. : $"{x.DbHost}/{x.DbName}",
  85. health = string.Equals(x.SourceType, "FILE_EXCEL", StringComparison.OrdinalIgnoreCase)
  86. ? (string.IsNullOrWhiteSpace(x.SourceCode) ? "配置异常" : "可用")
  87. : x.HealthStatus switch
  88. {
  89. 1 => "正常",
  90. 0 => "异常",
  91. _ => "未知"
  92. },
  93. healthType = x.HealthStatus switch
  94. {
  95. 1 => "success",
  96. 0 => "danger",
  97. _ => "info"
  98. },
  99. lastCheck = x.LastHealthCheck?.ToString("yyyy-MM-dd HH:mm:ss") ?? "-",
  100. healthMsg = x.HealthMsg,
  101. dbExtraParams = x.DbExtraParams,
  102. remark = x.Remark,
  103. secretSource = string.Equals(x.SourceType, "DB", StringComparison.OrdinalIgnoreCase)
  104. ? _passwords.Classify(x.SourceCode, x.DbPasswordEnc)
  105. : null
  106. })
  107. };
  108. }
  109. [DisplayName("新建或更新数据源")]
  110. [HttpPost("sources")]
  111. public async Task<object> Save([FromBody] MdpSourceSaveInput input)
  112. {
  113. if (string.IsNullOrWhiteSpace(input.SourceCode) || string.IsNullOrWhiteSpace(input.SourceName) || string.IsNullOrWhiteSpace(input.SourceType))
  114. throw Oops.Oh("sourceCode、sourceName、sourceType 必填");
  115. var code = input.SourceCode.Trim();
  116. var tenantId = _user.TenantId;
  117. var mode = string.IsNullOrWhiteSpace(input.ConnMode) ? "EXTERNAL" : input.ConnMode.Trim().ToUpperInvariant();
  118. if (mode is not ("SELF" or "EXTERNAL"))
  119. throw Oops.Oh("connMode 只能是 SELF 或 EXTERNAL");
  120. if (tenantId == 0)
  121. throw Oops.Oh("系统种子来源只能由迁移脚本维护");
  122. var sourceType = input.SourceType.Trim();
  123. ValidateDbSource(input, sourceType, mode);
  124. var existing = await _db.Queryable<MdpSource>()
  125. .Where(x => x.TenantId == tenantId && x.SourceCode == code)
  126. .FirstAsync();
  127. if (existing == null)
  128. {
  129. await _db.Insertable(new MdpSource
  130. {
  131. TenantId = tenantId,
  132. SourceCode = code,
  133. SourceName = input.SourceName.Trim(),
  134. SourceType = sourceType,
  135. SystemCode = input.SystemCode?.Trim(),
  136. ConnMode = mode,
  137. Status = 1,
  138. DbType = NormalizeDbType(input.DbType),
  139. DbHost = mode == "SELF" ? null : input.DbHost?.Trim(),
  140. DbPort = mode == "SELF" ? null : input.DbPort,
  141. DbName = mode == "SELF" ? null : input.DbName?.Trim(),
  142. DbUser = mode == "SELF" ? null : input.DbUser?.Trim(),
  143. DbPasswordEnc = mode == "SELF" ? null : EncryptPassword(input.DbPassword),
  144. DbExtraParams = mode == "SELF" ? null : MdpSourceScopeFactory.SanitizeStoredExtra(input.DbType, input.DbExtraParams),
  145. ApiBaseUrl = input.ApiBaseUrl?.Trim(),
  146. Remark = input.Remark?.Trim(),
  147. CreateTime = DateTime.Now,
  148. UpdateTime = DateTime.Now
  149. }).ExecuteCommandAsync();
  150. }
  151. else
  152. {
  153. if (existing.TenantId == 0)
  154. throw Oops.Oh("系统种子来源只能由迁移脚本维护");
  155. existing.SourceName = input.SourceName.Trim();
  156. existing.SourceType = sourceType;
  157. existing.SystemCode = input.SystemCode?.Trim();
  158. existing.ConnMode = mode;
  159. existing.DbType = NormalizeDbType(input.DbType);
  160. existing.DbHost = mode == "SELF" ? null : input.DbHost?.Trim();
  161. existing.DbPort = mode == "SELF" ? null : input.DbPort;
  162. existing.DbName = mode == "SELF" ? null : input.DbName?.Trim();
  163. existing.DbUser = mode == "SELF" ? null : input.DbUser?.Trim();
  164. if (mode == "SELF")
  165. existing.DbPasswordEnc = null;
  166. else if (!string.IsNullOrEmpty(input.DbPassword))
  167. existing.DbPasswordEnc = EncryptPassword(input.DbPassword);
  168. existing.DbExtraParams = mode == "SELF" ? null : MdpSourceScopeFactory.SanitizeStoredExtra(input.DbType, input.DbExtraParams);
  169. existing.ApiBaseUrl = input.ApiBaseUrl?.Trim();
  170. existing.Remark = input.Remark?.Trim();
  171. existing.UpdateTime = DateTime.Now;
  172. await _db.Updateable(existing).ExecuteCommandAsync();
  173. }
  174. return new { sourceCode = code };
  175. }
  176. private static void ValidateDbSource(MdpSourceSaveInput input, string sourceType, string mode)
  177. {
  178. if (!string.Equals(sourceType, "DB", StringComparison.OrdinalIgnoreCase))
  179. return;
  180. var dbType = NormalizeDbType(input.DbType);
  181. if (!MdpDbSyncRules.IsSupportedDbType(dbType))
  182. throw Oops.Oh("数据库类型只支持 SQLSERVER 或 MYSQL");
  183. if (mode == "EXTERNAL" && (string.IsNullOrWhiteSpace(input.DbHost) || input.DbPort is null or <= 0
  184. || string.IsNullOrWhiteSpace(input.DbName) || string.IsNullOrWhiteSpace(input.DbUser)))
  185. throw Oops.Oh("外部数据库必须填写主机、端口、库名和账号");
  186. }
  187. private static string? NormalizeDbType(string? dbType) =>
  188. string.IsNullOrWhiteSpace(dbType) ? null : dbType.Trim().ToUpperInvariant();
  189. private static string? EncryptPassword(string? password) =>
  190. string.IsNullOrEmpty(password) ? null : CryptogramUtil.Encrypt(password);
  191. [DisplayName("测试数据源连接")]
  192. [HttpPost("sources/{sourceCode}/test")]
  193. public async Task<object> Test([FromRoute] string sourceCode)
  194. {
  195. var source = await FindVisibleSourceAsync(sourceCode);
  196. if (string.Equals(source.SourceType, "DB", StringComparison.OrdinalIgnoreCase))
  197. {
  198. try
  199. {
  200. var started = DateTime.UtcNow;
  201. var scope = await _scopes.GetScopeAsync(source);
  202. await scope.Ado.GetScalarAsync("SELECT 1");
  203. var elapsed = (int)(DateTime.UtcNow - started).TotalMilliseconds;
  204. return new { ok = true, message = "数据库连接成功", dbType = source.DbType, elapsedMs = elapsed };
  205. }
  206. catch (Exception ex)
  207. {
  208. _logger.LogWarning(ex, "数据源 {SourceCode} 测试连接失败,tenant={TenantId}", source.SourceCode, source.TenantId);
  209. var error = MdpDbConnectionError.Describe(ex);
  210. return new { ok = false, code = error.Code, message = error.Message };
  211. }
  212. }
  213. if (string.Equals(source.SourceType, "API", StringComparison.OrdinalIgnoreCase))
  214. {
  215. if (string.IsNullOrWhiteSpace(source.ApiBaseUrl))
  216. return new { ok = false, message = "未填写接口地址" };
  217. try
  218. {
  219. var endpoint = new Uri(source.ApiBaseUrl);
  220. using var http = _egress.Open(source.TenantId, source.Id, endpoint, requireHttps: false);
  221. http.Timeout = TimeSpan.FromSeconds(5);
  222. using var resp = await http.GetAsync(endpoint, HttpCompletionOption.ResponseHeadersRead);
  223. return new { ok = resp.IsSuccessStatusCode, message = $"HTTP {(int)resp.StatusCode}" };
  224. }
  225. catch (MdpApiPullException error)
  226. {
  227. return new { ok = false, code = error.Code, message = "目标未获准访问" };
  228. }
  229. catch (Exception)
  230. {
  231. return new { ok = false, message = "接口探测失败" };
  232. }
  233. }
  234. return new { ok = true, message = "对方推送不需要探测对端连接" };
  235. }
  236. [DisplayName("停用数据源前的登记检查")]
  237. [HttpGet("sources/{sourceCode}/bindings")]
  238. public async Task<object> Bindings([FromRoute] string sourceCode)
  239. {
  240. var source = await FindVisibleSourceAsync(sourceCode);
  241. var system = string.IsNullOrWhiteSpace(source.SystemCode) ? source.SourceCode : source.SystemCode;
  242. var rows = await VisibleBindingsAsync(source, system);
  243. var needConfirm = rows.Count > 0 || await HasBindingsAsync(system);
  244. return new
  245. {
  246. systemCode = system,
  247. bindings = rows.Select(row => new { tenantId = row.TenantId, stdObject = row.StdObject }),
  248. needConfirm
  249. };
  250. }
  251. [DisplayName("停用数据源")]
  252. [HttpPost("sources/{sourceCode}/disable")]
  253. public async Task<object> Disable([FromRoute] string sourceCode, [FromBody] MdpSourceDisableInput input)
  254. {
  255. var source = await FindVisibleSourceAsync(sourceCode);
  256. var system = string.IsNullOrWhiteSpace(source.SystemCode) ? source.SourceCode : source.SystemCode;
  257. if (input.Confirm != true && await HasBindingsAsync(system))
  258. {
  259. var rows = await VisibleBindingsAsync(source, system);
  260. return new { disabled = false, needConfirm = true, bindings = rows.Select(row => new { stdObject = row.StdObject }) };
  261. }
  262. source.Status = 0;
  263. source.UpdateTime = DateTime.Now;
  264. await _db.Updateable(source).UpdateColumns(x => new { x.Status, x.UpdateTime }).ExecuteCommandAsync();
  265. return new { disabled = true, sourceCode = source.SourceCode };
  266. }
  267. private ISugarQueryable<MdpSource> VisibleSources()
  268. {
  269. var query = _db.Queryable<MdpSource>();
  270. if (_user.SuperAdmin)
  271. return query;
  272. var tenantId = _user.TenantId;
  273. return query.Where(x => x.TenantId == tenantId && x.TenantId > 0);
  274. }
  275. private async Task<MdpSource> FindVisibleSourceAsync(string sourceCode)
  276. {
  277. var code = sourceCode.Trim();
  278. return await VisibleSources().Where(x => x.SourceCode == code).FirstAsync()
  279. ?? throw new AppFriendlyException($"未找到来源 {code}", null)
  280. {
  281. StatusCode = StatusCodes.Status400BadRequest,
  282. ValidationException = true
  283. };
  284. }
  285. private Task<List<SourceBinding>> VisibleBindingsAsync(MdpSource source, string system) =>
  286. _db.Ado.SqlQueryAsync<SourceBinding>(
  287. """
  288. SELECT tenant_id AS TenantId, std_object AS StdObject
  289. FROM mdp_tenant_std_source
  290. WHERE source_system=@sys AND (@allTenants = 1 OR tenant_id=@tenantId)
  291. ORDER BY tenant_id, std_object
  292. """,
  293. new { sys = system, allTenants = _user.SuperAdmin ? 1 : 0, tenantId = source.TenantId });
  294. private async Task<bool> HasBindingsAsync(string system) =>
  295. await _db.Ado.GetIntAsync("SELECT COUNT(*) FROM mdp_tenant_std_source WHERE source_system=@sys", new { sys = system }) > 0;
  296. private sealed class SourceBinding
  297. {
  298. public long TenantId { get; set; }
  299. public string StdObject { get; set; } = string.Empty;
  300. }
  301. }
  302. public sealed class MdpSourceSaveInput
  303. {
  304. public string SourceCode { get; set; } = "";
  305. public string SourceName { get; set; } = "";
  306. public string SourceType { get; set; } = "DB";
  307. public string? SystemCode { get; set; }
  308. public string? ConnMode { get; set; }
  309. public string? DbType { get; set; }
  310. public string? DbHost { get; set; }
  311. public int? DbPort { get; set; }
  312. public string? DbName { get; set; }
  313. public string? DbUser { get; set; }
  314. public string? DbPassword { get; set; }
  315. public string? DbExtraParams { get; set; }
  316. public string? ApiBaseUrl { get; set; }
  317. public string? Remark { get; set; }
  318. }
  319. public sealed class MdpSourceDisableInput
  320. {
  321. public bool? Confirm { get; set; }
  322. }