From fb3325090e035f0ba2362ee915df837766fb383d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Tue, 12 Dec 2023 20:02:55 +0800 Subject: [PATCH 01/45] mongodb support init. --- .../AgileConfig.Server.Data.Mongodb.csproj | 16 + .../IRepository.cs | 118 +++ .../MongodbAccess.cs | 62 ++ AgileConfig.Server.Data.Mongodb/Repository.cs | 211 ++++ .../AdmBasicAuthService.cs | 29 + .../AgileConfig.Server.Mongodb.Service.csproj | 19 + .../AppService.cs | 173 +++ .../ConfigService.cs | 996 ++++++++++++++++++ .../MongodbServiceExtensions.cs | 12 + .../SettingService.cs | 181 ++++ .../UserService.cs | 104 ++ AgileConfig.sln | 14 + src/AgileConfig.Server.Apisite/Startup.cs | 11 +- .../appsettings.Development.json | 4 +- .../appsettings.json | 3 +- 15 files changed, 1948 insertions(+), 5 deletions(-) create mode 100644 AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj create mode 100644 AgileConfig.Server.Data.Mongodb/IRepository.cs create mode 100644 AgileConfig.Server.Data.Mongodb/MongodbAccess.cs create mode 100644 AgileConfig.Server.Data.Mongodb/Repository.cs create mode 100644 AgileConfig.Server.Mongodb.Service/AdmBasicAuthService.cs create mode 100644 AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj create mode 100644 AgileConfig.Server.Mongodb.Service/AppService.cs create mode 100644 AgileConfig.Server.Mongodb.Service/ConfigService.cs create mode 100644 AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs create mode 100644 AgileConfig.Server.Mongodb.Service/SettingService.cs create mode 100644 AgileConfig.Server.Mongodb.Service/UserService.cs diff --git a/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj b/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj new file mode 100644 index 00000000..40fc815e --- /dev/null +++ b/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj @@ -0,0 +1,16 @@ + + + + net8.0 + enable + enable + + + + + + + + + + diff --git a/AgileConfig.Server.Data.Mongodb/IRepository.cs b/AgileConfig.Server.Data.Mongodb/IRepository.cs new file mode 100644 index 00000000..e8a4801b --- /dev/null +++ b/AgileConfig.Server.Data.Mongodb/IRepository.cs @@ -0,0 +1,118 @@ +using System.Linq.Expressions; +using MongoDB.Bson; +using MongoDB.Driver; +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.Data.Mongodb; + +public interface IRepository +{ + IMongoDatabase Database { get; } +} + +public interface IRepository : IRepository where T : new() +{ + /// + /// mongodb客户端 + /// + IMongoClient Client { get; } + + /// + /// 获取 该实体Mongodb的集合 + /// + IMongoCollection Collection { get; } + + /// + /// Mongodb queryable + /// + IMongoQueryable MongodbQueryable { get; } + + /// + /// 查询数据 + /// + /// + /// + IMongoQueryable SearchFor(Expression> predicate); + + /// + /// 异步 数据查询 + /// + /// + /// + IAsyncEnumerable SearchForAsync(FilterDefinition filter); + + /// + /// 根据 Id 获取单条记录,不存在将会返回null + /// + /// + /// + T? Find(string id); + + /// + /// 根据 Id 获取单条记录,不存在将会返回null + /// + /// + /// + Task FindAsync(string id); + + void Insert(params T[] source); + + void Insert(IReadOnlyCollection source); + + /// + /// 插入数据 + /// + /// + /// + Task InsertAsync(params T[] source); + + /// + /// 插入数据 + /// + /// + /// + Task InsertAsync(IReadOnlyCollection source); + + /// + /// 删除数据 + /// + /// + /// + Task DeleteAsync(Expression> filter); + + /// + /// 删除数据 + /// + /// + /// + Task DeleteAsync(FilterDefinition filter); + + /// + /// 根据ID删除 + /// + /// + /// + Task DeleteAsync(string id); + + /// + /// 根据查询条件更新数据 + /// + /// + /// + /// + Task UpdateAsync(Expression> predicate, UpdateDefinition update); + + /// + /// 根据实体修改数据 + /// + /// + /// + /// If the entity no exists property 'id',then will throw exception. + Task UpdateAsync(T entity); + + Task UpdateAsync(IReadOnlyCollection collection); + + ReplaceOneResult Update(T entity); + + long Update(IReadOnlyCollection collection); +} \ No newline at end of file diff --git a/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs b/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs new file mode 100644 index 00000000..16f9474e --- /dev/null +++ b/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs @@ -0,0 +1,62 @@ +using System.Collections.Concurrent; +using System.Security; +using MongoDB.Driver; +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.Data.Mongodb; + +public abstract class MongodbAccess +{ + private readonly record struct Db(string DatabaseName,IMongoClient Client); + + private static readonly Lazy> LazyMongoClients = new(); + + private readonly string _connectionString; + + internal MongodbAccess(string? connectionString) + { + if (string.IsNullOrEmpty(connectionString)) + throw new Exception("没有配置Mongodb连接字符串"); + _connectionString = connectionString; + if (LazyMongoClients is not { IsValueCreated: true } || LazyMongoClients.Value.ContainsKey(connectionString)) + { + var url = MongoUrl.Create(connectionString); + + // 连接字符串如果不指定数据库名称,那么默认数据库名称就是 AgileConfig + const string defaultDataBaseName = "AgileConfig"; + var databaseName = string.IsNullOrEmpty(url.DatabaseName) ? defaultDataBaseName : url.DatabaseName; + LazyMongoClients.Value.TryAdd(connectionString, new Db(databaseName, new MongoClient(url))); + } + } + + /// + /// 获取Mongodb客户端 + /// + internal IMongoClient Client => LazyMongoClients.Value[_connectionString].Client ?? throw new Exception("IMongoClient value is null"); + + /// + /// 获取 MongoDB 数据库 + /// + public IMongoDatabase Database => Client.GetDatabase(LazyMongoClients.Value[_connectionString].DatabaseName); +} + +public class MongodbAccess(string? connectionString) : MongodbAccess(connectionString) + where T : new() +{ + /// + /// database collection name + /// + public string CollectionName => typeof(T).Name; + + /// + /// 获取 该实体中 MongoDB数据库的集合 + /// + public IMongoCollection Collection => Database.GetCollection(CollectionName); + + /// + /// 获取 提供对MongoDB数据查询的Queryable + /// + /// + public IMongoQueryable MongoQueryable => Database.GetCollection(CollectionName).AsQueryable( + new AggregateOptions { AllowDiskUse = true }); +} \ No newline at end of file diff --git a/AgileConfig.Server.Data.Mongodb/Repository.cs b/AgileConfig.Server.Data.Mongodb/Repository.cs new file mode 100644 index 00000000..5fb35166 --- /dev/null +++ b/AgileConfig.Server.Data.Mongodb/Repository.cs @@ -0,0 +1,211 @@ +using System.Linq.Expressions; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using MongoDB.Bson; +using MongoDB.Driver; +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.Data.Mongodb; + +public class Repository : IRepository where T : new() +{ + public IMongoDatabase Database => _access.Database; + public IMongoClient Client => _access.Client; + public IMongoCollection Collection => _access.Collection; + public IMongoQueryable MongodbQueryable => _access.MongoQueryable; + + private readonly MongodbAccess _access; + + public Repository(string? connectionString) + { + _access = new MongodbAccess(connectionString); + } + + [ActivatorUtilitiesConstructor] + public Repository(IConfiguration configuration) + { + var connectionString = configuration["db:conn"]; + _access = new MongodbAccess(connectionString); + } + + public IMongoQueryable SearchFor(Expression> predicate) + { + return _access.MongoQueryable.Where(predicate); + } + + public async IAsyncEnumerable SearchForAsync(FilterDefinition filter) + { + var result = await Collection.FindAsync(filter); + while (await result.MoveNextAsync()) + { + foreach (var item in result.Current) + { + yield return item; + } + } + } + + public T? Find(string id) + { + var idProperty = typeof(T).GetProperty("Id"); + if (idProperty != null && idProperty.PropertyType == typeof(string)) + { + var definitionString = new StringFieldDefinition("Id"); + var filter = Builders.Filter.Eq(definitionString, id); + return Collection.Find(filter).SingleOrDefault(); + } + return default; + } + + public async Task FindAsync(string id) + { + var idProperty = typeof(T).GetProperty("Id"); + if (idProperty != null && idProperty.PropertyType == typeof(string)) + { + var definitionString = new StringFieldDefinition("Id"); + var filter = Builders.Filter.Eq(definitionString, id); + return await (await Collection.FindAsync(filter)).SingleOrDefaultAsync(); + } + return default; + } + + public void Insert(params T[] source) + { + if(source.Length != 0) + Collection.InsertMany(source); + } + + public void Insert(IReadOnlyCollection source) + { + if(source.Count != 0) + Collection.InsertMany(source); + } + + public async Task InsertAsync(params T[] source) + { + if(source.Length != 0) + await Collection.InsertManyAsync(source); + } + + public async Task InsertAsync(IReadOnlyCollection source) + { + if(source.Count != 0) + await Collection.InsertManyAsync(source); + } + + public async Task DeleteAsync(Expression> filter) + { + var result = await Collection.DeleteManyAsync(filter); + return result; + } + + public async Task DeleteAsync(FilterDefinition filter) + { + var result = await Collection.DeleteManyAsync(filter); + return result; + } + + public async Task DeleteAsync(string id) + { + if (typeof(T).GetProperty("Id") == null) + throw new Exception($"type {typeof(T)} no exists property 'id'."); + var filter = Builders.Filter.Eq(new StringFieldDefinition("Id"), id); + return await Collection.DeleteOneAsync(filter); + } + + public async Task UpdateAsync(Expression> predicate, UpdateDefinition update) + { + var result = await Collection.UpdateManyAsync(predicate, update); + return result; + } + + public async Task UpdateAsync(T entity) + { + var idProperty = typeof(T).GetProperty("Id"); + if (idProperty == null) + throw new ArgumentException("In the entity no exists property 'id'.", nameof(entity)); + var id = idProperty.GetValue(entity); + if (id == null) + throw new ArgumentException("The entity property 'id' value is null.", nameof(entity)); + var idTypeName = idProperty.PropertyType.Name; + FilterDefinition filter; + switch (idTypeName) + { + case "ObjectId": + var definitionObjectId = new StringFieldDefinition("Id"); + filter = Builders.Filter.Eq(definitionObjectId, (ObjectId)id); + break; + case "Int32": + var definitionInt32 = new StringFieldDefinition("Id"); + filter = Builders.Filter.Eq(definitionInt32, (int)id); + break; + case "String": + var definitionString = new StringFieldDefinition("Id"); + filter = Builders.Filter.Eq(definitionString, (string)id); + break; + default: + throw new Exception($"Do not support {idTypeName} type!"); + } + + var result = await Collection.ReplaceOneAsync(filter, entity); + return result; + } + + public async Task UpdateAsync(IReadOnlyCollection collection) + { + var rows = 0L; + foreach (var item in collection) + { + var result = await UpdateAsync(item); + rows += result.ModifiedCount; + } + + return rows; + } + + public ReplaceOneResult Update(T entity) + { + var idProperty = typeof(T).GetProperty("Id"); + if (idProperty == null) + throw new ArgumentException("In the entity no exists property 'id'.", nameof(entity)); + var id = idProperty.GetValue(entity); + if (id == null) + throw new ArgumentException("The entity property 'id' value is null.", nameof(entity)); + var idTypeName = idProperty.PropertyType.Name; + FilterDefinition filter; + switch (idTypeName) + { + case "ObjectId": + var definitionObjectId = new StringFieldDefinition("Id"); + filter = Builders.Filter.Eq(definitionObjectId, (ObjectId)id); + break; + case "Int32": + var definitionInt32 = new StringFieldDefinition("Id"); + filter = Builders.Filter.Eq(definitionInt32, (int)id); + break; + case "String": + var definitionString = new StringFieldDefinition("Id"); + filter = Builders.Filter.Eq(definitionString, (string)id); + break; + default: + throw new Exception($"Do not support {idTypeName} type!"); + } + + var result = Collection.ReplaceOne(filter, entity); + return result; + } + + public long Update(IReadOnlyCollection collection) + { + var rows = 0L; + foreach (var item in collection) + { + var result = Update(item); + rows += result.ModifiedCount; + } + + return rows; + } + + +} \ No newline at end of file diff --git a/AgileConfig.Server.Mongodb.Service/AdmBasicAuthService.cs b/AgileConfig.Server.Mongodb.Service/AdmBasicAuthService.cs new file mode 100644 index 00000000..e408a064 --- /dev/null +++ b/AgileConfig.Server.Mongodb.Service/AdmBasicAuthService.cs @@ -0,0 +1,29 @@ +using AgileConfig.Server.Common; +using AgileConfig.Server.IService; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; + +namespace AgileConfig.Server.Mongodb.Service; + +public class AdmBasicAuthService(IUserService userService, ILoggerFactory lf) : IAdmBasicAuthService +{ + private readonly ILogger _logger = lf.CreateLogger(); + + public async Task ValidAsync(HttpRequest httpRequest) + { + var userPassword = httpRequest.GetUserNamePasswordFromBasicAuthorization(); + if (string.IsNullOrEmpty(userPassword.Item1)||string.IsNullOrEmpty(userPassword.Item2)) + { + _logger.LogWarning("Basic auth header have no username or password"); + return false; + } + + var result = await userService.ValidateUserPassword(userPassword.Item1, userPassword.Item2); + return result; + } + + public (string, string) GetUserNamePassword(HttpRequest httpRequest) + { + return httpRequest.GetUserNamePasswordFromBasicAuthorization(); + } +} \ No newline at end of file diff --git a/AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj b/AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj new file mode 100644 index 00000000..324f840d --- /dev/null +++ b/AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj @@ -0,0 +1,19 @@ + + + + net8.0 + enable + enable + + + + + + + + + + + + + diff --git a/AgileConfig.Server.Mongodb.Service/AppService.cs b/AgileConfig.Server.Mongodb.Service/AppService.cs new file mode 100644 index 00000000..f5a8edea --- /dev/null +++ b/AgileConfig.Server.Mongodb.Service/AppService.cs @@ -0,0 +1,173 @@ +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.IService; +using MongoDB.Driver; +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.Mongodb.Service; + +public class AppService( + IRepository repository, + IRepository appInheritancedRepository, + IRepository configRepository, + IRepository configPublishedRepository, + IRepository userAppAuthRepository, + IRepository userRepository):IAppService +{ + public void Dispose() + { + GC.SuppressFinalize(this); + } + + public Task GetAsync(string id) + { + return repository.FindAsync(id); + } + + public async Task AddAsync(App app) + { + await repository.InsertAsync(app); + return true; + } + + public async Task AddAsync(App app, List? appInheritanceds) + { + await repository.InsertAsync(app); + if (appInheritanceds != null) + { + await appInheritancedRepository.InsertAsync(appInheritanceds); + } + + return true; + } + + public async Task DeleteAsync(App app) + { + var app2 = await repository.FindAsync(app.Id); + if (app2 != null) + { + await repository.DeleteAsync(app2.Id); + //怕有的同学误删app导致要恢复,所以保留配置项吧。 + var update = Builders.Update.Set(x => x.Status, ConfigStatus.Deleted); + await configRepository.UpdateAsync(x => x.AppId == app2.Id, update); + //删除发布的配置项 + var publishedConfigUpdate = Builders.Update.Set(x => x.Status, ConfigStatus.Deleted); + await configPublishedRepository.UpdateAsync(x => x.AppId == app2.Id && x.Status == ConfigStatus.Enabled, + publishedConfigUpdate); + } + + return true; + } + + public async Task DeleteAsync(string appId) + { + var result = await repository.DeleteAsync(appId); + return result.DeletedCount > 0; + } + + public async Task UpdateAsync(App app, List? appInheritanceds) + { + await repository.UpdateAsync(app); + await appInheritancedRepository.DeleteAsync(x => x.AppId == app.Id); + if (appInheritanceds != null) + { + await appInheritancedRepository.InsertAsync(appInheritanceds); + } + + return true; + } + + public async Task UpdateAsync(App app) + { + var result = await repository.UpdateAsync(app); + return result.ModifiedCount > 0; + } + + public Task> GetAllAppsAsync() + { + return repository.SearchFor(x => true).ToListAsync(); + } + + public Task> GetAllInheritancedAppsAsync() + { + return repository.SearchFor(x => x.Type == AppType.Inheritance).ToListAsync(); + } + + public Task CountEnabledAppsAsync() + { + return repository.SearchFor(x => x.Enabled == true).CountAsync(); + } + + public async Task> GetInheritancedAppsAsync(string appId) + { + var appInheritanceds =await appInheritancedRepository.SearchFor(x => x.AppId == appId) + .OrderBy(x => x.Sort) + .ToListAsync(); + + var apps = new List(); + + foreach (var item in appInheritanceds) + { + var app = await GetAsync(item.InheritancedAppId); + if (app is { Enabled: true }) + { + apps.Add(app); + } + } + + return apps; + } + + public async Task> GetInheritancedFromAppsAsync(string appId) + { + var appInheritanceds = await appInheritancedRepository.SearchFor(a => a.InheritancedAppId == appId).ToListAsync(); + appInheritanceds = appInheritanceds.OrderBy(a => a.Sort).ToList(); + + var apps = new List(); + + foreach (var item in appInheritanceds) + { + var app = await GetAsync(item.AppId); + if (app is { Enabled: true }) + { + apps.Add(app); + } + } + + return apps; + } + + public async Task SaveUserAppAuth(string appId, List? userIds, string permission) + { + var userAppAuthList = new List(); + userIds ??= new List(); + foreach (var userId in userIds) + { + userAppAuthList.Add(new UserAppAuth + { + Id = Guid.NewGuid().ToString("N"), + AppId = appId, + UserId = userId, + Permission = permission + }); + } + await userAppAuthRepository.DeleteAsync(x => x.AppId == appId && x.Permission == permission); + await userAppAuthRepository.InsertAsync(userAppAuthList); + + return true; + } + + public async Task> GetUserAppAuth(string appId, string permission) + { + var auths = await userAppAuthRepository.SearchFor(x => x.AppId == appId && x.Permission == permission).ToListAsync(); + + var userIds = auths.Select(x => x.UserId).Distinct().ToList(); + return await userRepository.SearchFor(x => userIds.Contains(x.Id)).ToListAsync(); + } + + public List GetAppGroups() + { + var groups = repository.SearchFor(x => true).GroupBy(x => x.Group).Select(x => x.Key); + return groups.Where(x => !string.IsNullOrEmpty(x)).ToList(); + } +} \ No newline at end of file diff --git a/AgileConfig.Server.Mongodb.Service/ConfigService.cs b/AgileConfig.Server.Mongodb.Service/ConfigService.cs new file mode 100644 index 00000000..5b0d16bc --- /dev/null +++ b/AgileConfig.Server.Mongodb.Service/ConfigService.cs @@ -0,0 +1,996 @@ +using System.Text; +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.IService; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Configuration; +using MongoDB.Driver; +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.Mongodb.Service; + +public class ConfigService( + IConfiguration configuration, + IMemoryCache memoryCache, + IAppService appService, + ISettingService settingService, + IUserService userService) + : IConfigService +{ + public async Task IfEnvEmptySetDefaultAsync(string env) + { + if (!string.IsNullOrEmpty(env)) + { + return env; + } + + var envList = await settingService.GetEnvironmentList(); + if (envList == null || envList.Length == 0) + { + return ""; + } + + return envList[0]; + } + + + private IRepository GetRepository(string env) where T : new() + { + if (string.IsNullOrEmpty(env)) + { + //如果没有环境,使用默认连接 + return new Repository(configuration["db:conn"]); + } + + //是否配置的环境的连接 + var envDbProvider = configuration[$"db:env:{env}:provider"]; + if (string.IsNullOrEmpty(envDbProvider) || + string.Equals(envDbProvider, "mongodb", StringComparison.OrdinalIgnoreCase)) + { + //如果没有配置对应环境的连接,使用默认连接 + return new Repository(configuration["db:conn"]); + } + + Console.WriteLine("create env:{env} mongodb repository"); + return new Repository(configuration[$"db:env:{env}:conn"]); + } + + public async Task AddAsync(Config config, string env) + { + config.Value ??= ""; + await GetRepository(env).InsertAsync(config); + return true; + } + + public async Task UpdateAsync(Config config, string env) + { + var result = await GetRepository(env).UpdateAsync(config); + return result.ModifiedCount > 0; + } + + public async Task UpdateAsync(List configs, string env) + { + foreach (var item in configs) + { + await GetRepository(env).UpdateAsync(item); + } + + return true; + } + + public async Task CancelEdit(List ids, string env) + { + foreach (var configId in ids) + { + var config = await GetRepository(env).SearchFor(c => c.Id == configId).FirstOrDefaultAsync(); + if (config == null) + { + throw new Exception("Can not find config by id " + configId); + } + + if (config.EditStatus == EditStatus.Commit) + { + continue; + } + + if (config.EditStatus == EditStatus.Add) + { + await GetRepository(env).DeleteAsync(x => x.Id == configId); + } + + if (config.EditStatus is EditStatus.Deleted or EditStatus.Edit) + { + config.OnlineStatus = OnlineStatus.Online; + config.EditStatus = EditStatus.Commit; + config.UpdateTime = DateTime.Now; + + var publishedConfig = await GetPublishedConfigAsync(configId, env); + if (publishedConfig == null) + { + // + throw new Exception("Can not find published config by id " + configId); + } + + //reset value + config.Value = publishedConfig.Value; + config.OnlineStatus = OnlineStatus.Online; + + await GetRepository(env).UpdateAsync(config); + } + } + + return true; + } + + public async Task DeleteAsync(Config config, string env) + { + var result = await GetRepository(env).DeleteAsync(x => x.Id == config.Id); + + return result.DeletedCount > 0; + } + + public async Task DeleteAsync(string configId, string env) + { + var result = await GetRepository(env).DeleteAsync(configId); + + return result.DeletedCount > 0; + } + + public async Task GetAsync(string id, string env) + { + var config = await GetRepository(env).FindAsync(id); + return config; + } + + public Task> GetAllConfigsAsync(string env) + { + return GetRepository(env).SearchFor(c => c.Status == ConfigStatus.Enabled && c.Env == env) + .ToListAsync(); + } + + public async Task GetByAppIdKeyEnv(string appId, string group, string key, string env) + { + var q = GetRepository(env).SearchFor(c => + c.AppId == appId && + c.Key == key && + c.Env == env && + c.Status == ConfigStatus.Enabled + ); + if (string.IsNullOrEmpty(group)) + { + q = q.Where(c => c.Group == "" || c.Group == null); + } + else + { + q = q.Where(c => c.Group == group); + } + + return await q.FirstOrDefaultAsync(); + } + + public Task> GetByAppIdAsync(string appId, string env) + { + return GetRepository(env).SearchFor(c => + c.AppId == appId && c.Status == ConfigStatus.Enabled && c.Env == env + ).ToListAsync(); + } + + public Task> Search(string appId, string group, string key, string env) + { + var q = GetRepository(env).SearchFor(c => c.Status == ConfigStatus.Enabled && c.Env == env); + if (!string.IsNullOrEmpty(appId)) + { + q = q.Where(c => c.AppId == appId); + } + + if (!string.IsNullOrEmpty(group)) + { + q = q.Where(c => c.Group.Contains(group)); + } + + if (!string.IsNullOrEmpty(key)) + { + q = q.Where(c => c.Key.Contains(key)); + } + + return q.ToListAsync(); + } + + public async Task CountEnabledConfigsAsync() + { + int count = 0; + var envs = await settingService.GetEnvironmentList(); + foreach (var e in envs) + { + count += await CountEnabledConfigsAsync(e); + } + + return count; + } + + public async Task CountEnabledConfigsAsync(string env) + { + //这里计算所有的配置 + var q = await GetRepository(env).SearchFor(c => c.Status == ConfigStatus.Enabled && c.Env == env) + .CountAsync(); + + return (int)q; + } + + public string GenerateKey(Config config) + { + if (string.IsNullOrEmpty(config.Group)) + { + return config.Key; + } + + return $"{config.Group}:{config.Key}"; + } + + public string GenerateKey(ConfigPublished config) + { + if (string.IsNullOrEmpty(config.Group)) + { + return config.Key; + } + + return $"{config.Group}:{config.Key}"; + } + + /// + /// 获取当前app的配置集合的md5版本 + /// + /// + /// + public async Task AppPublishedConfigsMd5(string appId, string env) + { + var configs = await GetRepository(env).SearchFor(c => + c.AppId == appId && c.Status == ConfigStatus.Enabled + && c.Env == env + ).ToListAsync(); + + var keyStr = string.Join('&', + configs.Select(c => GenerateKey(c)).ToArray().OrderBy(k => k, StringComparer.Ordinal)); + var valStr = string.Join('&', configs.Select(c => c.Value).ToArray().OrderBy(v => v, StringComparer.Ordinal)); + var txt = $"{keyStr}&{valStr}"; + + return Encrypt.Md5(txt); + } + + /// + /// 获取当前app的配置集合的md5版本,1分钟缓存 + /// + /// + /// + public async Task AppPublishedConfigsMd5Cache(string appId, string env) + { + var cacheKey = AppPublishedConfigsMd5CacheKey(appId, env); + if (memoryCache != null && memoryCache.TryGetValue(cacheKey, out string md5)) + { + return md5; + } + + md5 = await AppPublishedConfigsMd5(appId, env); + + var cacheOp = new MemoryCacheEntryOptions() + .SetAbsoluteExpiration(TimeSpan.FromSeconds(60)); + memoryCache?.Set(cacheKey, md5, cacheOp); + + return md5; + } + + private string AppPublishedConfigsMd5CacheKey(string appId, string env) + { + return $"ConfigService_AppPublishedConfigsMd5Cache_{appId}_{env}"; + } + + private string AppPublishedConfigsMd5CacheKeyWithInheritanced(string appId, string env) + { + return $"ConfigService_AppPublishedConfigsMd5CacheWithInheritanced_{appId}_{env}"; + } + + private void ClearAppPublishedConfigsMd5Cache(string appId, string env) + { + var cacheKey = AppPublishedConfigsMd5CacheKey(appId, env); + memoryCache?.Remove(cacheKey); + } + + private void ClearAppPublishedConfigsMd5CacheWithInheritanced(string appId, string env) + { + var cacheKey = AppPublishedConfigsMd5CacheKeyWithInheritanced(appId, env); + memoryCache?.Remove(cacheKey); + } + + public async Task AddRangeAsync(List configs, string env) + { + configs.ForEach(x => { x.Value ??= ""; }); + + + await GetRepository(env).InsertAsync(configs); + ClearAppPublishedConfigsMd5Cache(configs.First().AppId, env); + ClearAppPublishedConfigsMd5CacheWithInheritanced(configs.First().AppId, env); + return true; + } + + /// + /// 获取app的配置项继承的app配置合并进来 + /// + /// + /// + public async Task> GetPublishedConfigsByAppIdWithInheritanced(string appId, string env) + { + var configs = await GetPublishedConfigsByAppIdWithInheritanced_Dictionary(appId, env); + + return configs.Values.ToList(); + } + + /// + /// 获取app的配置项继承的app配置合并进来转换为字典 + /// + /// + /// + public async Task> GetPublishedConfigsByAppIdWithInheritanced_Dictionary( + string appId, string env) + { + var apps = new List(); + var inheritanceApps = await appService.GetInheritancedAppsAsync(appId); + for (int i = 0; i < inheritanceApps.Count; i++) + { + if (inheritanceApps[i].Enabled) + { + apps.Add(inheritanceApps[i].Id); //后继承的排在后面 + } + } + + apps.Add(appId); //本应用放在最后 + + var configs = new Dictionary(); + //读取所有继承的配置跟本app的配置 + for (int i = 0; i < apps.Count; i++) + { + var id = apps[i]; + var publishConfigs = await GetPublishedConfigsAsync(id, env); + for (int j = 0; j < publishConfigs.Count; j++) + { + var config = publishConfigs[j].Convert(); + var key = GenerateKey(config); + if (configs.ContainsKey(key)) + { + //后面的覆盖前面的 + configs[key] = config; + } + else + { + configs.Add(key, config); + } + } + } + + return configs; + } + + public async Task AppPublishedConfigsMd5WithInheritanced(string appId, string env) + { + var configs = await GetPublishedConfigsByAppIdWithInheritanced(appId, env); + + var keyStr = string.Join('&', + configs.Select(c => GenerateKey(c)).ToArray().OrderBy(k => k, StringComparer.Ordinal)); + var valStr = string.Join('&', configs.Select(c => c.Value).ToArray().OrderBy(v => v, StringComparer.Ordinal)); + var txt = $"{keyStr}&{valStr}"; + + return Encrypt.Md5(txt); + } + + /// + /// 获取当前app的配置集合的md5版本,1分钟缓存 集合了继承app的配置 + /// + /// + /// + public async Task AppPublishedConfigsMd5CacheWithInheritanced(string appId, string env) + { + var cacheKey = AppPublishedConfigsMd5CacheKeyWithInheritanced(appId, env); + if (memoryCache != null && memoryCache.TryGetValue(cacheKey, out string md5)) + { + return md5; + } + + md5 = await AppPublishedConfigsMd5WithInheritanced(appId, env); + + var cacheOp = new MemoryCacheEntryOptions() + .SetAbsoluteExpiration(TimeSpan.FromSeconds(60)); + memoryCache?.Set(cacheKey, md5, cacheOp); + + return md5; + } + + public void Dispose() + { + GC.SuppressFinalize(this); + } + + private static readonly object Lockobj = new object(); + + /// + /// 发布当前待发布的配置项 + /// + /// 应用id + /// 待发布的id列表 + /// 发布日志 + /// 操作员 + /// + public (bool result, string publishTimelineId) Publish(string appId, string[] ids, string log, string operatorr, + string env) + { + lock (Lockobj) + { + var waitPublishConfigs = GetRepository(env).SearchFor(x => + x.AppId == appId && + x.Env == env && + x.Status == ConfigStatus.Enabled && + x.EditStatus != EditStatus.Commit).ToList(); + if (ids != null && ids.Any()) + { + //如果ids传值了,过滤一下 + waitPublishConfigs = waitPublishConfigs.Where(x => ids.Contains(x.Id)).ToList(); + } + + //这里默认admin console 实例只部署一个,如果部署多个同步操作,高并发的时候这个version会有问题 + var versionMax = GetRepository(env).SearchFor(x => x.AppId == appId).Max(x => x.Version); + + var user = userService.GetUser(operatorr); + + var publishTimelineNode = new PublishTimeline(); + publishTimelineNode.AppId = appId; + publishTimelineNode.Id = Guid.NewGuid().ToString("N"); + publishTimelineNode.PublishTime = DateTime.Now; + publishTimelineNode.PublishUserId = user.Id; + publishTimelineNode.PublishUserName = user.UserName; + publishTimelineNode.Version = versionMax + 1; + publishTimelineNode.Log = log; + publishTimelineNode.Env = env; + + var publishDetails = new List(); + waitPublishConfigs.ForEach(x => + { + publishDetails.Add(new PublishDetail() + { + AppId = appId, + ConfigId = x.Id, + Description = x.Description, + EditStatus = x.EditStatus, + Group = x.Group, + Id = Guid.NewGuid().ToString("N"), + Key = x.Key, + Value = x.Value, + PublishTimelineId = publishTimelineNode.Id, + Version = publishTimelineNode.Version, + Env = env + }); + + if (x.EditStatus == EditStatus.Deleted) + { + x.OnlineStatus = OnlineStatus.WaitPublish; + x.Status = ConfigStatus.Deleted; + } + else + { + x.OnlineStatus = OnlineStatus.Online; + x.Status = ConfigStatus.Enabled; + } + + x.EditStatus = EditStatus.Commit; + x.OnlineStatus = OnlineStatus.Online; + }); + + //当前发布的配置 + var publishedConfigs = GetRepository(env) + .SearchFor(x => x.Status == ConfigStatus.Enabled && x.AppId == appId && x.Env == env).ToList(); + //复制一份新版本,最后插入发布表 + var publishedConfigsCopy = new List(); + publishedConfigs.ForEach(x => + { + publishedConfigsCopy.Add(new ConfigPublished() + { + AppId = x.AppId, + ConfigId = x.ConfigId, + Group = x.Group, + Id = Guid.NewGuid().ToString("N"), + Key = x.Key, + PublishTimelineId = publishTimelineNode.Id, + PublishTime = publishTimelineNode.PublishTime, + Status = ConfigStatus.Enabled, + Version = publishTimelineNode.Version, + Value = x.Value, + Env = x.Env + }); + x.Status = ConfigStatus.Deleted; + }); + + publishDetails.ForEach(x => + { + if (x.EditStatus == EditStatus.Add) + { + publishedConfigsCopy.Add(new ConfigPublished() + { + AppId = x.AppId, + ConfigId = x.ConfigId, + Group = x.Group, + Id = Guid.NewGuid().ToString("N"), + Key = x.Key, + PublishTimelineId = publishTimelineNode.Id, + PublishTime = publishTimelineNode.PublishTime, + Status = ConfigStatus.Enabled, + Value = x.Value, + Version = publishTimelineNode.Version, + Env = env + }); + } + + if (x.EditStatus == EditStatus.Edit) + { + var oldEntity = publishedConfigsCopy.FirstOrDefault(c => c.ConfigId == x.ConfigId); + if (oldEntity == null) + { + //do nothing + } + else + { + //edit + oldEntity.Version = publishTimelineNode.Version; + oldEntity.Group = x.Group; + oldEntity.Key = x.Key; + oldEntity.Value = x.Value; + oldEntity.PublishTime = publishTimelineNode.PublishTime; + } + } + + if (x.EditStatus == EditStatus.Deleted) + { + var oldEntity = publishedConfigsCopy.FirstOrDefault(c => c.ConfigId == x.ConfigId); + if (oldEntity == null) + { + //do nothing + } + else + { + //remove + publishedConfigsCopy.Remove(oldEntity); + } + } + }); + + GetRepository(env).Update(waitPublishConfigs); + GetRepository(env).Insert(publishTimelineNode); + GetRepository(env).Insert(publishDetails); + GetRepository(env).Update(publishedConfigs); + GetRepository(env).Insert(publishedConfigsCopy); + + + ClearAppPublishedConfigsMd5Cache(appId, env); + ClearAppPublishedConfigsMd5CacheWithInheritanced(appId, env); + + return (true, publishTimelineNode.Id); + } + } + + public async Task IsPublishedAsync(string configId, string env) + { + var any = await GetRepository(env).SearchFor( + x => x.ConfigId == configId + && x.Env == env + && x.Status == ConfigStatus.Enabled).AnyAsync(); + + return any; + } + + public async Task> GetPublishDetailByPublishTimelineIdAsync(string publishTimelineId, + string env) + { + var list = await GetRepository(env) + .SearchFor(x => x.PublishTimelineId == publishTimelineId && x.Env == env).ToListAsync(); + + return list; + } + + public async Task GetPublishTimeLineNodeAsync(string publishTimelineId, string env) + { + var one = await GetRepository(env).SearchFor(x => x.Id == publishTimelineId && x.Env == env) + .FirstAsync(); + + return one; + } + + public async Task> GetPublishTimelineHistoryAsync(string appId, string env) + { + var list = await GetRepository(env).SearchFor(x => x.AppId == appId && x.Env == env) + .ToListAsync(); + + return list; + } + + public async Task> GetPublishDetailListAsync(string appId, string env) + { + var list = await GetRepository(env).SearchFor(x => x.AppId == appId && x.Env == env) + .ToListAsync(); + + return list; + } + + public async Task> GetConfigPublishedHistory(string configId, string env) + { + var list = await GetRepository(env).SearchFor(x => x.ConfigId == configId && x.Env == env) + .ToListAsync(); + + return list; + } + + public async Task> GetPublishedConfigsAsync(string appId, string env) + { + var list = await GetRepository(env) + .SearchFor(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env).ToListAsync(); + + return list; + } + + public async Task GetPublishedConfigAsync(string configId, string env) + { + var one = await GetRepository(env) + .SearchFor(x => x.ConfigId == configId && x.Status == ConfigStatus.Enabled && x.Env == env) + .FirstOrDefaultAsync(); + return one; + } + + public async Task RollbackAsync(string publishTimelineId, string env) + { + var publishNode = await GetRepository(env) + .SearchFor(x => x.Id == publishTimelineId && x.Env == env) + .FirstAsync(); + var version = publishNode.Version; + var appId = publishNode.AppId; + + var latest = await GetRepository(env).SearchFor(x => x.AppId == appId && x.Env == env) + .OrderByDescending(x => x.Version).FirstAsync(); + + if (latest.Id == publishTimelineId) + { + //当前版本直接返回true + return true; + } + + var publishedConfigs = await GetRepository(env) + .SearchFor(x => x.AppId == appId && x.Version == version && x.Env == env).ToListAsync(); + var currentConfigs = await GetRepository(env) + .SearchFor(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env).ToListAsync(); + + //把当前的全部软删除 + foreach (var item in currentConfigs) + { + item.Status = ConfigStatus.Deleted; + } + + await GetRepository(env).UpdateAsync(currentConfigs); + //根据id把所有发布项目设置为启用 + var now = DateTime.Now; + foreach (var item in publishedConfigs) + { + var config = await GetRepository(env).SearchFor(x => x.AppId == appId && x.Id == item.ConfigId) + .FirstAsync(); + config.Status = ConfigStatus.Enabled; + config.Value = item.Value; + config.UpdateTime = now; + config.EditStatus = EditStatus.Commit; + config.OnlineStatus = OnlineStatus.Online; + + await GetRepository(env).UpdateAsync(config); + } + + //删除version之后的版本 + await GetRepository(env) + .DeleteAsync(x => x.AppId == appId && x.Env == env && x.Version > version); + //设置为发布状态 + foreach (var item in publishedConfigs) + { + item.Status = ConfigStatus.Enabled; + await GetRepository(env).UpdateAsync(item); + } + + //删除发布时间轴version之后的版本 + await GetRepository(env) + .DeleteAsync(x => x.AppId == appId && x.Env == env && x.Version > version); + await GetRepository(env) + .DeleteAsync(x => x.AppId == appId && x.Env == env && x.Version > version); + + ClearAppPublishedConfigsMd5Cache(appId, env); + ClearAppPublishedConfigsMd5CacheWithInheritanced(appId, env); + + return true; + } + + public async Task EnvSync(string appId, string currentEnv, List toEnvs) + { + var currentEnvConfigs = await this.GetByAppIdAsync(appId, currentEnv); + + foreach (var env in toEnvs) + { + var envConfigs = await this.GetByAppIdAsync(appId, env); + var addRanges = new List(); + var updateRanges = new List(); + foreach (var currentEnvConfig in currentEnvConfigs) + { + var envConfig = envConfigs.FirstOrDefault(x => GenerateKey(x) == GenerateKey(currentEnvConfig)); + if (envConfig == null) + { + //没有相同的配置,则添加 + currentEnvConfig.Id = Guid.NewGuid().ToString("N"); + currentEnvConfig.Env = env; + currentEnvConfig.CreateTime = DateTime.Now; + currentEnvConfig.UpdateTime = DateTime.Now; + currentEnvConfig.Status = ConfigStatus.Enabled; + currentEnvConfig.EditStatus = EditStatus.Add; + currentEnvConfig.OnlineStatus = OnlineStatus.WaitPublish; //全部设置为待发布状态 + addRanges.Add(currentEnvConfig); + } + else + { + // 如果有了相同的键,如果值不同,则更新 + if (envConfig.Value != currentEnvConfig.Value) + { + envConfig.UpdateTime = DateTime.Now; + envConfig.Value = currentEnvConfig.Value; + if (envConfig.EditStatus == EditStatus.Commit) + { + envConfig.EditStatus = EditStatus.Edit; + } + + envConfig.OnlineStatus = OnlineStatus.WaitPublish; + envConfig.Description = currentEnvConfig.Description; + updateRanges.Add(envConfig); + } + } + } + + if (addRanges.Count > 0) + { + await this.AddRangeAsync(addRanges, env); + } + + if (updateRanges.Count > 0) + { + await this.UpdateAsync(updateRanges, env); + } + } + + return true; + } + + /// + /// 获取配置项转换成键值对列表形式 + /// + /// + /// + /// + public async Task>> GetKvListAsync(string appId, string env) + { + var configs = await GetByAppIdAsync(appId, env); + var kvList = new List>(); + foreach (var config in configs) + { + kvList.Add(new KeyValuePair(GenerateKey(config), config.Value)); + } + + return kvList; + } + + private async Task SaveFromDictAsync(IDictionary dict, string appId, string env, bool isPatch) + { + var currentConfigs = await GetRepository(env) + .SearchFor(x => x.AppId == appId && x.Env == env && x.Status == ConfigStatus.Enabled).ToListAsync(); + var addConfigs = new List(); + var updateConfigs = new List(); + var deleteConfigs = new List(); + + var now = DateTime.Now; + + foreach (var kv in dict) + { + var key = kv.Key; + var value = kv.Value; + var config = currentConfigs.FirstOrDefault(x => GenerateKey(x) == key); + if (config == null) + { + var gk = SplitJsonKey(key); + addConfigs.Add(new Config + { + Id = Guid.NewGuid().ToString("N"), + AppId = appId, + Env = env, + Key = gk.Item2, + Group = gk.Item1, + Value = value, + CreateTime = now, + Status = ConfigStatus.Enabled, + EditStatus = EditStatus.Add, + OnlineStatus = OnlineStatus.WaitPublish + }); + } + else if (config.Value != kv.Value) + { + config.Value = value; + config.UpdateTime = now; + if (config.OnlineStatus == OnlineStatus.Online) + { + config.EditStatus = EditStatus.Edit; + config.OnlineStatus = OnlineStatus.WaitPublish; + } + else + { + if (config.EditStatus == EditStatus.Add) + { + //do nothing + } + + if (config.EditStatus == EditStatus.Edit) + { + //do nothing + } + + if (config.EditStatus == EditStatus.Deleted) + { + //上一次是删除状态,现在恢复为编辑状态 + config.EditStatus = EditStatus.Edit; + } + } + + updateConfigs.Add(config); + } + } + + if (!isPatch) //补丁模式不删除现有配置,只有全量模式才删除 + { + var keys = dict.Keys.ToList(); + foreach (var item in currentConfigs) + { + var key = GenerateKey(item); + if (!keys.Contains(key)) + { + item.EditStatus = EditStatus.Deleted; + item.OnlineStatus = OnlineStatus.WaitPublish; + deleteConfigs.Add(item); + } + } + } + + if (addConfigs.Any()) + { + await GetRepository(env).InsertAsync(addConfigs); + } + + if (updateConfigs.Any()) + { + await GetRepository(env).UpdateAsync(updateConfigs); + } + + if (deleteConfigs.Any()) + { + await GetRepository(env).UpdateAsync(deleteConfigs); + } + + return true; + } + + /// + /// 保存json字符串为配置项 + /// + /// + /// + /// + /// + /// + /// + public async Task SaveJsonAsync(string json, string appId, string env, bool isPatch) + { + if (string.IsNullOrEmpty(json)) + { + throw new ArgumentNullException("json"); + } + + byte[] byteArray = Encoding.UTF8.GetBytes(json); + using var stream = new MemoryStream(byteArray); + var dict = JsonConfigurationFileParser.Parse(stream); + + return await SaveFromDictAsync(dict, appId, env, isPatch); + } + + public (bool, string) ValidateKvString(string kvStr) + { + StringReader sr = new StringReader(kvStr); + int row = 0; + var dict = new Dictionary(); + while (true) + { + var line = sr.ReadLine(); + if (line == null) + { + break; + } + + row++; + //必须要有=号 + if (line.IndexOf('=') < 0) + { + return (false, $"第 {row} 行缺少等号。"); + } + + var index = line.IndexOf('='); + var key = line.Substring(0, index); + if (dict.ContainsKey(key)) + { + return (false, $"键 {key} 重复。"); + } + + dict.Add(key, ""); + } + + return (true, ""); + } + + public void ClearCache() + { + if (memoryCache != null && memoryCache is MemoryCache memCache) + { + memCache.Compact(1.0); + } + } + + public async Task SaveKvListAsync(string kvString, string appId, string env, bool isPatch) + { + if (kvString == null) + { + throw new ArgumentNullException(nameof(kvString)); + } + + StringReader sr = new StringReader(kvString); + var dict = new Dictionary(); + while (true) + { + var line = sr.ReadLine(); + if (line == null) + { + break; + } + + var index = line.IndexOf('='); + if (index < 0) + { + continue; + } + + var key = line.Substring(0, index); + var val = line.Substring(index + 1, line.Length - index - 1); + + dict.Add(key, val); + } + + return await SaveFromDictAsync(dict, appId, env, isPatch); + } + + private (string, string) SplitJsonKey(string key) + { + if (string.IsNullOrEmpty(key)) + { + throw new ArgumentNullException(nameof(key)); + } + + var index = key.LastIndexOf(':'); + if (index >= 0) + { + var group = key.Substring(0, index); + var newkey = key.Substring(index + 1, key.Length - index - 1); + + return (group, newkey); + } + + return ("", key); + } +} \ No newline at end of file diff --git a/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs b/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs new file mode 100644 index 00000000..8cc3e2d2 --- /dev/null +++ b/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs @@ -0,0 +1,12 @@ +using AgileConfig.Server.Data.Mongodb; +using Microsoft.Extensions.DependencyInjection; + +namespace AgileConfig.Server.Mongodb.Service; + +public static class MongodbServiceExtensions +{ + public static void AddBusinessServices(this IServiceCollection services) + { + services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); + } +} \ No newline at end of file diff --git a/AgileConfig.Server.Mongodb.Service/SettingService.cs b/AgileConfig.Server.Mongodb.Service/SettingService.cs new file mode 100644 index 00000000..b60adf9b --- /dev/null +++ b/AgileConfig.Server.Mongodb.Service/SettingService.cs @@ -0,0 +1,181 @@ +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.IService; +using MongoDB.Driver; +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.Mongodb.Service; + +public class SettingService( + IRepository repository, + IRepository userRepository, + IRepository userRoleRepository) : ISettingService +{ + public const string SuperAdminId = "super_admin"; + public const string SuperAdminUserName = "admin"; + + public const string DefaultEnvironment = "DEV,TEST,STAGING,PROD"; + public const string DefaultEnvironmentKey = "environment"; + public const string DefaultJwtSecretKey = "jwtsecret"; + + public async Task AddAsync(Setting setting) + { + await repository.InsertAsync(setting); + return true; + } + + public async Task DeleteAsync(Setting setting) + { + var result = await repository.DeleteAsync(setting.Id); + return result.DeletedCount > 0; + } + + public async Task DeleteAsync(string settingId) + { + var result = await repository.DeleteAsync(settingId); + return result.DeletedCount > 0; + } + + public Task GetAsync(string id) + { + return repository.SearchFor(s => s.Id == id).FirstOrDefaultAsync(); + } + + public Task> GetAllSettingsAsync() + { + return repository.SearchFor(s => true).ToListAsync(); + } + + public async Task UpdateAsync(Setting setting) + { + var result = await repository.UpdateAsync(setting); + return result.ModifiedCount > 0; + } + + public async Task SetSuperAdminPassword(string password) + { + if (string.IsNullOrEmpty(password)) + { + throw new ArgumentNullException(nameof(password)); + } + + var newSalt = Guid.NewGuid().ToString("N"); + password = Encrypt.Md5((password + newSalt)); + + var su = new User(); + su.Id = SuperAdminId; + su.Password = password; + su.Salt = newSalt; + su.Status = UserStatus.Normal; + su.Team = ""; + su.CreateTime = DateTime.Now; + su.UserName = SuperAdminUserName; + await userRepository.InsertAsync(su); + + var ursa = new UserRole() + { + Id = Guid.NewGuid().ToString("N"), + Role = Role.SuperAdmin, + UserId = SuperAdminId + }; + + var ura = new UserRole() + { + Id = Guid.NewGuid().ToString("N"), + Role = Role.Admin, + UserId = SuperAdminId + }; + await userRoleRepository.InsertAsync(ursa, ura); + + return true; + } + + public async Task HasSuperAdmin() + { + var admin = await userRepository.SearchFor(x => x.Id == SuperAdminId).FirstOrDefaultAsync(); + + return admin != null; + } + + public async Task InitDefaultEnvironment() + { + var env = await repository.SearchFor(x => x.Id == DefaultEnvironmentKey).FirstOrDefaultAsync(); + if (env == null) + { + await repository.InsertAsync(new Setting + { + Id = DefaultEnvironmentKey, + Value = DefaultEnvironment, + CreateTime = DateTime.Now + }); + } + + return true; + } + + public void Dispose() + { + GC.SuppressFinalize(this); + } + + public async Task GetEnvironmentList() + { + var env = await repository.SearchFor(x => x.Id == DefaultEnvironmentKey).FirstAsync(); + + return env.Value.ToUpper().Split(','); + } + + /// + /// 如果 配置文件或者环境变量没配置 JwtSetting:SecurityKey 则生成一个存库 + /// + /// + public bool TryInitJwtSecret() + { + var jwtSecretFromConfig = Global.Config["JwtSetting:SecurityKey"]; + if (string.IsNullOrEmpty(jwtSecretFromConfig)) + { + var jwtSecretSetting = repository.Find(DefaultJwtSecretKey); + if (jwtSecretSetting == null) + { + try + { + repository.Insert(new Setting + { + Id = DefaultJwtSecretKey, + Value = GenreateJwtSecretKey(), + CreateTime = DateTime.Now + }); + return true; + } + catch (Exception e) + { + //处理异常,防止多个实例第一次启动的时候,并发生成key值,发生异常,导致服务起不来 + Console.WriteLine(e); + } + + return false; + } + } + + return true; + } + + public string? GetJwtTokenSecret() + { + var jwtSecretSetting = repository.Find(DefaultJwtSecretKey);; + return jwtSecretSetting?.Value; + } + + /// + /// 生成一个 jwt 加密的 key ,38位 + /// + /// + private string GenreateJwtSecretKey() + { + var guid1 = Guid.NewGuid().ToString("n"); + var guid2 = Guid.NewGuid().ToString("n"); + + return guid1.Substring(0, 19) + guid2.Substring(0, 19); + } +} \ No newline at end of file diff --git a/AgileConfig.Server.Mongodb.Service/UserService.cs b/AgileConfig.Server.Mongodb.Service/UserService.cs new file mode 100644 index 00000000..dc80d749 --- /dev/null +++ b/AgileConfig.Server.Mongodb.Service/UserService.cs @@ -0,0 +1,104 @@ +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.IService; +using MongoDB.Driver; +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.Mongodb.Service; + +public class UserService(IRepository repository, IRepository userRoleRepository) : IUserService +{ + public void Dispose() + { + GC.SuppressFinalize(this); + } + + public Task> GetAll() + { + return repository.SearchFor(x => true).ToListAsync(); + } + + public Task GetUserAsync(string userId) + { + return repository.FindAsync(userId); + } + + public User? GetUser(string userId) + { + return repository.Find(userId); + } + + public Task> GetUsersByNameAsync(string userName) + { + return repository.SearchFor(x => x.UserName == userName).ToListAsync(); + } + + public async Task> GetUserRolesAsync(string userId) + { + var userRoles = await userRoleRepository.SearchFor(x => x.UserId == userId).ToListAsync(); + return userRoles.Select(x => x.Role).ToList(); + } + + public async Task AddAsync(User user) + { + var old = repository.SearchFor(x => x.UserName == user.UserName && x.Status == UserStatus.Normal) + .FirstOrDefault(); + if (old != null) + return false; + + await repository.InsertAsync(user); + return true; + } + + public async Task DeleteAsync(User user) + { + var result = await repository.DeleteAsync(user.Id); + return result.DeletedCount > 0; + } + + public async Task UpdateAsync(User user) + { + var result = await repository.UpdateAsync(user); + return result.ModifiedCount > 0; + } + + public async Task UpdateUserRolesAsync(string userId, List roles) + { + await userRoleRepository.DeleteAsync(x => x.UserId == userId); + var userRoles = roles.Select(x => new UserRole + { + Id = Guid.NewGuid().ToString("N"), + UserId = userId, + Role = x + }) + .ToList(); + + await userRoleRepository.InsertAsync(userRoles); + return true; + } + + public async Task ValidateUserPassword(string userName, string password) + { + var user = await repository.SearchFor(x => x.Status == UserStatus.Normal && x.UserName == userName) + .FirstOrDefaultAsync(); + if (user == null) + return false; + + if (user.Password == Encrypt.Md5(password + user.Salt)) + { + return true; + } + + return false; + } + + public Task> GetUsersByRoleAsync(Role role) + { + return (from user in repository.MongodbQueryable + join userRole in userRoleRepository.MongodbQueryable + on user.Id equals userRole.UserId + where userRole.Role == role + select user).ToListAsync(); + } +} \ No newline at end of file diff --git a/AgileConfig.sln b/AgileConfig.sln index ce1e58a4..9c074d7d 100644 --- a/AgileConfig.sln +++ b/AgileConfig.sln @@ -38,6 +38,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.CommonTe EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.OIDC", "src\AgileConfig.Server.OIDC\AgileConfig.Server.OIDC.csproj", "{E49A2006-6D07-4434-AEC1-27E356A767AE}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Mongodb", "AgileConfig.Server.Data.Mongodb\AgileConfig.Server.Data.Mongodb.csproj", "{4803646E-8327-4F69-8BA5-2244CB58BBA2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Mongodb.Service", "AgileConfig.Server.Mongodb.Service\AgileConfig.Server.Mongodb.Service.csproj", "{375B1F54-11CA-415D-ADCC-3B14684AE1DB}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -88,6 +92,14 @@ Global {E49A2006-6D07-4434-AEC1-27E356A767AE}.Debug|Any CPU.Build.0 = Debug|Any CPU {E49A2006-6D07-4434-AEC1-27E356A767AE}.Release|Any CPU.ActiveCfg = Release|Any CPU {E49A2006-6D07-4434-AEC1-27E356A767AE}.Release|Any CPU.Build.0 = Release|Any CPU + {4803646E-8327-4F69-8BA5-2244CB58BBA2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4803646E-8327-4F69-8BA5-2244CB58BBA2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4803646E-8327-4F69-8BA5-2244CB58BBA2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4803646E-8327-4F69-8BA5-2244CB58BBA2}.Release|Any CPU.Build.0 = Release|Any CPU + {375B1F54-11CA-415D-ADCC-3B14684AE1DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {375B1F54-11CA-415D-ADCC-3B14684AE1DB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {375B1F54-11CA-415D-ADCC-3B14684AE1DB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {375B1F54-11CA-415D-ADCC-3B14684AE1DB}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -104,6 +116,8 @@ Global {8CE2DB53-3A35-4991-A419-0EC12B001F59} = {F277EC27-8C0E-4490-9645-F5F3244F9246} {70724B0E-7D81-412C-BDA7-747F4845E990} = {F277EC27-8C0E-4490-9645-F5F3244F9246} {E49A2006-6D07-4434-AEC1-27E356A767AE} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} + {4803646E-8327-4F69-8BA5-2244CB58BBA2} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} + {375B1F54-11CA-415D-ADCC-3B14684AE1DB} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {7F10DB58-5B6F-4EAC-994F-14E8046B306F} diff --git a/src/AgileConfig.Server.Apisite/Startup.cs b/src/AgileConfig.Server.Apisite/Startup.cs index 0afaf10a..745a11f0 100644 --- a/src/AgileConfig.Server.Apisite/Startup.cs +++ b/src/AgileConfig.Server.Apisite/Startup.cs @@ -82,8 +82,15 @@ public void ConfigureServices(IServiceCollection services) AddSwaggerService(services); } - services.AddFreeSqlDbContext(); - services.AddBusinessServices(); + if (string.Equals(Configuration["db:provider"], "mongodb", StringComparison.OrdinalIgnoreCase)) + { + + } + else + { + services.AddFreeSqlDbContext(); + services.AddBusinessServices(); + } services.AddHostedService(); services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = true); diff --git a/src/AgileConfig.Server.Apisite/appsettings.Development.json b/src/AgileConfig.Server.Apisite/appsettings.Development.json index e6613074..8855c93a 100644 --- a/src/AgileConfig.Server.Apisite/appsettings.Development.json +++ b/src/AgileConfig.Server.Apisite/appsettings.Development.json @@ -16,8 +16,8 @@ "cluster": false, // 集群模式:服务启动后自动加入节点列表,服务启动的时候会获取容器的ip,端口默认5000,适合 docker compose 环境使用 "preview_mode": true, "db": { - "provider": "sqlite", //sqlite,mysql,sqlserver,npgsql,oracle - "conn": "Data Source=agile_config.db", + "provider": "mongodb", //sqlite,mysql,sqlserver,npgsql,oracle,mongodb + "conn": "mongodb://localhost:27017,localhost:37017/AgileConfig", //"provider": "sqlserver", //"conn": "Encrypt=True;TrustServerCertificate=True;Persist Security Info = False; User ID =dev; Password =dev@123; Initial Catalog =agile_config; Server =192.168.18.82" //"provider": "npgsql", diff --git a/src/AgileConfig.Server.Apisite/appsettings.json b/src/AgileConfig.Server.Apisite/appsettings.json index f245b60f..9940e82b 100644 --- a/src/AgileConfig.Server.Apisite/appsettings.json +++ b/src/AgileConfig.Server.Apisite/appsettings.json @@ -16,10 +16,11 @@ "cluster": false, // 集群模式:服务启动后自动加入节点列表,服务启动的时候会获取容器的ip,端口默认5000,适合 docker compose 环境使用 "preview_mode": false, "db": { - "provider": "", //sqlite,mysql,sqlserver,npgsql,oracle + "provider": "", //sqlite,mysql,sqlserver,npgsql,oracle,mongodb "conn": "", //"conn": "Data Source=agile_config.db" //"conn": "Persist Security Info = False; User ID =dev; Password =dev@123; Initial Catalog =agile_config; Server =." + //"conn": "mongodb://user:password@localhost:27017,localhost:37017/database-name?authSource=admin" "env": { "TEST": { "provider": "", //sqlite,mysql,sqlserver,npgsql,oracle From 34929c6789cbf85be039bf3ee684dd30a863eed4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Wed, 13 Dec 2023 16:57:06 +0800 Subject: [PATCH 02/45] =?UTF-8?q?=E9=80=82=E9=85=8Dmongodb?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MongodbServiceExtensions.cs | 12 - AgileConfig.sln | 4 +- .../AgileConfig.Server.Apisite.csproj | 1 + .../ConfigureJwtBearerOptions.cs | 28 ++ src/AgileConfig.Server.Apisite/Startup.cs | 22 +- .../AgileConfig.Server.Data.Mongodb.csproj | 0 .../IRepository.cs | 0 .../MongodbAccess.cs | 0 .../Repository.cs | 0 .../AdmBasicAuthService.cs | 0 .../AgileConfig.Server.Mongodb.Service.csproj | 5 +- .../AppBasicAuthService.cs | 97 ++++ .../AppService.cs | 0 .../ConfigService.cs | 0 .../ConfigStatusUpdateRegister.cs | 128 +++++ .../EventRegisterService/EventRegister.cs | 19 + .../ServiceInfoStatusUpdateRegister.cs | 139 +++++ .../EventRegisterService/SysLogRegister.cs | 475 ++++++++++++++++++ .../JwtService.cs | 67 +++ .../MongodbServiceExtensions.cs | 49 ++ .../PermissionService.cs | 230 +++++++++ .../RegisterCenterService.cs | 153 ++++++ .../RemoteServerNodeProxy.cs | 272 ++++++++++ .../ServerNodeService.cs | 117 +++++ .../ServiceHealthCheckService.cs | 204 ++++++++ .../ServiceInfoService.cs | 145 ++++++ .../SettingService.cs | 0 .../SysLogService.cs | 84 ++++ .../UserService.cs | 0 29 files changed, 2222 insertions(+), 29 deletions(-) delete mode 100644 AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs create mode 100644 src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs rename {AgileConfig.Server.Data.Mongodb => src/AgileConfig.Server.Data.Mongodb}/AgileConfig.Server.Data.Mongodb.csproj (100%) rename {AgileConfig.Server.Data.Mongodb => src/AgileConfig.Server.Data.Mongodb}/IRepository.cs (100%) rename {AgileConfig.Server.Data.Mongodb => src/AgileConfig.Server.Data.Mongodb}/MongodbAccess.cs (100%) rename {AgileConfig.Server.Data.Mongodb => src/AgileConfig.Server.Data.Mongodb}/Repository.cs (100%) rename {AgileConfig.Server.Mongodb.Service => src/AgileConfig.Server.Mongodb.Service}/AdmBasicAuthService.cs (100%) rename {AgileConfig.Server.Mongodb.Service => src/AgileConfig.Server.Mongodb.Service}/AgileConfig.Server.Mongodb.Service.csproj (64%) create mode 100644 src/AgileConfig.Server.Mongodb.Service/AppBasicAuthService.cs rename {AgileConfig.Server.Mongodb.Service => src/AgileConfig.Server.Mongodb.Service}/AppService.cs (100%) rename {AgileConfig.Server.Mongodb.Service => src/AgileConfig.Server.Mongodb.Service}/ConfigService.cs (100%) create mode 100644 src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ConfigStatusUpdateRegister.cs create mode 100644 src/AgileConfig.Server.Mongodb.Service/EventRegisterService/EventRegister.cs create mode 100644 src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs create mode 100644 src/AgileConfig.Server.Mongodb.Service/EventRegisterService/SysLogRegister.cs create mode 100644 src/AgileConfig.Server.Mongodb.Service/JwtService.cs create mode 100644 src/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs create mode 100644 src/AgileConfig.Server.Mongodb.Service/PermissionService.cs create mode 100644 src/AgileConfig.Server.Mongodb.Service/RegisterCenterService.cs create mode 100644 src/AgileConfig.Server.Mongodb.Service/RemoteServerNodeProxy.cs create mode 100644 src/AgileConfig.Server.Mongodb.Service/ServerNodeService.cs create mode 100644 src/AgileConfig.Server.Mongodb.Service/ServiceHealthCheckService.cs create mode 100644 src/AgileConfig.Server.Mongodb.Service/ServiceInfoService.cs rename {AgileConfig.Server.Mongodb.Service => src/AgileConfig.Server.Mongodb.Service}/SettingService.cs (100%) create mode 100644 src/AgileConfig.Server.Mongodb.Service/SysLogService.cs rename {AgileConfig.Server.Mongodb.Service => src/AgileConfig.Server.Mongodb.Service}/UserService.cs (100%) diff --git a/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs b/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs deleted file mode 100644 index 8cc3e2d2..00000000 --- a/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs +++ /dev/null @@ -1,12 +0,0 @@ -using AgileConfig.Server.Data.Mongodb; -using Microsoft.Extensions.DependencyInjection; - -namespace AgileConfig.Server.Mongodb.Service; - -public static class MongodbServiceExtensions -{ - public static void AddBusinessServices(this IServiceCollection services) - { - services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); - } -} \ No newline at end of file diff --git a/AgileConfig.sln b/AgileConfig.sln index 9c074d7d..4a5c89f4 100644 --- a/AgileConfig.sln +++ b/AgileConfig.sln @@ -38,9 +38,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.CommonTe EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.OIDC", "src\AgileConfig.Server.OIDC\AgileConfig.Server.OIDC.csproj", "{E49A2006-6D07-4434-AEC1-27E356A767AE}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Mongodb", "AgileConfig.Server.Data.Mongodb\AgileConfig.Server.Data.Mongodb.csproj", "{4803646E-8327-4F69-8BA5-2244CB58BBA2}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Mongodb", "src\AgileConfig.Server.Data.Mongodb\AgileConfig.Server.Data.Mongodb.csproj", "{4803646E-8327-4F69-8BA5-2244CB58BBA2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Mongodb.Service", "AgileConfig.Server.Mongodb.Service\AgileConfig.Server.Mongodb.Service.csproj", "{375B1F54-11CA-415D-ADCC-3B14684AE1DB}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Mongodb.Service", "src\AgileConfig.Server.Mongodb.Service\AgileConfig.Server.Mongodb.Service.csproj", "{375B1F54-11CA-415D-ADCC-3B14684AE1DB}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj b/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj index 7a25e770..a6dd4940 100644 --- a/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj +++ b/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj @@ -38,6 +38,7 @@ + diff --git a/src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs b/src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs new file mode 100644 index 00000000..d28859b9 --- /dev/null +++ b/src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs @@ -0,0 +1,28 @@ +using System.Text; +using AgileConfig.Server.IService; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; + +namespace AgileConfig.Server.Apisite; + +public class ConfigureJwtBearerOptions( + IJwtService jwtService, + ISettingService settingService) : IConfigureNamedOptions +{ + public void Configure(JwtBearerOptions options) + { + settingService.TryInitJwtSecret(); + options.TokenValidationParameters = new TokenValidationParameters + { + ValidIssuer = jwtService.Issuer, + ValidAudience = jwtService.Audience, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtService.GetSecurityKey())), + }; + } + + public void Configure(string name, JwtBearerOptions options) + { + Configure(options); + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Apisite/Startup.cs b/src/AgileConfig.Server.Apisite/Startup.cs index 745a11f0..7c1c993f 100644 --- a/src/AgileConfig.Server.Apisite/Startup.cs +++ b/src/AgileConfig.Server.Apisite/Startup.cs @@ -8,6 +8,7 @@ using AgileConfig.Server.Common; using AgileConfig.Server.Common.RestClient; using AgileConfig.Server.Data.Freesql; +using AgileConfig.Server.Mongodb.Service; using AgileConfig.Server.OIDC; using AgileConfig.Server.Service; using Microsoft.AspNetCore.Authentication.JwtBearer; @@ -61,19 +62,9 @@ public void ConfigureServices(IServiceCollection services) { services.AddDefaultHttpClient(IsTrustSSL(Configuration)); services.AddRestClient(); - - var jwtService = new JwtService(); + services.AddMemoryCache(); - services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) - .AddJwtBearer(options => - { - options.TokenValidationParameters = new TokenValidationParameters - { - ValidIssuer = jwtService.Issuer, - ValidAudience = jwtService.Audience, - IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtService.GetSecurityKey())), - }; - }); + services.AddCors(); services.AddMvc().AddRazorRuntimeCompilation(); @@ -84,13 +75,18 @@ public void ConfigureServices(IServiceCollection services) if (string.Equals(Configuration["db:provider"], "mongodb", StringComparison.OrdinalIgnoreCase)) { - + services.AddBusinessForMongoServices(); } else { services.AddFreeSqlDbContext(); services.AddBusinessServices(); } + + services.ConfigureOptions(); + services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddJwtBearer(); + services.AddHostedService(); services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = true); diff --git a/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj b/src/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj similarity index 100% rename from AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj rename to src/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj diff --git a/AgileConfig.Server.Data.Mongodb/IRepository.cs b/src/AgileConfig.Server.Data.Mongodb/IRepository.cs similarity index 100% rename from AgileConfig.Server.Data.Mongodb/IRepository.cs rename to src/AgileConfig.Server.Data.Mongodb/IRepository.cs diff --git a/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs similarity index 100% rename from AgileConfig.Server.Data.Mongodb/MongodbAccess.cs rename to src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs diff --git a/AgileConfig.Server.Data.Mongodb/Repository.cs b/src/AgileConfig.Server.Data.Mongodb/Repository.cs similarity index 100% rename from AgileConfig.Server.Data.Mongodb/Repository.cs rename to src/AgileConfig.Server.Data.Mongodb/Repository.cs diff --git a/AgileConfig.Server.Mongodb.Service/AdmBasicAuthService.cs b/src/AgileConfig.Server.Mongodb.Service/AdmBasicAuthService.cs similarity index 100% rename from AgileConfig.Server.Mongodb.Service/AdmBasicAuthService.cs rename to src/AgileConfig.Server.Mongodb.Service/AdmBasicAuthService.cs diff --git a/AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj b/src/AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj similarity index 64% rename from AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj rename to src/AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj index 324f840d..cf79b219 100644 --- a/AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj +++ b/src/AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj @@ -8,12 +8,13 @@ + - - + + diff --git a/src/AgileConfig.Server.Mongodb.Service/AppBasicAuthService.cs b/src/AgileConfig.Server.Mongodb.Service/AppBasicAuthService.cs new file mode 100644 index 00000000..cd0c6ba8 --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/AppBasicAuthService.cs @@ -0,0 +1,97 @@ +using System.Text; +using AgileConfig.Server.IService; +using Microsoft.AspNetCore.Http; + +namespace AgileConfig.Server.Mongodb.Service; + +public class AppBasicAuthService(IAppService appService) : IAppBasicAuthService +{ + /// + /// 从request中解析出appid、secret + /// + /// + /// + public (string, string) GetAppIdSecret(HttpRequest httpRequest) + { + var authorization = httpRequest.Headers["Authorization"]; + if (string.IsNullOrEmpty(authorization)) + { + return ("", ""); + } + + var authStr = authorization.First(); + //去掉basic_ + if (!authStr.StartsWith("Basic ")) + { + return ("", ""); + ; + } + + authStr = authStr.Substring(6, authStr.Length - 6); + byte[] base64Decode = null; + try + { + base64Decode = Convert.FromBase64String(authStr); + } + catch + { + return ("", ""); + } + + var base64Str = Encoding.UTF8.GetString(base64Decode); + + if (string.IsNullOrEmpty(base64Str)) + { + return ("", ""); + } + + var appId = ""; + var sec = ""; + + + var baseAuthArr = base64Str.Split(':'); + + if (baseAuthArr.Length > 0) + { + appId = baseAuthArr[0]; + } + + if (baseAuthArr.Length > 1) + { + sec = baseAuthArr[1]; + } + + return (appId, sec); + } + + public (string, string) GetUserNamePassword(HttpRequest httpRequest) + { + throw new NotImplementedException(); + } + + public async Task ValidAsync(HttpRequest httpRequest) + { + var appIdSecret = GetAppIdSecret(httpRequest); + var appId = appIdSecret.Item1; + var sec = appIdSecret.Item2; + if (string.IsNullOrEmpty(appIdSecret.Item1)) + { + return false; + } + + var app = await appService.GetAsync(appId); + if (app == null) + { + return false; + } + + if (!app.Enabled) + { + return false; + } + + var txt = $"{app.Id}:{app.Secret}"; + + return txt == $"{appId}:{sec}"; + } +} \ No newline at end of file diff --git a/AgileConfig.Server.Mongodb.Service/AppService.cs b/src/AgileConfig.Server.Mongodb.Service/AppService.cs similarity index 100% rename from AgileConfig.Server.Mongodb.Service/AppService.cs rename to src/AgileConfig.Server.Mongodb.Service/AppService.cs diff --git a/AgileConfig.Server.Mongodb.Service/ConfigService.cs b/src/AgileConfig.Server.Mongodb.Service/ConfigService.cs similarity index 100% rename from AgileConfig.Server.Mongodb.Service/ConfigService.cs rename to src/AgileConfig.Server.Mongodb.Service/ConfigService.cs diff --git a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ConfigStatusUpdateRegister.cs b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ConfigStatusUpdateRegister.cs new file mode 100644 index 00000000..d9daebc8 --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ConfigStatusUpdateRegister.cs @@ -0,0 +1,128 @@ +using Agile.Config.Protocol; +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.IService; + +namespace AgileConfig.Server.Mongodb.Service.EventRegisterService; + +internal class ConfigStatusUpdateRegister : IEventRegister +{ + private readonly IRemoteServerNodeProxy _remoteServerNodeProxy; + private readonly IServerNodeService _serverNodeService; + private readonly IAppService _appService; + + public ConfigStatusUpdateRegister( + IRemoteServerNodeProxy remoteServerNodeProxy, + IServerNodeService serverNodeService, + IAppService appService) + { + _remoteServerNodeProxy = remoteServerNodeProxy; + _serverNodeService = serverNodeService; + _appService = appService; + } + + public void Register() + { + TinyEventBus.Instance.Register(EventKeys.PUBLISH_CONFIG_SUCCESS, (param) => + { + dynamic param_dy = param; + PublishTimeline timelineNode = param_dy.publishTimelineNode; + if (timelineNode != null) + { + Task.Run(async () => + { + var nodes = await _serverNodeService.GetAllNodesAsync(); + var noticeApps = await GetNeedNoticeInheritancedFromAppsAction(timelineNode.AppId); + noticeApps.Add(timelineNode.AppId, + new WebsocketAction { Action = ActionConst.Reload, Module = ActionModule.ConfigCenter }); + + foreach (var node in nodes) + { + if (node.Status == NodeStatus.Offline) + { + continue; + } + + //all server cache + await _remoteServerNodeProxy.ClearConfigServiceCache(node.Address); + } + + foreach (var node in nodes) + { + if (node.Status == NodeStatus.Offline) + { + continue; + } + + foreach (var item in noticeApps) + { + await _remoteServerNodeProxy.AppClientsDoActionAsync( + node.Address, + item.Key, + timelineNode.Env, + item.Value); + } + } + }); + } + }); + + TinyEventBus.Instance.Register(EventKeys.ROLLBACK_CONFIG_SUCCESS, (param) => + { + dynamic param_dy = param; + PublishTimeline timelineNode = param_dy.timelineNode; + if (timelineNode != null) + { + Task.Run(async () => + { + var nodes = await _serverNodeService.GetAllNodesAsync(); + var noticeApps = await GetNeedNoticeInheritancedFromAppsAction(timelineNode.AppId); + noticeApps.Add(timelineNode.AppId, + new WebsocketAction + { Action = ActionConst.Reload, Module = ActionModule.ConfigCenter }); + + foreach (var node in nodes) + { + if (node.Status == NodeStatus.Offline) + { + continue; + } + + foreach (var item in noticeApps) + { + await _remoteServerNodeProxy.AppClientsDoActionAsync(node.Address, item.Key, + timelineNode.Env, + item.Value); + } + } + }); + } + }); + } + + /// + /// 根据当前配置计算需要通知的应用 + /// + /// + private async Task> GetNeedNoticeInheritancedFromAppsAction(string appId) + { + Dictionary needNoticeAppsActions = new Dictionary + { + }; + + var currentApp = await _appService.GetAsync(appId); + if (currentApp.Type == AppType.Inheritance) + { + var inheritancedFromApps = await _appService.GetInheritancedFromAppsAsync(appId); + inheritancedFromApps.ForEach(x => + { + needNoticeAppsActions.Add(x.Id, new WebsocketAction + { + Action = ActionConst.Reload, Module = ActionModule.ConfigCenter + }); + }); + } + + return needNoticeAppsActions; + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/EventRegister.cs b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/EventRegister.cs new file mode 100644 index 00000000..c3d518e3 --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/EventRegister.cs @@ -0,0 +1,19 @@ +using AgileConfig.Server.Common.RestClient; +using AgileConfig.Server.IService; +using Microsoft.Extensions.Logging; + +namespace AgileConfig.Server.Mongodb.Service.EventRegisterService; + +public class EventRegister(EventRegisterResolver eventRegisterResolver) : IEventRegister +{ + private readonly IEventRegister? _configStatusUpdateRegister = eventRegisterResolver(nameof(ConfigStatusUpdateRegister)); + private readonly IEventRegister? _sysLogRegister = eventRegisterResolver(nameof(SysLogRegister)); + private readonly IEventRegister? _serviceInfoStatusUpdateRegister = eventRegisterResolver(nameof(ServiceInfoStatusUpdateRegister)); + + public void Register() + { + _configStatusUpdateRegister?.Register(); + _sysLogRegister?.Register(); + _serviceInfoStatusUpdateRegister?.Register(); + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs new file mode 100644 index 00000000..de8b9508 --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs @@ -0,0 +1,139 @@ +using System.Net; +using Agile.Config.Protocol; +using AgileConfig.Server.Common; +using AgileConfig.Server.Common.RestClient; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.IService; +using Microsoft.Extensions.Logging; + +namespace AgileConfig.Server.Mongodb.Service.EventRegisterService; + +internal class ServiceInfoStatusUpdateRegister : IEventRegister +{ + private readonly IRemoteServerNodeProxy _remoteServerNodeProxy; + private readonly IServerNodeService _serverNodeService; + private readonly IServiceInfoService _serviceInfoService; + private readonly IRestClient _restClient; + private ILogger _logger; + + public ServiceInfoStatusUpdateRegister( + IRemoteServerNodeProxy remoteServerNodeProxy, + IServerNodeService serverNodeService, + IServiceInfoService serviceInfoService, + ILoggerFactory loggerFactory, + IRestClient restClient) + { + _remoteServerNodeProxy = remoteServerNodeProxy; + _serverNodeService = serverNodeService; + _serviceInfoService = serviceInfoService; + _restClient = restClient; + _logger = loggerFactory.CreateLogger(); + } + + public void Register() + { + TinyEventBus.Instance.Register(EventKeys.REGISTER_A_SERVICE, (param) => + { + Task.Run(async () => + { + var serverNodes = await _serverNodeService.GetAllNodesAsync(); + foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) + { + //clear cache + _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Address); + //send ws action + var act = new WebsocketAction() + { + Module = ActionModule.RegisterCenter, + Action = ActionConst.Reload + }; + _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Address, act); + } + }); + }); + TinyEventBus.Instance.Register(EventKeys.UNREGISTER_A_SERVICE, (param) => + { + Task.Run(async () => + { + var serverNodes = await _serverNodeService.GetAllNodesAsync(); + foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) + { + //clear cache + _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Address); + //send ws action + var act = new WebsocketAction() + { + Module = ActionModule.RegisterCenter, + Action = ActionConst.Reload + }; + _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Address, act); + } + }); + }); + TinyEventBus.Instance.Register(EventKeys.UPDATE_SERVICE_STATUS, (param) => + { + Task.Run(async () => + { + var serverNodes = await _serverNodeService.GetAllNodesAsync(); + foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) + { + //clear cache + _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Address); + //send ws action + var act = new WebsocketAction() + { + Module = ActionModule.RegisterCenter, + Action = ActionConst.Reload + }; + _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Address, act); + } + }); + }); + TinyEventBus.Instance.Register(EventKeys.UPDATE_SERVICE_STATUS, (param) => + { + Task.Run(async () => + { + dynamic paramObj = param; + string id = paramObj.UniqueId; + var service = await _serviceInfoService.GetByUniqueIdAsync(id); + if (service != null && !string.IsNullOrWhiteSpace(service.AlarmUrl) && + service.Status == ServiceStatus.Unhealthy) + { + //如果是下线发送通知 + _ = SendServiceOfflineMessageAsync(service); + } + }); + }); + } + + private async Task SendServiceOfflineMessageAsync(ServiceInfo service) + { + var msg = new + { + UniqueId = service.Id, + service.ServiceId, + service.ServiceName, + Time = DateTime.Now, + Status = ServiceStatus.Unhealthy.ToString(), + Message = "服务不健康" + }; + + try + { + await FunctionUtil.TRYAsync(async () => + { + var content = new StringContent(""); + content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); + using var resp = await _restClient.PostAsync(service.AlarmUrl, null); + + resp.EnsureSuccessStatusCode(); + + return resp.StatusCode == HttpStatusCode.OK; + }, 5); + } + catch (Exception e) + { + _logger.LogError(e, $"try to send message to alarm url {service.AlarmUrl} failed"); + } + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/SysLogRegister.cs b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/SysLogRegister.cs new file mode 100644 index 00000000..5c4e57c1 --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/SysLogRegister.cs @@ -0,0 +1,475 @@ +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.IService; + +namespace AgileConfig.Server.Mongodb.Service.EventRegisterService; + +internal class SysLogRegister(ISysLogService sysLogService) : IEventRegister +{ + public void Register() + { + TinyEventBus.Instance.Register(EventKeys.USER_LOGIN_SUCCESS, (param) => + { + dynamic param_dy = param as dynamic; + string userName = param_dy.userName; + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + LogText = $"{userName} 登录成功" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + + TinyEventBus.Instance.Register(EventKeys.INIT_SUPERADMIN_PASSWORD_SUCCESS, (parm) => + { + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + LogText = $"超级管理员密码初始化成功" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + + TinyEventBus.Instance.Register(EventKeys.RESET_USER_PASSWORD_SUCCESS, (param) => + { + dynamic param_dy = param as dynamic; + User user = param_dy.user; + string userName = param_dy.userName; + + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + LogText = $"用户 {userName} 重置 {user.UserName} 的密码为默认密码 " + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + + TinyEventBus.Instance.Register(EventKeys.CHANGE_USER_PASSWORD_SUCCESS, (param) => + { + dynamic param_dy = param as dynamic; + string userName = param_dy.userName; + + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + LogText = $"修改用户 {userName} 的密码成功" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + + TinyEventBus.Instance.Register(EventKeys.ADD_APP_SUCCESS, (param) => + { + dynamic param_dy = param; + App app = param_dy.app; + string userName = param_dy.userName; + if (app != null) + { + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + LogText = $"用户:{userName} 新增应用【AppId:{app.Id}】【AppName:{app.Name}】" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + } + }); + + // app + TinyEventBus.Instance.Register(EventKeys.EDIT_APP_SUCCESS, (param) => + { + dynamic param_dy = param; + App app = param_dy.app; + string userName = param_dy.userName; + if (app != null) + { + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + LogText = $"用户:{userName} 编辑应用【AppId:{app.Id}】【AppName:{app.Name}】" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + } + }); + + TinyEventBus.Instance.Register(EventKeys.DISABLE_OR_ENABLE_APP_SUCCESS, (param) => + { + dynamic param_dy = param; + App app = param_dy.app; + string userName = param_dy.userName; + if (app != null) + { + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + LogText = $"用户:{userName} {(app.Enabled ? "启用" : "禁用")}应用【AppId:{app.Id}】" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + } + }); + + TinyEventBus.Instance.Register(EventKeys.DELETE_APP_SUCCESS, (param) => + { + dynamic param_dy = param; + App app = param_dy.app; + string userName = param_dy.userName; + if (app != null) + { + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Warn, + LogText = $"用户:{userName} 删除应用【AppId:{app.Id}】" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + } + }); + + //config + TinyEventBus.Instance.Register(EventKeys.ADD_CONFIG_SUCCESS, (param) => + { + dynamic param_dy = param; + Config config = param_dy.config; + string userName = param_dy.userName; + + if (config != null) + { + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + AppId = config.AppId, + LogText = + $"用户:{userName} 新增配置【Group:{config.Group}】【Key:{config.Key}】【AppId:{config.AppId}】【Env:{config.Env}】【待发布】" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + } + }); + TinyEventBus.Instance.Register(EventKeys.EDIT_CONFIG_SUCCESS, (param) => + { + dynamic param_dy = param; + Config config = param_dy.config; + string userName = param_dy.userName; + + if (config != null) + { + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + AppId = config.AppId, + LogText = + $"用户:{userName} 编辑配置【Group:{config.Group}】【Key:{config.Key}】【AppId:{config.AppId}】【Env:{config.Env}】【待发布】" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + } + }); + + TinyEventBus.Instance.Register(EventKeys.DELETE_CONFIG_SUCCESS, (param) => + { + dynamic param_dy = param; + Config config = param_dy.config; + string userName = param_dy.userName; + + if (config != null) + { + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Warn, + AppId = config.AppId, + LogText = + $"用户:{userName} 删除配置【Group:{config.Group}】【Key:{config.Key}】【AppId:{config.AppId}】【Env:{config.Env}】【待发布】" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + } + }); + TinyEventBus.Instance.Register(EventKeys.DELETE_CONFIG_SOME_SUCCESS, (param) => + { + dynamic param_dy = param; + string userName = param_dy.userName; + string appId = param_dy.appId; + string env = param_dy.env; + if (appId != null) + { + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Warn, + AppId = appId, + LogText = $"用户:{userName} 批量删除配置【Env:{env}】" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + } + }); + + TinyEventBus.Instance.Register(EventKeys.PUBLISH_CONFIG_SUCCESS, (param) => + { + dynamic param_dy = param; + PublishTimeline node = param_dy.publishTimelineNode; + string userName = param_dy.userName; + string env = param_dy.env; + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + AppId = node.AppId, + LogText = + $"用户:{userName} 发布配置【AppId:{node.AppId}】【Env:{env}】【版本:{node.PublishTime.Value:yyyyMMddHHmmss}】" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + TinyEventBus.Instance.Register(EventKeys.ROLLBACK_CONFIG_SUCCESS, (param) => + { + dynamic param_dy = param; + string userName = param_dy.userName; + PublishTimeline timelineNode = param_dy.timelineNode; + string env = param_dy.env; + + if (timelineNode != null) + { + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Warn, + AppId = timelineNode.AppId, + LogText = + $"{userName} 回滚应用【{timelineNode.AppId}】【Env:{env}】至发布版本【{timelineNode.PublishTime.Value:yyyyMMddHHmmss}】" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + } + }); + TinyEventBus.Instance.Register(EventKeys.CANCEL_EDIT_CONFIG_SUCCESS, (param) => + { + dynamic param_dy = param; + string userName = param_dy.userName; + Config config = param_dy.config; + + if (config != null) + { + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + AppId = config.AppId, + LogText = + $"{userName} 撤销编辑状态的配置【Group:{config.Group}】【Key:{config.Key}】【AppId:{config.AppId}】【Env:{config.Env}】" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + } + }); + TinyEventBus.Instance.Register(EventKeys.CANCEL_EDIT_CONFIG_SOME_SUCCESS, (param) => + { + dynamic param_dy = param; + string userName = param_dy.userName; + string appId = param_dy.appId; + string env = param_dy.env; + + if (appId != null) + { + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + AppId = appId, + LogText = $"{userName} 批量撤销编辑状态的配置【Env:{env}】" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + } + }); + TinyEventBus.Instance.Register(EventKeys.ADD_NODE_SUCCESS, (param) => + { + dynamic param_dy = param; + ServerNode node = param_dy.node; + string userName = param_dy.userName; + + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + LogText = $"用户:{userName} 添加节点:{node.Address}" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + + TinyEventBus.Instance.Register(EventKeys.DELETE_NODE_SUCCESS, (param) => + { + dynamic param_dy = param; + ServerNode node = param_dy.node; + string userName = param_dy.userName; + + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Warn, + LogText = $"用户:{userName} 删除节点:{node.Address}" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + + TinyEventBus.Instance.Register(EventKeys.ADD_USER_SUCCESS, (param) => + { + dynamic param_dy = param; + User user = param_dy.user; + string userName = param_dy.userName; + + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + LogText = $"用户:{userName} 添加用户:{user.UserName} 成功" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + + TinyEventBus.Instance.Register(EventKeys.EDIT_USER_SUCCESS, (param) => + { + dynamic param_dy = param; + User user = param_dy.user; + string userName = param_dy.userName; + + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + LogText = $"用户:{userName} 编辑用户:{user.UserName} 成功" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + + TinyEventBus.Instance.Register(EventKeys.DELETE_USER_SUCCESS, (param) => + { + dynamic param_dy = param; + User user = param_dy.user; + string userName = param_dy.userName; + + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Warn, + LogText = $"用户:{userName} 删除用户:{user.UserName} 成功" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + + TinyEventBus.Instance.Register(EventKeys.DISCONNECT_CLIENT_SUCCESS, (param) => + { + dynamic param_dy = param; + string clientId = param_dy.clientId; + string userName = param_dy.userName; + + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Warn, + LogText = $"用户:{userName} 断开客户端 {clientId} 成功" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + + //service info envets + TinyEventBus.Instance.Register(EventKeys.REGISTER_A_SERVICE, (param) => + { + dynamic param_dy = param; + string serviceId = param_dy.ServiceId; + string serviceName = param_dy.ServiceName; + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + LogText = $"服务:【{serviceId}】【{serviceName}】 注册成功" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + TinyEventBus.Instance.Register(EventKeys.UNREGISTER_A_SERVICE, (param) => + { + dynamic param_dy = param; + string serviceId = param_dy.ServiceId; + string serviceName = param_dy.ServiceName; + var log = new SysLog + { + LogTime = DateTime.Now, + LogType = SysLogType.Normal, + LogText = $"服务:【{serviceId}】【{serviceName}】 卸载成功" + }; + Task.Run(async () => + { + await sysLogService.AddSysLogAsync(log); + }); + }); + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/JwtService.cs b/src/AgileConfig.Server.Mongodb.Service/JwtService.cs new file mode 100644 index 00000000..0bbd5e4f --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/JwtService.cs @@ -0,0 +1,67 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +using AgileConfig.Server.Common; +using AgileConfig.Server.IService; +using Microsoft.IdentityModel.Tokens; + +namespace AgileConfig.Server.Mongodb.Service; + +public class JwtService(ISettingService settingService) : IJwtService +{ + public string Issuer => Global.Config["JwtSetting:Issuer"]; + public string Audience => Global.Config["JwtSetting:Audience"]; + public int ExpireSeconds => int.Parse(Global.Config["JwtSetting:ExpireSeconds"]); + + private string? _secretKey; + + public string GetSecurityKey() + { + if (!string.IsNullOrEmpty(_secretKey)) + { + return _secretKey; + } + + _secretKey = Global.Config["JwtSetting:SecurityKey"]; + if (!string.IsNullOrEmpty(_secretKey)) + { + return _secretKey; + } + + _secretKey = settingService.GetJwtTokenSecret(); + + if (string.IsNullOrEmpty(_secretKey)) + { + throw new ArgumentNullException($"No JwtSetting SecurityKey"); + } + + return _secretKey; + } + + public string GetToken(string userId, string userName, bool isAdmin) + { + //创建用户身份标识,可按需要添加更多信息 + var claims = new Claim[] + { + new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), + new Claim("id", userId, ClaimValueTypes.String), // 用户id + new Claim("username", userName, ClaimValueTypes.String), // 用户名 + new Claim("admin", isAdmin.ToString(), ClaimValueTypes.Boolean) // 是否是管理员 + }; + var key = Encoding.UTF8.GetBytes(GetSecurityKey()); + //创建令牌 + var token = new JwtSecurityToken( + issuer: Issuer, + audience: Audience, + signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), + SecurityAlgorithms.HmacSha256Signature), + claims: claims, + notBefore: DateTime.Now, + expires: DateTime.Now.AddSeconds(ExpireSeconds) + ); + + string jwtToken = new JwtSecurityTokenHandler().WriteToken(token); + + return jwtToken; + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs b/src/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs new file mode 100644 index 00000000..b85a1ace --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs @@ -0,0 +1,49 @@ +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.IService; +using AgileConfig.Server.Mongodb.Service.EventRegisterService; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; + +namespace AgileConfig.Server.Mongodb.Service; + +public delegate IEventRegister? EventRegisterResolver(string key); + +public static class MongodbServiceExtensions +{ + public static void AddBusinessForMongoServices(this IServiceCollection services) + { + services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); + services.AddSingleton(); + + services.AddScoped(); + + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(x => key => + { + return key switch + { + nameof(ConfigStatusUpdateRegister) => x.GetService(), + nameof(ServiceInfoStatusUpdateRegister) => x.GetService(), + nameof(SysLogRegister) => x.GetService(), + _ => x.GetService() + }; + }); + + services.AddScoped(); + services.AddScoped(); + + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/PermissionService.cs b/src/AgileConfig.Server.Mongodb.Service/PermissionService.cs new file mode 100644 index 00000000..2a715d2c --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/PermissionService.cs @@ -0,0 +1,230 @@ +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.IService; +using MongoDB.Driver; + +namespace AgileConfig.Server.Mongodb.Service; + +public class PermissionService( + IRepository userRoleRepository, + IRepository userAppAuthRepository, + IRepository appRepository) : IPremissionService +{ + private static readonly List Template_SuperAdminPermissions = new List + { + "GLOBAL_" + Functions.App_Add, + "GLOBAL_" + Functions.App_Delete, + "GLOBAL_" + Functions.App_Edit, + "GLOBAL_" + Functions.App_Auth, + + "GLOBAL_" + Functions.Config_Add, + "GLOBAL_" + Functions.Config_Delete, + "GLOBAL_" + Functions.Config_Edit, + "GLOBAL_" + Functions.Config_Offline, + "GLOBAL_" + Functions.Config_Publish, + + "GLOBAL_" + Functions.Node_Add, + "GLOBAL_" + Functions.Node_Delete, + + "GLOBAL_" + Functions.Client_Disconnect, + + "GLOBAL_" + Functions.User_Add, + "GLOBAL_" + Functions.User_Edit, + "GLOBAL_" + Functions.User_Delete, + }; + + private static readonly List Template_NormalAdminPermissions = new List + { + "GLOBAL_" + Functions.App_Add, + "GLOBAL_" + Functions.Node_Add, + "GLOBAL_" + Functions.Node_Delete, + "GLOBAL_" + Functions.Client_Disconnect, + + "GLOBAL_" + Functions.User_Add, + "GLOBAL_" + Functions.User_Edit, + "GLOBAL_" + Functions.User_Delete, + + "APP_{0}_" + Functions.App_Delete, + "APP_{0}_" + Functions.App_Edit, + "APP_{0}_" + Functions.App_Auth, + + "APP_{0}_" + Functions.Config_Add, + "APP_{0}_" + Functions.Config_Delete, + "APP_{0}_" + Functions.Config_Edit, + "APP_{0}_" + Functions.Config_Offline, + "APP_{0}_" + Functions.Config_Publish, + }; + + private static readonly List Template_NormalUserPermissions_Edit = new List + { + "APP_{0}_" + Functions.Config_Add, + "APP_{0}_" + Functions.Config_Delete, + "APP_{0}_" + Functions.Config_Edit, + }; + + private static readonly List Template_NormalUserPermissions_Publish = new List + { + "APP_{0}_" + Functions.Config_Offline, + "APP_{0}_" + Functions.Config_Publish + }; + + private async Task> GetAdminUserFunctions(string userId) + { + var userFunctions = new List(); + //获取当前用户为管理员的app + var adminApps = await GetUserAdminApps(userId); + Template_NormalAdminPermissions.Where(x => x.StartsWith("GLOBAL_")).ToList().ForEach( + key => { userFunctions.Add(key); } + ); + Template_NormalUserPermissions_Edit.Where(x => x.StartsWith("GLOBAL_")).ToList().ForEach( + key => { userFunctions.Add(key); } + ); + Template_NormalUserPermissions_Publish.Where(x => x.StartsWith("GLOBAL_")).ToList().ForEach( + key => { userFunctions.Add(key); } + ); + foreach (var app in adminApps) + { + foreach (var temp in Template_NormalAdminPermissions) + { + if (temp.StartsWith("APP_{0}_")) + { + userFunctions.Add(string.Format(temp, app.Id)); + } + } + } + + //EditConfigPermissionKey + var editPermissionApps = await GetUserAuthApp(userId, EditConfigPermissionKey); + foreach (var app in editPermissionApps) + { + foreach (var temp in Template_NormalUserPermissions_Edit) + { + if (temp.StartsWith("APP_{0}_")) + { + userFunctions.Add(string.Format(temp, app.Id)); + } + } + } + + //PublishConfigPermissionKey + var publishPermissionApps = await GetUserAuthApp(userId, PublishConfigPermissionKey); + foreach (var app in publishPermissionApps) + { + foreach (var temp in Template_NormalUserPermissions_Publish) + { + if (temp.StartsWith("APP_{0}_")) + { + userFunctions.Add(string.Format(temp, app.Id)); + } + } + } + + return userFunctions; + } + + private async Task> GetNormalUserFunctions(string userId) + { + var userFunctions = new List(); + //EditConfigPermissionKey + var editPermissionApps = await GetUserAuthApp(userId, EditConfigPermissionKey); + foreach (var app in editPermissionApps) + { + foreach (var temp in Template_NormalUserPermissions_Edit) + { + if (temp.StartsWith("GLOBAL_")) + { + userFunctions.Add(temp); + } + + if (temp.StartsWith("APP_{0}_")) + { + userFunctions.Add(string.Format(temp, app.Id)); + } + } + } + + //PublishConfigPermissionKey + var publishPermissionApps = await GetUserAuthApp(userId, PublishConfigPermissionKey); + foreach (var app in publishPermissionApps) + { + foreach (var temp in Template_NormalUserPermissions_Publish) + { + if (temp.StartsWith("GLOBAL_")) + { + userFunctions.Add(temp); + } + + if (temp.StartsWith("APP_{0}_")) + { + userFunctions.Add(string.Format(temp, app.Id)); + } + } + } + + return userFunctions; + } + + /// + /// 获取角色权限的模板 + /// + /// + /// + public async Task> GetUserPermission(string userId) + { + var userRoles = await userRoleRepository.SearchFor(x => x.UserId == userId).ToListAsync(); + if (userRoles.Any(x => x.Role == Role.SuperAdmin)) + { + return Template_SuperAdminPermissions; + } + + var userFunctions = new List(); + //计算普通管理员的权限 + if (userRoles.Any(x => x.Role == Role.Admin)) + { + userFunctions.AddRange(await GetAdminUserFunctions(userId)); + } + + //计算普通用户的权限 + if (userRoles.Any(x => x.Role == Role.NormalUser)) + { + userFunctions.AddRange(await GetNormalUserFunctions(userId)); + } + + return userFunctions.Distinct().ToList(); + } + + /// + /// 获取被授权给用户的app + /// + /// + /// + private async Task> GetUserAuthApp(string userId, string authPermissionKey) + { + var apps = new List(); + var userAuths = await userAppAuthRepository.SearchFor(x => x.UserId == userId && x.Permission == authPermissionKey).ToListAsync(); + foreach (var appAuth in userAuths) + { + var app = await appRepository.SearchFor(x => x.Id == appAuth.AppId).FirstAsync(); + if (app != null) + { + apps.Add(app); + } + } + + return apps; + } + + /// + /// 获取是管理员的app + /// + /// + /// + private async Task> GetUserAdminApps(string userId) + { + return await appRepository.SearchFor(x => x.AppAdmin == userId).ToListAsync(); + } + + public string EditConfigPermissionKey => "EDIT_CONFIG"; + + public string PublishConfigPermissionKey => "PUBLISH_CONFIG"; +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/RegisterCenterService.cs b/src/AgileConfig.Server.Mongodb.Service/RegisterCenterService.cs new file mode 100644 index 00000000..926b92d9 --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/RegisterCenterService.cs @@ -0,0 +1,153 @@ +using System.Dynamic; +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.IService; +using Microsoft.Extensions.Logging; +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.Mongodb.Service; + +public class RegisterCenterService( + IRepository serviceInfoRepository, + IServiceInfoService serviceInfoService, + ILogger logger) : IRegisterCenterService +{ + public async Task RegisterAsync(ServiceInfo serviceInfo) + { + if (serviceInfo == null) + { + throw new ArgumentNullException(nameof(serviceInfo)); + } + + + //if exist + var oldEntity = await serviceInfoRepository.SearchFor(x => x.ServiceId == serviceInfo.ServiceId) + .FirstOrDefaultAsync(); + if (oldEntity != null) + { + oldEntity.RegisterTime = DateTime.Now; + oldEntity.Status = ServiceStatus.Healthy; + oldEntity.LastHeartBeat = DateTime.Now; + oldEntity.ServiceName = serviceInfo.ServiceName; + oldEntity.Ip = serviceInfo.Ip; + oldEntity.Port = serviceInfo.Port; + oldEntity.MetaData = serviceInfo.MetaData; + oldEntity.HeartBeatMode = serviceInfo.HeartBeatMode; + oldEntity.CheckUrl = serviceInfo.CheckUrl; + oldEntity.AlarmUrl = serviceInfo.AlarmUrl; + oldEntity.RegisterWay = serviceInfo.RegisterWay; + await serviceInfoRepository.UpdateAsync(oldEntity); + + serviceInfoService.ClearCache(); + + logger.LogInformation("registered service {ServiceId} {ServiceName} successful", serviceInfo.ServiceId, + serviceInfo.ServiceName); + + return oldEntity.Id; + } + + serviceInfo.RegisterTime = DateTime.Now; + serviceInfo.LastHeartBeat = DateTime.Now; + serviceInfo.Status = ServiceStatus.Healthy; + serviceInfo.Id = Guid.NewGuid().ToString("n"); + + await serviceInfoRepository.InsertAsync(serviceInfo); + serviceInfoService.ClearCache(); + + logger.LogInformation("registered service {ServiceId} {ServiceName} successful", serviceInfo.ServiceId, + serviceInfo.ServiceName); + + return serviceInfo.Id; + } + + public async Task UnRegisterAsync(string serviceUniqueId) + { + logger.LogInformation("try to unregister service {ServiceUniqueId}", serviceUniqueId); + + if (string.IsNullOrEmpty(serviceUniqueId)) + { + throw new ArgumentNullException(nameof(serviceUniqueId)); + } + + var oldEntity = await serviceInfoRepository.SearchFor(x => x.Id == serviceUniqueId).FirstOrDefaultAsync(); + if (oldEntity == null) + { + //if not exist + logger.LogInformation("not find the service {ServiceUniqueId} ", serviceUniqueId); + return false; + } + + await serviceInfoRepository.DeleteAsync(oldEntity.Id); + + serviceInfoService.ClearCache(); + + logger.LogInformation("unregister service {ServiceId} {ServiceName} successful", oldEntity.ServiceId, + oldEntity.ServiceName); + + return true; + } + + public async Task UnRegisterByServiceIdAsync(string serviceId) + { + logger.LogInformation("try to unregister service {ServiceId}", serviceId); + + if (string.IsNullOrEmpty(serviceId)) + { + throw new ArgumentNullException(nameof(serviceId)); + } + + var oldEntity = await serviceInfoRepository.SearchFor(x => x.ServiceId == serviceId).FirstOrDefaultAsync(); + if (oldEntity == null) + { + //if not exist + logger.LogInformation("not find the service {ServiceId}", serviceId); + return false; + } + + await serviceInfoRepository.DeleteAsync(oldEntity.Id); + + serviceInfoService.ClearCache(); + + logger.LogInformation("unregister service {ServiceId} {ServiceName} successful", oldEntity.ServiceId, + oldEntity.ServiceName); + + return true; + } + + public async Task ReceiveHeartbeatAsync(string serviceUniqueId) + { + var entity = await serviceInfoRepository.FindAsync(serviceUniqueId); + if (entity == null) + { + return false; + } + + logger.LogInformation("receive service {ServiceId} {ServiceName} heartbeat", entity.ServiceId, entity.ServiceName); + + if (entity.HeartBeatMode == "server") + { + //如果是server模式,则不作为服务是否在线的判断依据 + } + else + { + var oldStatus = entity.Status; + entity.Status = ServiceStatus.Healthy; + entity.LastHeartBeat = DateTime.Now; + await serviceInfoRepository.UpdateAsync(entity); + + + if (oldStatus != ServiceStatus.Healthy) + { + serviceInfoService.ClearCache(); + dynamic param = new ExpandoObject(); + param.ServiceId = entity.ServiceId; + param.ServiceName = entity.ServiceName; + param.UniqueId = entity.Id; + TinyEventBus.Instance.Fire(EventKeys.UPDATE_SERVICE_STATUS, param); + } + } + + return true; + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/RemoteServerNodeProxy.cs b/src/AgileConfig.Server.Mongodb.Service/RemoteServerNodeProxy.cs new file mode 100644 index 00000000..15c5e7b4 --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/RemoteServerNodeProxy.cs @@ -0,0 +1,272 @@ +using System.Collections.Concurrent; +using Agile.Config.Protocol; +using AgileConfig.Server.Common; +using AgileConfig.Server.Common.RestClient; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.IService; +using Microsoft.Extensions.Logging; + +namespace AgileConfig.Server.Mongodb.Service; + +public class RemoteServerNodeProxy( + IServerNodeService serverNodeService, + ISysLogService sysLogService, + ILoggerFactory loggerFactory, + IRestClient restClient) + : IRemoteServerNodeProxy +{ + + private readonly ILogger _logger = loggerFactory.CreateLogger(); + + + private static readonly ConcurrentDictionary _serverNodeClientReports = + new ConcurrentDictionary(); + + public async Task AllClientsDoActionAsync(string address, WebsocketAction action) + { + var result = await FunctionUtil.TRYAsync(async () => + { + dynamic result = await restClient.PostAsync(address + "/RemoteOP/AllClientsDoAction", action); + if ((bool)result.success) + { + return true; + } + + return false; + }, 5); + + var module = ""; + if (action.Module == "r") + { + module = "注册中心"; + } + + if (action.Module == "c") + { + module = "配置中心"; + } + + await sysLogService.AddSysLogAsync(new SysLog + { + LogTime = DateTime.Now, + LogType = result ? SysLogType.Normal : SysLogType.Warn, + LogText = $"通知节点【{address}】所有客户端:【{module}】【{action.Action}】 响应:{(result ? "成功" : "失败")}" + }); + + return result; + } + + public async Task AppClientsDoActionAsync(string address, string appId, string env, WebsocketAction action) + { + var result = await FunctionUtil.TRYAsync(async () => + { + var url = $"{address}/RemoteOP/AppClientsDoAction?appId={Uri.EscapeDataString(appId)}&env={env}"; + dynamic result = await restClient.PostAsync(url, action); + if ((bool)result.success) + { + return true; + } + + return false; + }, 5); + + + var module = ""; + if (action.Module == "r") + { + module = "注册中心"; + } + + if (action.Module == "c") + { + module = "配置中心"; + } + + await sysLogService.AddSysLogAsync(new SysLog + { + LogTime = DateTime.Now, + LogType = result ? SysLogType.Normal : SysLogType.Warn, + AppId = appId, + LogText = $"通知节点【{address}】应用【{appId}】的客户端:【{module}】【{action.Action}】 响应:{(result ? "成功" : "失败")}" + }); + + + return result; + } + + public async Task OneClientDoActionAsync(string address, string clientId, WebsocketAction action) + { + var result = await FunctionUtil.TRYAsync(async () => + { + var url = $"{address}/RemoteOP/OneClientDoAction?clientId={clientId}"; + dynamic result = await restClient.PostAsync(url, action); + + if ((bool)result.success) + { + if (action.Action == ActionConst.Offline) + { + if (_serverNodeClientReports.ContainsKey(address)) + { + if (_serverNodeClientReports[address].Infos != null) + { + var report = _serverNodeClientReports[address]; + report.Infos.RemoveAll(c => c.Id == clientId); + report.ClientCount = report.Infos.Count; + } + } + } + + return true; + } + + return false; + }, 5); + + + var module = ""; + if (action.Module == "r") + { + module = "注册中心"; + } + + if (action.Module == "c") + { + module = "配置中心"; + } + + await sysLogService.AddSysLogAsync(new SysLog + { + LogTime = DateTime.Now, + LogType = result ? SysLogType.Normal : SysLogType.Warn, + LogText = $"通知节点【{address}】的客户端【{clientId}】:【{module}】【{action.Action}】 响应:{(result ? "成功" : "失败")}" + }); + + + return result; + } + + public async Task GetClientsReportAsync(string address) + { + if (string.IsNullOrEmpty(address)) + { + return new ClientInfos() + { + ClientCount = 0, + Infos = new List() + }; + } + + try + { + var url = address + "/report/Clients"; + + var clients = await restClient.GetAsync(url); + if (clients != null) + { + clients.Infos?.ForEach(i => { i.Address = address; }); + return clients; + } + + return new ClientInfos() + { + ClientCount = 0, + Infos = new List() + }; + } + catch (Exception ex) + { + _logger?.LogError(ex,"Try to get client infos from node {Address} occur ERROR ",address); + } + + return new ClientInfos() + { + ClientCount = 0, + Infos = new List() + }; + } + + public async Task TestEchoAsync(string address) + { + var node = await serverNodeService.GetAsync(address); + try + { + var url = node.Address + "/home/echo"; + + using var resp = await restClient.GetAsync(url); + + if (resp.StatusCode == System.Net.HttpStatusCode.OK && (await resp.Content.ReadAsStringAsync()) == "ok") + { + node.LastEchoTime = DateTime.Now; + node.Status = NodeStatus.Online; + } + else + { + node.Status = NodeStatus.Offline; + } + } + catch (Exception e) + { + node.Status = NodeStatus.Offline; + _logger.LogInformation(e, "Try test node {Address} echo , but fail", node.Address); + } + + if (node.Status == NodeStatus.Offline) + { + var time = node.LastEchoTime ?? node.CreateTime; + + if ((DateTime.Now - time).TotalMinutes >= 30) + { + // 超过 30 分钟没有回应,则移除节点 + await serverNodeService.DeleteAsync(address); + return; + } + } + + await serverNodeService.UpdateAsync(node); + } + + public Task TestEchoAsync() + { + return Task.Run(async () => + { + while (true) + { + var nodes = await serverNodeService.GetAllNodesAsync(); + + foreach (var node in nodes) + { + await TestEchoAsync(node.Address); + } + + await Task.Delay(5000 * 1); + } + }); + } + + public async Task ClearConfigServiceCache(string address) + { + try + { + var url = (address + "/RemoteOP/ClearConfigServiceCache"); + using var resp = await restClient.PostAsync(url, null); + } + catch (Exception e) + { + _logger.LogError(e, "Try to clear node {Address}'s config cache , but fail", address); + } + } + + public async Task ClearServiceInfoCache(string address) + { + try + { + var url = (address + "/RemoteOP/ClearServiceInfoCache"); + + await restClient.PostAsync(url, null); + } + catch (Exception e) + { + _logger.LogError(e, "Try to clear node {Address}'s services info cache , but fail", address); + } + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/ServerNodeService.cs b/src/AgileConfig.Server.Mongodb.Service/ServerNodeService.cs new file mode 100644 index 00000000..c4e61e43 --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/ServerNodeService.cs @@ -0,0 +1,117 @@ +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.IService; +using MongoDB.Driver; +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.Mongodb.Service; + +public class ServerNodeService(IRepository repository) : IServerNodeService +{ + public async Task AddAsync(ServerNode node) + { + await repository.InsertAsync(node); + return true; + } + + public async Task DeleteAsync(ServerNode node) + { + var result = await repository.DeleteAsync(x => x.Address == node.Address); + return result.DeletedCount > 0; + } + + public async Task DeleteAsync(string address) + { + var result = await repository.DeleteAsync(x => x.Address == address); + return result.DeletedCount > 0; + } + + public void Dispose() + { + GC.SuppressFinalize(this); + } + + public Task> GetAllNodesAsync() + { + return repository.SearchFor(x => true).ToListAsync(); + } + + public Task GetAsync(string address) + { + return repository.SearchFor(n => n.Address == address).FirstOrDefaultAsync(); + } + + public async Task UpdateAsync(ServerNode node) + { + var result = await repository.UpdateAsync(node); + return result.ModifiedCount > 0; + } + + + public async Task InitWatchNodeAsync() + { + var count = await repository.SearchFor(x => true).CountAsync(); + if (count > 0) + { + return false; + } + + var nodes = Global.Config["nodes"]; + var addresses = new List(); + if (!string.IsNullOrEmpty(nodes)) + { + var arr = nodes.Split(','); + foreach (var item in arr) + { + var address = ""; + if (item.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + address = item; + } + else + { + address = "http://" + item; + } + + addresses.Add(address); + } + } + + var existNodes = await repository.SearchFor(x => addresses.Contains(x.Address)).ToListAsync(); + var newNodes = addresses + .Where(x => existNodes.All(y => y.Address != x)) + .Select(x => new ServerNode { Address = x, CreateTime = DateTime.Now }) + .ToList(); + await repository.InsertAsync(newNodes); + + return true; + } + + public async Task JoinAsync(string ip, int port, string desc) + { + var address = $"http://{ip}:{port}"; + var nodes = await repository.SearchFor(x => x.Address == address).ToListAsync(); + if (nodes.Count > 0) + { + nodes.ForEach(n => + { + n.Address = address; + n.Remark = desc; + n.Status = NodeStatus.Online; + }); + } + else + { + await repository.InsertAsync(new ServerNode + { + Address = address, + CreateTime = DateTime.Now, + Remark = desc, + Status = NodeStatus.Online, + LastEchoTime = DateTime.Now + }); + } + return true; + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/ServiceHealthCheckService.cs b/src/AgileConfig.Server.Mongodb.Service/ServiceHealthCheckService.cs new file mode 100644 index 00000000..f3be7b1c --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/ServiceHealthCheckService.cs @@ -0,0 +1,204 @@ +using AgileConfig.Server.Common; +using AgileConfig.Server.Common.RestClient; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.IService; +using Microsoft.Extensions.Logging; +using MongoDB.Driver; + +namespace AgileConfig.Server.Mongodb.Service; + +public class ServiceHealthCheckService( + IRepository serviceInfoRepository, + IServiceInfoService serviceInfoService, + ILogger logger, + IRestClient restClient) + : IServiceHealthCheckService +{ + private readonly ILogger _logger = logger; + + private int _checkInterval; + private int _unhealthInterval; + private int _removeServiceInterval; + + /// + /// 健康检测的间隔 + /// + /// + private int CheckInterval + { + get + { + if (_checkInterval > 0) + { + return _checkInterval; + } + + var interval = Global.Config["serviceHealthCheckInterval"]; + if (int.TryParse(interval, out int i)) + { + if (i <= 0) + { + throw new ArgumentException("serviceHealthCheckInterval must be greater than 0"); + } + + _checkInterval = i; + } + + return _checkInterval; + } + } + + /// + /// 判断一个服务是否健康的标准时间,操作这个时间没有收到响应,则认为不健康 + /// + /// + private int UnhealthInterval + { + get + { + if (_unhealthInterval > 0) + { + return _unhealthInterval; + } + + var interval = Global.Config["serviceUnhealthInterval"]; + if (int.TryParse(interval, out int i)) + { + if (i <= 0) + { + throw new ArgumentException("serviceUnhealthInterval must be greater than 0"); + } + + _unhealthInterval = i; + } + + return _unhealthInterval; + } + } + + private int RemoveServiceInterval + { + get + { + if (_removeServiceInterval > 0) + { + return _removeServiceInterval; + } + + var interval = Global.Config["removeServiceInterval"]; + if (int.TryParse(interval, out int i)) + { + if (i <= 0) + { + _removeServiceInterval = 0; + } + else + { + _removeServiceInterval = i; + } + } + + return _removeServiceInterval; + } + } + + public Task StartCheckAsync() + { + _logger.LogInformation("start to service health check"); + + Task.Factory.StartNew(async () => + { + while (true) + { + //没有填写心跳模式,则不做检查 + var services = await serviceInfoRepository + .SearchFor(x => x.HeartBeatMode != null && x.HeartBeatMode != "").ToListAsync(); + foreach (var service in services) + { + if (service.HeartBeatMode == HeartBeatModes.none.ToString()) + { + continue; + } + + var lstHeartBeat = service.LastHeartBeat; + if (!lstHeartBeat.HasValue) + { + lstHeartBeat = service.RegisterTime ?? DateTime.MinValue; + } + + //service.HeartBeatMode 不为空 + if (!string.IsNullOrWhiteSpace(service.HeartBeatMode)) + { + if (RemoveServiceInterval > 0 && + (DateTime.Now - lstHeartBeat.Value).TotalSeconds > RemoveServiceInterval) + { + //超过设定时间,则直接删除服务 + await serviceInfoService.RemoveAsync(service.Id); + continue; + } + + //是客户端主动心跳,不做http健康检查 + if (service.HeartBeatMode == HeartBeatModes.client.ToString()) + { + if ((DateTime.Now - lstHeartBeat.Value).TotalSeconds > UnhealthInterval) + { + //客户端主动心跳模式:超过 UnhealthInterval 没有心跳,则认为服务不可用 + if (service.Status == ServiceStatus.Healthy) + { + await serviceInfoService.UpdateServiceStatus(service, ServiceStatus.Unhealthy); + } + } + + continue; + } + + //等于server 主动http健康检查 + if (service.HeartBeatMode == HeartBeatModes.server.ToString()) + { + if (string.IsNullOrWhiteSpace(service.CheckUrl)) + { + //CheckUrl不填,直接认为下线 + await serviceInfoService.UpdateServiceStatus(service, ServiceStatus.Unhealthy); + continue; + } + + _ = Task.Run(async () => + { + var result = await CheckAService(service); + await serviceInfoService.UpdateServiceStatus(service, + result ? ServiceStatus.Healthy : ServiceStatus.Unhealthy); + }); + } + } + } + + await Task.Delay(CheckInterval * 1000); + } + }, TaskCreationOptions.LongRunning); + + return Task.CompletedTask; + } + + private async Task CheckAService(ServiceInfo service) + { + try + { + using var resp = await restClient.GetAsync(service.CheckUrl); + + var result = false; + int istatus = ((int)resp.StatusCode - 200); + result = istatus >= 0 && istatus < 100; // 200 段都认为是正常的 + + _logger.LogInformation("check service health {0} {1} {2} result:{3}", service.CheckUrl, service.ServiceId, + service.ServiceName, result ? "up" : "down"); + return result; + } + catch (Exception e) + { + _logger.LogError(e, "check service health {0} {1} {2} error", service.CheckUrl, service.ServiceId, + service.ServiceName); + return false; + } + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/ServiceInfoService.cs b/src/AgileConfig.Server.Mongodb.Service/ServiceInfoService.cs new file mode 100644 index 00000000..4aa066d8 --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/ServiceInfoService.cs @@ -0,0 +1,145 @@ +using System.Dynamic; +using System.Text; +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.IService; +using Microsoft.Extensions.Caching.Memory; +using MongoDB.Driver; +using MongoDB.Driver.Linq; +using Newtonsoft.Json; + +namespace AgileConfig.Server.Mongodb.Service; + +public class ServiceInfoService(IRepository repository, IMemoryCache? memoryCache) : IServiceInfoService +{ + public async Task GetByUniqueIdAsync(string id) + { + var entity = await repository.FindAsync(id); + return entity; + } + + public async Task GetByServiceIdAsync(string serviceId) + { + var entity = await repository.SearchFor(x => x.ServiceId == serviceId).FirstOrDefaultAsync(); + return entity; + } + + public async Task RemoveAsync(string id) + { + var result = await repository.DeleteAsync(id); + return result.DeletedCount > 0; + } + + public async Task> GetAllServiceInfoAsync() + { + var services = await repository.SearchFor(x => true).ToListAsync(); + + return services; + } + + public async Task> GetOnlineServiceInfoAsync() + { + var services = await repository.SearchFor(x => x.Status == ServiceStatus.Healthy) + .ToListAsync(); + + return services; + } + + public async Task> GetOfflineServiceInfoAsync() + { + var services = await repository.SearchFor(x => x.Status == ServiceStatus.Unhealthy) + .ToListAsync(); + + return services; + } + + public async Task ServicesMD5Cache() + { + var cacheKey = $"ServiceInfoService_ServicesMD5Cache"; + if (memoryCache != null && memoryCache.TryGetValue(cacheKey, out string? md5)) + { + return md5; + } + + md5 = await ServicesMD5(); + var cacheOp = new MemoryCacheEntryOptions() + .SetAbsoluteExpiration(TimeSpan.FromSeconds(60)); + memoryCache?.Set(cacheKey, md5, cacheOp); + + return md5; + } + + public async Task ServicesMD5() + { + var services = await GetAllServiceInfoAsync(); + var md5 = GenerateMD5(services); + + return md5; + } + + private string GenerateMD5(List services) + { + var sb = new StringBuilder(); + foreach (var serviceInfo in services.OrderBy(x => x.ServiceId, StringComparer.Ordinal)) + { + var metaDataStr = ""; + if (!string.IsNullOrEmpty(serviceInfo.MetaData)) + { + var metaData = JsonConvert.DeserializeObject>(serviceInfo.MetaData); + if (metaData != null) + { + metaDataStr = string.Join(",", metaData.OrderBy(x => x, StringComparer.Ordinal)); + } + } + + sb.Append( + $"{serviceInfo.ServiceId}&{serviceInfo.ServiceName}&{serviceInfo.Ip}&{serviceInfo.Port}&{(int)serviceInfo.Status}&{metaDataStr}&"); + } + + var txt = sb.ToString(); + return Encrypt.Md5(txt); + } + + public void ClearCache() + { + if (memoryCache is MemoryCache memCache) + { + memCache.Compact(1.0); + } + } + + public async Task UpdateServiceStatus(ServiceInfo service, ServiceStatus status) + { + var id = service.Id; + var oldStatus = service.Status; + + if (status == ServiceStatus.Unhealthy) + { + var update = Builders.Update.Set(x => x.Status, status); + await repository.UpdateAsync(x => x.Id == id, update); + } + else + { + var update = Builders.Update + .Set(x => x.Status, status) + .Set(x => x.LastHeartBeat,DateTime.Now); + await repository.UpdateAsync(x => x.Id == id, update); + } + + if (oldStatus != status) + { + ClearCache(); + dynamic param = new ExpandoObject(); + param.ServiceId = service.ServiceId; + param.ServiceName = service.ServiceName; + param.UniqueId = service.Id; + TinyEventBus.Instance.Fire(EventKeys.UPDATE_SERVICE_STATUS, param); + } + } + + public void Dispose() + { + GC.SuppressFinalize(this); + } +} \ No newline at end of file diff --git a/AgileConfig.Server.Mongodb.Service/SettingService.cs b/src/AgileConfig.Server.Mongodb.Service/SettingService.cs similarity index 100% rename from AgileConfig.Server.Mongodb.Service/SettingService.cs rename to src/AgileConfig.Server.Mongodb.Service/SettingService.cs diff --git a/src/AgileConfig.Server.Mongodb.Service/SysLogService.cs b/src/AgileConfig.Server.Mongodb.Service/SysLogService.cs new file mode 100644 index 00000000..552d7ea1 --- /dev/null +++ b/src/AgileConfig.Server.Mongodb.Service/SysLogService.cs @@ -0,0 +1,84 @@ +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.IService; +using MongoDB.Driver; +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.Mongodb.Service; + +public class SysLogService(IRepository repository) : ISysLogService +{ + public async Task AddRangeAsync(IEnumerable logs) + { + await repository.InsertAsync(logs.ToList()); + return true; + } + + public async Task AddSysLogAsync(SysLog log) + { + await repository.InsertAsync(log); + return true; + } + + public async Task Count(string appId, SysLogType? logType, DateTime? startTime, DateTime? endTime) + { + var query = repository.SearchFor(x => true); + if (!string.IsNullOrEmpty(appId)) + { + query = query.Where(x => x.AppId == appId); + } + + if (startTime.HasValue) + { + query = query.Where(x => x.LogTime >= startTime); + } + + if (endTime.HasValue) + { + query = query.Where(x => x.LogTime < endTime); + } + + if (logType.HasValue) + { + query = query.Where(x => x.LogType == logType); + } + + var count = await query.CountAsync(); + + return count; + } + + public void Dispose() + { + GC.SuppressFinalize(this); + } + + public Task> SearchPage(string appId, SysLogType? logType, DateTime? startTime, DateTime? endTime, + int pageSize, int pageIndex) + { + var query = repository.SearchFor(x => true); + if (!string.IsNullOrEmpty(appId)) + { + query = query.Where(x => x.AppId == appId); + } + + if (startTime.HasValue) + { + query = query.Where(x => x.LogTime >= startTime); + } + + if (endTime.HasValue) + { + query = query.Where(x => x.LogTime < endTime); + } + + if (logType.HasValue) + { + query = query.Where(x => x.LogType == logType); + } + + query = query.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize); + + return query.ToListAsync(); + } +} \ No newline at end of file diff --git a/AgileConfig.Server.Mongodb.Service/UserService.cs b/src/AgileConfig.Server.Mongodb.Service/UserService.cs similarity index 100% rename from AgileConfig.Server.Mongodb.Service/UserService.cs rename to src/AgileConfig.Server.Mongodb.Service/UserService.cs From 34f47ec56fc73da09709c3a3df5c8513f088ab8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Fri, 15 Dec 2023 14:11:42 +0800 Subject: [PATCH 03/45] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dbug=EF=BC=8C=20?= =?UTF-8?q?=E6=94=B9=E5=96=84=E6=89=B9=E9=87=8F=E4=BF=AE=E6=94=B9=E7=9A=84?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../IRepository.cs | 4 +- .../MongodbAccess.cs | 4 +- .../Repository.cs | 65 ++++++------------- 3 files changed, 23 insertions(+), 50 deletions(-) diff --git a/src/AgileConfig.Server.Data.Mongodb/IRepository.cs b/src/AgileConfig.Server.Data.Mongodb/IRepository.cs index e8a4801b..cc939a7b 100644 --- a/src/AgileConfig.Server.Data.Mongodb/IRepository.cs +++ b/src/AgileConfig.Server.Data.Mongodb/IRepository.cs @@ -110,9 +110,9 @@ public interface IRepository /// If the entity no exists property 'id',then will throw exception. Task UpdateAsync(T entity); - Task UpdateAsync(IReadOnlyCollection collection); + Task> UpdateAsync(IEnumerable entities); ReplaceOneResult Update(T entity); - long Update(IReadOnlyCollection collection); + BulkWriteResult Update(IEnumerable entities); } \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs index 16f9474e..2d87d624 100644 --- a/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs @@ -18,7 +18,7 @@ internal MongodbAccess(string? connectionString) if (string.IsNullOrEmpty(connectionString)) throw new Exception("没有配置Mongodb连接字符串"); _connectionString = connectionString; - if (LazyMongoClients is not { IsValueCreated: true } || LazyMongoClients.Value.ContainsKey(connectionString)) + if (LazyMongoClients is not { IsValueCreated: true } || !LazyMongoClients.Value.ContainsKey(connectionString)) { var url = MongoUrl.Create(connectionString); @@ -40,7 +40,7 @@ internal MongodbAccess(string? connectionString) public IMongoDatabase Database => Client.GetDatabase(LazyMongoClients.Value[_connectionString].DatabaseName); } -public class MongodbAccess(string? connectionString) : MongodbAccess(connectionString) +public sealed class MongodbAccess(string? connectionString) : MongodbAccess(connectionString) where T : new() { /// diff --git a/src/AgileConfig.Server.Data.Mongodb/Repository.cs b/src/AgileConfig.Server.Data.Mongodb/Repository.cs index 5fb35166..70ddb507 100644 --- a/src/AgileConfig.Server.Data.Mongodb/Repository.cs +++ b/src/AgileConfig.Server.Data.Mongodb/Repository.cs @@ -118,8 +118,8 @@ public async Task UpdateAsync(Expression> predicate, var result = await Collection.UpdateManyAsync(predicate, update); return result; } - - public async Task UpdateAsync(T entity) + + private static FilterDefinition GetIdPropertyFilter(T entity) { var idProperty = typeof(T).GetProperty("Id"); if (idProperty == null) @@ -147,64 +147,37 @@ public async Task UpdateAsync(T entity) throw new Exception($"Do not support {idTypeName} type!"); } + return filter; + } + + public async Task UpdateAsync(T entity) + { + var filter = GetIdPropertyFilter(entity); var result = await Collection.ReplaceOneAsync(filter, entity); return result; } - public async Task UpdateAsync(IReadOnlyCollection collection) + public async Task> UpdateAsync(IEnumerable entities) { - var rows = 0L; - foreach (var item in collection) - { - var result = await UpdateAsync(item); - rows += result.ModifiedCount; - } - - return rows; + var writes = entities + .Select(x => new ReplaceOneModel(GetIdPropertyFilter(x), x)) + .ToList(); + return await Collection.BulkWriteAsync(writes); } public ReplaceOneResult Update(T entity) { - var idProperty = typeof(T).GetProperty("Id"); - if (idProperty == null) - throw new ArgumentException("In the entity no exists property 'id'.", nameof(entity)); - var id = idProperty.GetValue(entity); - if (id == null) - throw new ArgumentException("The entity property 'id' value is null.", nameof(entity)); - var idTypeName = idProperty.PropertyType.Name; - FilterDefinition filter; - switch (idTypeName) - { - case "ObjectId": - var definitionObjectId = new StringFieldDefinition("Id"); - filter = Builders.Filter.Eq(definitionObjectId, (ObjectId)id); - break; - case "Int32": - var definitionInt32 = new StringFieldDefinition("Id"); - filter = Builders.Filter.Eq(definitionInt32, (int)id); - break; - case "String": - var definitionString = new StringFieldDefinition("Id"); - filter = Builders.Filter.Eq(definitionString, (string)id); - break; - default: - throw new Exception($"Do not support {idTypeName} type!"); - } - + var filter = GetIdPropertyFilter(entity); var result = Collection.ReplaceOne(filter, entity); return result; } - public long Update(IReadOnlyCollection collection) + public BulkWriteResult Update(IEnumerable entities) { - var rows = 0L; - foreach (var item in collection) - { - var result = Update(item); - rows += result.ModifiedCount; - } - - return rows; + var writes = entities + .Select(x => new ReplaceOneModel(GetIdPropertyFilter(x), x)) + .ToList(); + return Collection.BulkWrite(writes); } From a93d2ad213a4783c9e588e2fd573d561dadd1ca8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Fri, 15 Dec 2023 16:09:25 +0800 Subject: [PATCH 04/45] =?UTF-8?q?mongodb=E5=AD=98=E5=82=A8=E7=9A=84?= =?UTF-8?q?=E6=98=AFUTC=E6=97=B6=E9=97=B4=EF=BC=8C=E7=9B=AE=E5=89=8D?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E5=8F=96=E5=87=BA=E6=97=B6=E4=B8=BA=20?= =?UTF-8?q?=E6=9C=AC=E5=9C=B0=E6=97=B6=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AgileConfig.Server.Data.Entity.csproj | 1 + src/AgileConfig.Server.Data.Entity/App.cs | 3 +++ src/AgileConfig.Server.Data.Entity/Config.cs | 3 +++ src/AgileConfig.Server.Data.Entity/ConfigPublished.cs | 2 ++ src/AgileConfig.Server.Data.Entity/PublishTimeline.cs | 2 ++ src/AgileConfig.Server.Data.Entity/ServerNode.cs | 3 +++ src/AgileConfig.Server.Data.Entity/ServiceInfo.cs | 3 +++ src/AgileConfig.Server.Data.Entity/Setting.cs | 2 ++ src/AgileConfig.Server.Data.Entity/SysLog.cs | 2 ++ src/AgileConfig.Server.Data.Entity/User.cs | 3 +++ src/AgileConfig.Server.Data.Entity/UserRole.cs | 2 ++ 11 files changed, 26 insertions(+) diff --git a/src/AgileConfig.Server.Data.Entity/AgileConfig.Server.Data.Entity.csproj b/src/AgileConfig.Server.Data.Entity/AgileConfig.Server.Data.Entity.csproj index 2f74890f..4c0540b2 100644 --- a/src/AgileConfig.Server.Data.Entity/AgileConfig.Server.Data.Entity.csproj +++ b/src/AgileConfig.Server.Data.Entity/AgileConfig.Server.Data.Entity.csproj @@ -6,6 +6,7 @@ + diff --git a/src/AgileConfig.Server.Data.Entity/App.cs b/src/AgileConfig.Server.Data.Entity/App.cs index a6c4f975..9fea9148 100644 --- a/src/AgileConfig.Server.Data.Entity/App.cs +++ b/src/AgileConfig.Server.Data.Entity/App.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Text; +using MongoDB.Bson.Serialization.Attributes; namespace AgileConfig.Server.Data.Entity { @@ -41,9 +42,11 @@ public class App: IAppModel public string Secret { get; set; } [Column(Name = "create_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime CreateTime { get; set; } [Column(Name = "update_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime? UpdateTime { get; set; } [Column(Name = "enabled")] diff --git a/src/AgileConfig.Server.Data.Entity/Config.cs b/src/AgileConfig.Server.Data.Entity/Config.cs index 6dd8c461..4cca12ee 100644 --- a/src/AgileConfig.Server.Data.Entity/Config.cs +++ b/src/AgileConfig.Server.Data.Entity/Config.cs @@ -1,5 +1,6 @@ using FreeSql.DataAnnotations; using System; +using MongoDB.Bson.Serialization.Attributes; namespace AgileConfig.Server.Data.Entity { @@ -59,9 +60,11 @@ public class Config public string Description { get; set; } [Column(Name = "create_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime CreateTime { get; set; } [Column(Name = "update_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime? UpdateTime { get; set; } [Column(Name = "status")] diff --git a/src/AgileConfig.Server.Data.Entity/ConfigPublished.cs b/src/AgileConfig.Server.Data.Entity/ConfigPublished.cs index 19c5a9f8..b6126101 100644 --- a/src/AgileConfig.Server.Data.Entity/ConfigPublished.cs +++ b/src/AgileConfig.Server.Data.Entity/ConfigPublished.cs @@ -1,5 +1,6 @@ using FreeSql.DataAnnotations; using System; +using MongoDB.Bson.Serialization.Attributes; namespace AgileConfig.Server.Data.Entity { @@ -22,6 +23,7 @@ public class ConfigPublished public string Value { get; set; } [Column(Name = "publish_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime? PublishTime { get; set; } [Column(Name = "config_id", StringLength = 36)] diff --git a/src/AgileConfig.Server.Data.Entity/PublishTimeline.cs b/src/AgileConfig.Server.Data.Entity/PublishTimeline.cs index 10239b84..2b980b50 100644 --- a/src/AgileConfig.Server.Data.Entity/PublishTimeline.cs +++ b/src/AgileConfig.Server.Data.Entity/PublishTimeline.cs @@ -1,5 +1,6 @@ using FreeSql.DataAnnotations; using System; +using MongoDB.Bson.Serialization.Attributes; namespace AgileConfig.Server.Data.Entity { @@ -14,6 +15,7 @@ public class PublishTimeline public string AppId { get; set; } [Column(Name = "publish_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime? PublishTime { get; set; } [Column(Name = "publish_user_id", StringLength = 36)] diff --git a/src/AgileConfig.Server.Data.Entity/ServerNode.cs b/src/AgileConfig.Server.Data.Entity/ServerNode.cs index feee6ba9..5d49a3a2 100644 --- a/src/AgileConfig.Server.Data.Entity/ServerNode.cs +++ b/src/AgileConfig.Server.Data.Entity/ServerNode.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Text; +using MongoDB.Bson.Serialization.Attributes; namespace AgileConfig.Server.Data.Entity { @@ -29,9 +30,11 @@ public class ServerNode public NodeStatus Status { get; set; } [Column(Name = "last_echo_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime? LastEchoTime { get; set; } [Column(Name = "create_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime CreateTime { get; set; } } } diff --git a/src/AgileConfig.Server.Data.Entity/ServiceInfo.cs b/src/AgileConfig.Server.Data.Entity/ServiceInfo.cs index 19d50bf8..8b3ca074 100644 --- a/src/AgileConfig.Server.Data.Entity/ServiceInfo.cs +++ b/src/AgileConfig.Server.Data.Entity/ServiceInfo.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Text; +using MongoDB.Bson.Serialization.Attributes; namespace AgileConfig.Server.Data.Entity { @@ -50,9 +51,11 @@ public class ServiceInfo public ServiceStatus Status { get; set; } [Column(Name = "register_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime? RegisterTime { get; set; } [Column(Name = "last_heart_beat")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime? LastHeartBeat { get; set; } [Column(Name = "heart_beat_mode",StringLength = 10)] diff --git a/src/AgileConfig.Server.Data.Entity/Setting.cs b/src/AgileConfig.Server.Data.Entity/Setting.cs index 7c5fd3e2..8878fd5f 100644 --- a/src/AgileConfig.Server.Data.Entity/Setting.cs +++ b/src/AgileConfig.Server.Data.Entity/Setting.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Text; +using MongoDB.Bson.Serialization.Attributes; namespace AgileConfig.Server.Data.Entity { @@ -16,6 +17,7 @@ public class Setting public string Value { get; set; } [Column(Name = "create_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime CreateTime { get; set; } } } diff --git a/src/AgileConfig.Server.Data.Entity/SysLog.cs b/src/AgileConfig.Server.Data.Entity/SysLog.cs index 81eeb597..0b4938ee 100644 --- a/src/AgileConfig.Server.Data.Entity/SysLog.cs +++ b/src/AgileConfig.Server.Data.Entity/SysLog.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Text; +using MongoDB.Bson.Serialization.Attributes; namespace AgileConfig.Server.Data.Entity { @@ -25,6 +26,7 @@ public class SysLog public SysLogType LogType { get; set; } [Column(Name = "log_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime? LogTime { get; set; } [Column(Name = "log_text", StringLength = 2000)] diff --git a/src/AgileConfig.Server.Data.Entity/User.cs b/src/AgileConfig.Server.Data.Entity/User.cs index 5e04ab4f..4f3d000b 100644 --- a/src/AgileConfig.Server.Data.Entity/User.cs +++ b/src/AgileConfig.Server.Data.Entity/User.cs @@ -1,5 +1,6 @@ using FreeSql.DataAnnotations; using System; +using MongoDB.Bson.Serialization.Attributes; namespace AgileConfig.Server.Data.Entity { @@ -23,9 +24,11 @@ public class User public string Team { get; set; } [Column(Name = "create_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime CreateTime { get; set; } [Column(Name = "update_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime? UpdateTime { get; set; } [Column(Name = "status")] diff --git a/src/AgileConfig.Server.Data.Entity/UserRole.cs b/src/AgileConfig.Server.Data.Entity/UserRole.cs index 04e902a1..d03f9a5b 100644 --- a/src/AgileConfig.Server.Data.Entity/UserRole.cs +++ b/src/AgileConfig.Server.Data.Entity/UserRole.cs @@ -1,6 +1,7 @@ using FreeSql.DataAnnotations; using System; using System.ComponentModel; +using MongoDB.Bson.Serialization.Attributes; namespace AgileConfig.Server.Data.Entity { @@ -18,6 +19,7 @@ public class UserRole public Role Role { get; set; } [Column(Name = "create_time")] + [BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime CreateTime { get; set; } } From 4da434142d9a1da6de3947fc0f18248bcda074a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Fri, 15 Dec 2023 17:30:38 +0800 Subject: [PATCH 05/45] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AgileConfig.sln | 7 + .../MongodbAccess.cs | 8 + ...leConfig.Server.Mongodb.ServiceTest.csproj | 27 + .../AppServiceTests.cs | 336 +++++++ .../ConfigServiceTests.cs | 834 ++++++++++++++++++ .../DatabaseFixture.cs | 24 + .../GlobalUsings.cs | 6 + 7 files changed, 1242 insertions(+) create mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/AgileConfig.Server.Mongodb.ServiceTest.csproj create mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/AppServiceTests.cs create mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/ConfigServiceTests.cs create mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs create mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/GlobalUsings.cs diff --git a/AgileConfig.sln b/AgileConfig.sln index 4a5c89f4..0df69c50 100644 --- a/AgileConfig.sln +++ b/AgileConfig.sln @@ -42,6 +42,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Mon EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Mongodb.Service", "src\AgileConfig.Server.Mongodb.Service\AgileConfig.Server.Mongodb.Service.csproj", "{375B1F54-11CA-415D-ADCC-3B14684AE1DB}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Mongodb.ServiceTest", "test\AgileConfig.Server.Mongodb.ServiceTest\AgileConfig.Server.Mongodb.ServiceTest.csproj", "{E35504A4-E032-4EEA-A53A-12C99B56680B}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -100,6 +102,10 @@ Global {375B1F54-11CA-415D-ADCC-3B14684AE1DB}.Debug|Any CPU.Build.0 = Debug|Any CPU {375B1F54-11CA-415D-ADCC-3B14684AE1DB}.Release|Any CPU.ActiveCfg = Release|Any CPU {375B1F54-11CA-415D-ADCC-3B14684AE1DB}.Release|Any CPU.Build.0 = Release|Any CPU + {E35504A4-E032-4EEA-A53A-12C99B56680B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E35504A4-E032-4EEA-A53A-12C99B56680B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E35504A4-E032-4EEA-A53A-12C99B56680B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E35504A4-E032-4EEA-A53A-12C99B56680B}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -118,6 +124,7 @@ Global {E49A2006-6D07-4434-AEC1-27E356A767AE} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {4803646E-8327-4F69-8BA5-2244CB58BBA2} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {375B1F54-11CA-415D-ADCC-3B14684AE1DB} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} + {E35504A4-E032-4EEA-A53A-12C99B56680B} = {F277EC27-8C0E-4490-9645-F5F3244F9246} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {7F10DB58-5B6F-4EAC-994F-14E8046B306F} diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs index 2d87d624..efa67da0 100644 --- a/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbAccess.cs @@ -16,7 +16,15 @@ public abstract class MongodbAccess internal MongodbAccess(string? connectionString) { if (string.IsNullOrEmpty(connectionString)) + { + if (!LazyMongoClients.Value.IsEmpty) + { + _connectionString = LazyMongoClients.Value.First().Key; + return; + } throw new Exception("没有配置Mongodb连接字符串"); + } + _connectionString = connectionString; if (LazyMongoClients is not { IsValueCreated: true } || !LazyMongoClients.Value.ContainsKey(connectionString)) { diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/AgileConfig.Server.Mongodb.ServiceTest.csproj b/test/AgileConfig.Server.Mongodb.ServiceTest/AgileConfig.Server.Mongodb.ServiceTest.csproj new file mode 100644 index 00000000..357327f6 --- /dev/null +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/AgileConfig.Server.Mongodb.ServiceTest.csproj @@ -0,0 +1,27 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/AppServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/AppServiceTests.cs new file mode 100644 index 00000000..66300ec8 --- /dev/null +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/AppServiceTests.cs @@ -0,0 +1,336 @@ +namespace AgileConfig.Server.Mongodb.ServiceTest; + +[TestFixture] +public class AppServiceTests : DatabaseFixture +{ + private IAppService service; + + [SetUp] + public void TestInitialize() + { + service = new AppService(AppRepository, AppInheritancedRepository, ConfigRepository, ConfigPublishedRepository, + UserAppAuthRepository, UserRepository); + } + + [Test] + public async Task AddAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new App + { + Id = id, + Name = "xx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true + }; + var result = await service.AddAsync(source); + var app = await AppRepository.FindAsync(id); + + Assert.IsTrue(result); + Assert.IsNotNull(app); + + Assert.AreEqual(source.Id, app.Id); + Assert.AreEqual(source.Name, app.Name); + Assert.AreEqual(source.Secret, app.Secret); + Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), app.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), app.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.Enabled, app.Enabled); + } + + [Test] + public async Task DeleteAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Data.Entity.App + { + Id = id, + Name = "xx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true + }; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + var delResult = await service.DeleteAsync(source); + Assert.IsTrue(delResult); + + var app = await AppRepository.FindAsync(id); + Assert.IsNull(app); + } + + [Test] + public async Task DeleteAsyncTest1() + { + var id = Guid.NewGuid().ToString(); + var source = new Data.Entity.App + { + Id = id, + Name = "xx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true + }; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + var delResult = await service.DeleteAsync(id); + Assert.IsTrue(delResult); + + var app = await AppRepository.FindAsync(id); + Assert.IsNull(app); + } + + [Test] + public async Task GetAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Data.Entity.App + { + Id = id, + Name = "xx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true + }; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + var app = await service.GetAsync(id); + Assert.IsNotNull(app); + + Assert.AreEqual(source.Id, app.Id); + Assert.AreEqual(source.Name, app.Name); + Assert.AreEqual(source.Secret, app.Secret); + Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), app.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), app.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.Enabled, app.Enabled); + } + + [Test] + public async Task GetAllAppsAsyncTest() + { + await AppRepository.DeleteAsync(x => true); + var id = Guid.NewGuid().ToString(); + var source = new Data.Entity.App + { + Id = id, + Name = "xx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true + }; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + var id1 = Guid.NewGuid().ToString(); + var source1 = new Data.Entity.App + { + Id = id1, + Name = "xx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true + }; + var result1 = await service.AddAsync(source1); + Assert.IsTrue(result1); + + var apps = await service.GetAllAppsAsync(); + Assert.IsNotNull(apps); + Assert.AreEqual(2, apps.Count); + } + + [Test] + public async Task UpdateAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Data.Entity.App + { + Id = id, + Name = "xx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true + }; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + source.Name = "new name"; + source.Secret = "new sec"; + source.CreateTime = DateTime.Now.AddDays(1); + source.UpdateTime = DateTime.Now.AddDays(1); + source.Enabled = false; + + var result1 = await service.UpdateAsync(source); + Assert.IsTrue(result1); + + var app = await AppRepository.FindAsync(id); + + Assert.AreEqual(source.Id, app.Id); + Assert.AreEqual(source.Name, app.Name); + Assert.AreEqual(source.Secret, app.Secret); + Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), app.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), app.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.Enabled, app.Enabled); + } + + [Test] + public async Task CountEnabledAppsAsyncTest() + { + await AppRepository.DeleteAsync(x => true); + var id = Guid.NewGuid().ToString(); + var source = new Data.Entity.App + { + Id = id, + Name = "xx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true + }; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + var id1 = Guid.NewGuid().ToString(); + var source1 = new Data.Entity.App + { + Id = id1, + Name = "xx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = false + }; + var result1 = await service.AddAsync(source1); + Assert.IsTrue(result1); + + var count = await service.CountEnabledAppsAsync(); + Assert.AreEqual(1, count); + } + + [Test] + public async Task GetAllInheritancedAppsAsyncTest() + { + await AppRepository.DeleteAsync(x => true); + var id = Guid.NewGuid().ToString(); + var source = new Data.Entity.App + { + Id = id, + Name = "xx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true, + Type = AppType.PRIVATE + }; + var source1 = new Data.Entity.App + { + Id = Guid.NewGuid().ToString(), + Name = "xxx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true, + Type = AppType.PRIVATE + }; + var source2 = new Data.Entity.App + { + Id = Guid.NewGuid().ToString(), + Name = "xxxx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true, + Type = AppType.Inheritance + }; + var source3 = new Data.Entity.App + { + Id = Guid.NewGuid().ToString(), + Name = "xxxx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = false, + Type = AppType.Inheritance + }; + var result = await service.AddAsync(source); + await service.AddAsync(source1); + await service.AddAsync(source2); + await service.AddAsync(source3); + + Assert.IsTrue(result); + + var apps = await service.GetAllInheritancedAppsAsync(); + + Assert.AreEqual(2, apps.Count); + } + + [Test] + public async Task GetInheritancedAppsAsyncTest() + { + await AppRepository.DeleteAsync(x => true); + await AppInheritancedRepository.DeleteAsync(x => true); + + var id = Guid.NewGuid().ToString(); + var source = new Data.Entity.App + { + Id = id, + Name = "xx", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true, + Type = AppType.PRIVATE + }; + var source1 = new Data.Entity.App + { + Id = Guid.NewGuid().ToString(), + Name = "xx1", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true, + Type = AppType.Inheritance + }; + var source2 = new Data.Entity.App + { + Id = Guid.NewGuid().ToString(), + Name = "xx2", + Secret = "sec", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Enabled = true, + Type = AppType.Inheritance + }; + // + var appInher = new AppInheritanced(); + appInher.Id = Guid.NewGuid().ToString(); + appInher.AppId = source.Id; + appInher.InheritancedAppId = source1.Id; + appInher.Sort = 1; + var appInher1 = new AppInheritanced(); + appInher1.Id = Guid.NewGuid().ToString(); + appInher1.AppId = source.Id; + appInher1.InheritancedAppId = source2.Id; + appInher1.Sort = 2; + + var result = await service.AddAsync(source); + await service.AddAsync(source1); + await service.AddAsync(source2); + + await AppInheritancedRepository.InsertAsync(appInher); + await AppInheritancedRepository.InsertAsync(appInher1); + + Assert.IsTrue(result); + + var apps = await service.GetInheritancedAppsAsync(source.Id); + + Assert.AreEqual(2, apps.Count); + } +} \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/ConfigServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/ConfigServiceTests.cs new file mode 100644 index 00000000..ebc88761 --- /dev/null +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/ConfigServiceTests.cs @@ -0,0 +1,834 @@ +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Configuration; + +namespace AgileConfig.Server.Mongodb.ServiceTest; + +public class ConfigServiceTests : DatabaseFixture +{ + private IConfigService service; + + [SetUp] + public async Task TestInitialize() + { + var cache = new Mock(); + var configuration = new Mock(); + var appService = new AppService(AppRepository, AppInheritancedRepository, ConfigRepository, + ConfigPublishedRepository, + UserAppAuthRepository, UserRepository); + var settingService = new SettingService(SettingRepository, UserRepository, UserRoleRepository); + var userService = new UserService(UserRepository, UserRoleRepository); + service = new ConfigService(configuration.Object, cache.Object, appService, settingService, userService); + + await ConfigRepository.DeleteAsync(x => true); + } + + [Test] + public async Task AddAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var config = await ConfigRepository.FindAsync(id); + + Assert.IsTrue(result); + Assert.IsNotNull(config); + + Assert.AreEqual(source.Id, config.Id); + Assert.AreEqual(source.Group, config.Group); + Assert.AreEqual(source.Key, config.Key); + Assert.AreEqual(source.Value, config.Value); + Assert.AreEqual(source.Description, config.Description); + Assert.AreEqual(source.AppId, config.AppId); + Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), config.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), config.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.Status, config.Status); + Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); + } + + [Test] + public async Task UpdateAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + + source.AppId = "1"; + source.Group = "1"; + source.Key = "1"; + source.Value = "1"; + source.Description = "1"; + source.CreateTime = DateTime.Now; + source.UpdateTime = DateTime.Now; + source.Status = ConfigStatus.Enabled; + source.OnlineStatus = OnlineStatus.WaitPublish; + + var result1 = await service.UpdateAsync(source, ""); + var config = await ConfigRepository.FindAsync(id); + + Assert.IsTrue(result1); + Assert.IsNotNull(config); + + Assert.AreEqual(source.Id, config.Id); + Assert.AreEqual(source.Group, config.Group); + Assert.AreEqual(source.Key, config.Key); + Assert.AreEqual(source.Value, config.Value); + Assert.AreEqual(source.Description, config.Description); + Assert.AreEqual(source.AppId, config.AppId); + Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), config.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), config.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.Status, config.Status); + Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); + } + + [Test] + public async Task DeleteAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + + var result1 = await service.DeleteAsync(source, ""); + Assert.IsTrue(result1); + + var config = await ConfigRepository.FindAsync(id); + + Assert.IsNull(config); + } + + [Test] + public async Task DeleteAsyncTest1() + { + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + + var result1 = await service.DeleteAsync(id, ""); + Assert.IsTrue(result1); + + var config = await ConfigRepository.FindAsync(id); + + Assert.IsNull(config); + } + + [Test] + public async Task GetAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + + var config = await service.GetAsync(id, ""); + Assert.IsNotNull(config); + + Assert.AreEqual(source.Id, config.Id); + Assert.AreEqual(source.Group, config.Group); + Assert.AreEqual(source.Key, config.Key); + Assert.AreEqual(source.Value, config.Value); + Assert.AreEqual(source.Description, config.Description); + Assert.AreEqual(source.AppId, config.AppId); + Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), config.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), config.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.Status, config.Status); + Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); + } + + [Test] + public async Task GetAllConfigsAsyncTest() + { + await ConfigRepository.DeleteAsync(x => true); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + Env = "", + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + Env = "", + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + + var configs = await service.GetAllConfigsAsync(""); + Assert.IsNotNull(configs); + Assert.AreEqual(1, configs.Count); + } + + [Test] + public async Task GetByAppIdKeyTest() + { + await ConfigRepository.DeleteAsync(x => true); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + Env = "env", + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + Env = "env", + OnlineStatus = OnlineStatus.Online + }; + var id2 = Guid.NewGuid().ToString(); + var source2 = new Config + { + AppId = "002", + Id = id2, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + Env = "env", + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, "env"); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, "env"); + Assert.IsTrue(result1); + var result2 = await service.AddAsync(source2, "env"); + Assert.IsTrue(result2); + + var config = await service.GetByAppIdKeyEnv("001", "g", "k", "env"); + Assert.IsNotNull(config); + + var config1 = await service.GetByAppIdKeyEnv("002", "g", "k", "env"); + Assert.IsNull(config1); + } + + [Test] + public async Task GetByAppIdTest() + { + await ConfigRepository.DeleteAsync(x => true); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + Env = "", + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + Env = "", + OnlineStatus = OnlineStatus.Online + }; + var id2 = Guid.NewGuid().ToString(); + var source2 = new Config + { + AppId = "002", + Id = id2, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + Env = "", + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + var result2 = await service.AddAsync(source2, ""); + Assert.IsTrue(result2); + + var configs = await service.GetByAppIdAsync("001", ""); + Assert.IsNotNull(configs); + Assert.AreEqual(1, configs.Count); + } + + [Test] + public async Task SearchTest() + { + await ConfigRepository.DeleteAsync(x => true); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "group", + Key = "key", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var id2 = Guid.NewGuid().ToString(); + var source2 = new Config + { + AppId = "002", + Id = id2, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + var result2 = await service.AddAsync(source2, ""); + Assert.IsTrue(result2); + + var configs = await service.Search("001", "", "", ""); + Assert.IsNotNull(configs); + Assert.AreEqual(1, configs.Count); + var configs1 = await service.Search("", "o", "", ""); + Assert.IsNotNull(configs1); + Assert.AreEqual(1, configs1.Count); + var configs2 = await service.Search("", "", "e", ""); + Assert.IsNotNull(configs2); + Assert.AreEqual(1, configs2.Count); + } + + [Test] + public async Task CountEnabledConfigsAsyncTest() + { + await ConfigRepository.DeleteAsync(x => true); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "group", + Key = "key", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var id2 = Guid.NewGuid().ToString(); + var source2 = new Config + { + AppId = "002", + Id = id2, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + var result2 = await service.AddAsync(source2, ""); + Assert.IsTrue(result2); + + var count = await service.CountEnabledConfigsAsync(); + Assert.AreEqual(1, count); + } + + [Test] + public async Task AppPublishedConfigsMd5Test() + { + await ConfigRepository.DeleteAsync(x => true); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "group", + Key = "key", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var id2 = Guid.NewGuid().ToString(); + var source2 = new Config + { + AppId = "002", + Id = id2, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + var result2 = await service.AddAsync(source2, ""); + Assert.IsTrue(result2); + + var md5 = await service.AppPublishedConfigsMd5("001", ""); + Assert.IsNotNull(md5); + } + + [Test] + public void AppPublishedConfigsMd5CacheTest() + { + } + + [Test] + public async Task GetPublishedConfigsByAppIdTest() + { + await ConfigRepository.DeleteAsync(x => true); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "group", + Key = "key", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var id2 = Guid.NewGuid().ToString(); + var source2 = new Config + { + AppId = "002", + Id = id2, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + var result2 = await service.AddAsync(source2, ""); + Assert.IsTrue(result2); + + //var configs = await service.GetPublishedConfigsByAppId("001"); + //Assert.IsNotNull(configs); + //Assert.AreEqual(1, configs.Count); + } + + [Test] + public async Task AddRangeAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "group", + Key = "key", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + + var result = await service.AddRangeAsync(new List + { + source, + source1 + }, ""); + Assert.IsTrue(result); + + var config = await ConfigRepository.FindAsync(id); + Assert.IsNotNull(config); + var config1 = await ConfigRepository.FindAsync(id1); + Assert.IsNotNull(config1); + } + + [Test] + public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() + { + await AppRepository.DeleteAsync(x => true); + await ConfigRepository.DeleteAsync(x => true); + await AppInheritancedRepository.DeleteAsync(x => true); + + var app = new App(); + app.Id = "001"; + app.Name = "x"; + app.Enabled = true; + app.CreateTime = DateTime.Now; + app.UpdateTime = DateTime.Now; + app.Type = AppType.PRIVATE; + var app1 = new App(); + app1.Id = "002"; + app1.Name = "x"; + app1.Enabled = true; + app1.CreateTime = DateTime.Now; + app1.UpdateTime = DateTime.Now; + app.Type = AppType.Inheritance; + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Key = "k1", + Value = "v1", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var source2 = new Config + { + AppId = "002", + Id = Guid.NewGuid().ToString(), + Key = "k2", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var source3 = new Config + { + AppId = "002", + Id = Guid.NewGuid().ToString(), + Key = "k21", + Value = "v2", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var appref = new AppInheritanced(); + appref.AppId = app.Id; + appref.InheritancedAppId = app1.Id; + appref.Sort = 1; + appref.Id = Guid.NewGuid().ToString(); + + await AppRepository.InsertAsync(app, app1); + await ConfigRepository.InsertAsync(source, source1, source3); + await AppInheritancedRepository.InsertAsync(appref); + + var dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); + Assert.IsNotNull(dict); + Assert.AreEqual(4, dict.Keys.Count); + + Assert.IsTrue(dict.ContainsKey(source.Key)); + Assert.IsTrue(dict.ContainsKey(source1.Key)); + Assert.IsTrue(dict.ContainsKey(source2.Key)); + Assert.IsTrue(dict.ContainsKey(source3.Key)); + + Assert.IsTrue(dict[source.Key].Value == "v"); + Assert.IsTrue(dict[source1.Key].Value == "v1"); + Assert.IsTrue(dict[source2.Key].Value == "v"); + Assert.IsTrue(dict[source3.Key].Value == "v2"); + + var source4 = new Config + { + AppId = "001", + Id = Guid.NewGuid().ToString(), + Key = "k4", + Value = "v3", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var source5 = new Config + { + AppId = "002", + Id = Guid.NewGuid().ToString(), + Key = "k4", + Value = "v2", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + + await ConfigRepository.InsertAsync(source4, source5); + + dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); + Assert.IsNotNull(dict); + Assert.AreEqual(5, dict.Keys.Count); + + var config1 = dict["k4"]; + Assert.AreEqual(source4.Value, config1.Value); + + var app2 = new App(); + app2.Id = "003"; + app2.Name = "x"; + app2.Enabled = true; + app2.CreateTime = DateTime.Now; + app2.UpdateTime = DateTime.Now; + app2.Type = AppType.Inheritance; + await AppRepository.InsertAsync(app2); + var source6 = new Config + { + AppId = "003", + Id = Guid.NewGuid().ToString(), + Key = "k2", + Value = "k4444", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + + await AppInheritancedRepository.DeleteAsync(x => true); + await ConfigRepository.InsertAsync(source6); + await AppInheritancedRepository.InsertAsync(appref); + + + var appref1 = new AppInheritanced(); + appref1.AppId = app.Id; + appref1.InheritancedAppId = app2.Id; + appref1.Sort = 2; + appref1.Id = Guid.NewGuid().ToString(); + await AppInheritancedRepository.InsertAsync(appref1); + dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); + Assert.IsNotNull(dict); + Assert.AreEqual(5, dict.Keys.Count); + + config1 = dict["k2"]; + Assert.AreEqual(source6.Value, config1.Value); + } +} \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs new file mode 100644 index 00000000..a5a39c7e --- /dev/null +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs @@ -0,0 +1,24 @@ +namespace AgileConfig.Server.Mongodb.ServiceTest; + +public class DatabaseFixture +{ + private const string ConnectionString = "mongodb://localhost:27017,localhost:37017/AgileConfig"; + + protected IRepository AppRepository => new Repository(ConnectionString); + + protected IRepository AppInheritancedRepository => + new Repository(ConnectionString); + + protected IRepository ConfigRepository => new Repository(ConnectionString); + + protected IRepository ConfigPublishedRepository => + new Repository(ConnectionString); + + protected IRepository UserAppAuthRepository => new Repository(ConnectionString); + + protected IRepository UserRepository => new Repository(ConnectionString); + + protected IRepository SettingRepository => new Repository(ConnectionString); + + protected IRepository UserRoleRepository => new Repository(ConnectionString); +} \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/GlobalUsings.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/GlobalUsings.cs new file mode 100644 index 00000000..1bf22356 --- /dev/null +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/GlobalUsings.cs @@ -0,0 +1,6 @@ +global using Moq; +global using NUnit.Framework; +global using AgileConfig.Server.Data.Mongodb; +global using AgileConfig.Server.Data.Entity; +global using AgileConfig.Server.IService; +global using AgileConfig.Server.Mongodb.Service; \ No newline at end of file From 143a9ce576c96eaa823c6c08ef14b3b02252d57d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Fri, 15 Dec 2023 17:54:59 +0800 Subject: [PATCH 06/45] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=BD=93=20=E4=B8=BB?= =?UTF-8?q?=E9=94=AE=20=E5=B1=9E=E6=80=A7=E5=90=8D=E4=B8=8D=E4=B8=BAId?= =?UTF-8?q?=E6=97=B6=E4=BA=A7=E7=94=9F=E9=94=99=E8=AF=AF=E7=9A=84=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/AgileConfig.Server.Data.Entity/ServerNode.cs | 1 + .../Repository.cs | 16 +++++++++++----- .../DatabaseFixture.cs | 2 ++ 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/AgileConfig.Server.Data.Entity/ServerNode.cs b/src/AgileConfig.Server.Data.Entity/ServerNode.cs index 5d49a3a2..af1f5788 100644 --- a/src/AgileConfig.Server.Data.Entity/ServerNode.cs +++ b/src/AgileConfig.Server.Data.Entity/ServerNode.cs @@ -20,6 +20,7 @@ public enum NodeStatus [OraclePrimaryKeyName("agc_server_node_pk")] public class ServerNode { + [BsonId] [Column(Name = "address", StringLength = 100, IsPrimary = true)] public string Address { get; set; } diff --git a/src/AgileConfig.Server.Data.Mongodb/Repository.cs b/src/AgileConfig.Server.Data.Mongodb/Repository.cs index 70ddb507..5d866d44 100644 --- a/src/AgileConfig.Server.Data.Mongodb/Repository.cs +++ b/src/AgileConfig.Server.Data.Mongodb/Repository.cs @@ -1,7 +1,9 @@ using System.Linq.Expressions; +using System.Reflection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using MongoDB.Bson; +using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver; using MongoDB.Driver.Linq; @@ -121,26 +123,30 @@ public async Task UpdateAsync(Expression> predicate, private static FilterDefinition GetIdPropertyFilter(T entity) { - var idProperty = typeof(T).GetProperty("Id"); + var idProperty = typeof(T).GetProperty("Id") ?? typeof(T).GetProperties().FirstOrDefault(x => + { + var attribute = x.GetCustomAttribute(typeof(BsonIdAttribute)); + return attribute != null; + }); if (idProperty == null) throw new ArgumentException("In the entity no exists property 'id'.", nameof(entity)); var id = idProperty.GetValue(entity); if (id == null) - throw new ArgumentException("The entity property 'id' value is null.", nameof(entity)); + throw new ArgumentException($"The entity property '{idProperty.Name}' value is null.", nameof(entity)); var idTypeName = idProperty.PropertyType.Name; FilterDefinition filter; switch (idTypeName) { case "ObjectId": - var definitionObjectId = new StringFieldDefinition("Id"); + var definitionObjectId = new StringFieldDefinition(idProperty.Name); filter = Builders.Filter.Eq(definitionObjectId, (ObjectId)id); break; case "Int32": - var definitionInt32 = new StringFieldDefinition("Id"); + var definitionInt32 = new StringFieldDefinition(idProperty.Name); filter = Builders.Filter.Eq(definitionInt32, (int)id); break; case "String": - var definitionString = new StringFieldDefinition("Id"); + var definitionString = new StringFieldDefinition(idProperty.Name); filter = Builders.Filter.Eq(definitionString, (string)id); break; default: diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs index a5a39c7e..7c2b1f89 100644 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs @@ -21,4 +21,6 @@ public class DatabaseFixture protected IRepository SettingRepository => new Repository(ConnectionString); protected IRepository UserRoleRepository => new Repository(ConnectionString); + + protected IRepository ServerNodeRepository => new Repository(ConnectionString); } \ No newline at end of file From 797c3dfc3ad0ce03d7a35ad93c752d4bc88b759b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Fri, 15 Dec 2023 19:13:03 +0800 Subject: [PATCH 07/45] =?UTF-8?q?=E4=BC=98=E5=8C=96=E8=BF=87=E6=BB=A4?= =?UTF-8?q?=E5=99=A8=EF=BC=8CIRepository=20Find=20FindAsync=20=E5=8F=82?= =?UTF-8?q?=E6=95=B0=E7=AD=BE=E5=90=8D=E6=94=B9=E4=B8=BAobject,=E9=80=82?= =?UTF-8?q?=E9=85=8DSysLog=E5=AE=9E=E4=BD=93int=E7=B1=BB=E5=9E=8B=E7=9A=84?= =?UTF-8?q?id?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../IRepository.cs | 4 +- .../Repository.cs | 85 +++++++++---------- .../SysLogService.cs | 34 +++++++- 3 files changed, 73 insertions(+), 50 deletions(-) diff --git a/src/AgileConfig.Server.Data.Mongodb/IRepository.cs b/src/AgileConfig.Server.Data.Mongodb/IRepository.cs index cc939a7b..ba32027f 100644 --- a/src/AgileConfig.Server.Data.Mongodb/IRepository.cs +++ b/src/AgileConfig.Server.Data.Mongodb/IRepository.cs @@ -46,14 +46,14 @@ public interface IRepository /// /// /// - T? Find(string id); + T? Find(object id); /// /// 根据 Id 获取单条记录,不存在将会返回null /// /// /// - Task FindAsync(string id); + Task FindAsync(object id); void Insert(params T[] source); diff --git a/src/AgileConfig.Server.Data.Mongodb/Repository.cs b/src/AgileConfig.Server.Data.Mongodb/Repository.cs index 5d866d44..7ff6f006 100644 --- a/src/AgileConfig.Server.Data.Mongodb/Repository.cs +++ b/src/AgileConfig.Server.Data.Mongodb/Repository.cs @@ -2,7 +2,6 @@ using System.Reflection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; using MongoDB.Driver; using MongoDB.Driver.Linq; @@ -47,28 +46,30 @@ public async IAsyncEnumerable SearchForAsync(FilterDefinition filter) } } - public T? Find(string id) + public T? Find(object id) { - var idProperty = typeof(T).GetProperty("Id"); - if (idProperty != null && idProperty.PropertyType == typeof(string)) - { - var definitionString = new StringFieldDefinition("Id"); - var filter = Builders.Filter.Eq(definitionString, id); - return Collection.Find(filter).SingleOrDefault(); - } - return default; + var filter = GetIdPropertyFilter(id); + return Collection.Find(filter).SingleOrDefault(); } - public async Task FindAsync(string id) + public async Task FindAsync(object id) { - var idProperty = typeof(T).GetProperty("Id"); - if (idProperty != null && idProperty.PropertyType == typeof(string)) - { - var definitionString = new StringFieldDefinition("Id"); - var filter = Builders.Filter.Eq(definitionString, id); - return await (await Collection.FindAsync(filter)).SingleOrDefaultAsync(); - } - return default; + var filter = GetIdPropertyFilter(id); + return await (await Collection.FindAsync(filter)).SingleOrDefaultAsync(); + } + + private static Expression> GetIdPropertyFilter(object idValue) + { + var idProperty = GetIdProperty(); + if (idValue == null) + throw new Exception($"The entity property '{idProperty.Name}' value is null."); + + var parameter = Expression.Parameter(typeof(T), "__q"); + var memberExpress = Expression.Property(parameter, idProperty); + var expression = + Expression.Lambda>(Expression.Equal(memberExpress, Expression.Constant(idValue)),parameter); + + return expression; } public void Insert(params T[] source) @@ -109,9 +110,7 @@ public async Task DeleteAsync(FilterDefinition filter) public async Task DeleteAsync(string id) { - if (typeof(T).GetProperty("Id") == null) - throw new Exception($"type {typeof(T)} no exists property 'id'."); - var filter = Builders.Filter.Eq(new StringFieldDefinition("Id"), id); + var filter = GetIdPropertyFilter(id); return await Collection.DeleteOneAsync(filter); } @@ -120,8 +119,8 @@ public async Task UpdateAsync(Expression> predicate, var result = await Collection.UpdateManyAsync(predicate, update); return result; } - - private static FilterDefinition GetIdPropertyFilter(T entity) + + private static PropertyInfo GetIdProperty() { var idProperty = typeof(T).GetProperty("Id") ?? typeof(T).GetProperties().FirstOrDefault(x => { @@ -129,31 +128,23 @@ private static FilterDefinition GetIdPropertyFilter(T entity) return attribute != null; }); if (idProperty == null) - throw new ArgumentException("In the entity no exists property 'id'.", nameof(entity)); - var id = idProperty.GetValue(entity); - if (id == null) + throw new Exception("In the entity no exists property 'id'."); + return idProperty; + } + + private static Expression> GetIdPropertyFilter(T entity) + { + var idProperty = GetIdProperty(); + var idValue = idProperty.GetValue(entity); + if (idValue == null) throw new ArgumentException($"The entity property '{idProperty.Name}' value is null.", nameof(entity)); - var idTypeName = idProperty.PropertyType.Name; - FilterDefinition filter; - switch (idTypeName) - { - case "ObjectId": - var definitionObjectId = new StringFieldDefinition(idProperty.Name); - filter = Builders.Filter.Eq(definitionObjectId, (ObjectId)id); - break; - case "Int32": - var definitionInt32 = new StringFieldDefinition(idProperty.Name); - filter = Builders.Filter.Eq(definitionInt32, (int)id); - break; - case "String": - var definitionString = new StringFieldDefinition(idProperty.Name); - filter = Builders.Filter.Eq(definitionString, (string)id); - break; - default: - throw new Exception($"Do not support {idTypeName} type!"); - } + + var parameter = Expression.Parameter(typeof(T), "__q"); + var memberExpress = Expression.Property(parameter, idProperty); + var expression = + Expression.Lambda>(Expression.Equal(memberExpress, Expression.Constant(idValue))); - return filter; + return expression; } public async Task UpdateAsync(T entity) diff --git a/src/AgileConfig.Server.Mongodb.Service/SysLogService.cs b/src/AgileConfig.Server.Mongodb.Service/SysLogService.cs index 552d7ea1..3798930f 100644 --- a/src/AgileConfig.Server.Mongodb.Service/SysLogService.cs +++ b/src/AgileConfig.Server.Mongodb.Service/SysLogService.cs @@ -10,16 +10,38 @@ public class SysLogService(IRepository repository) : ISysLogService { public async Task AddRangeAsync(IEnumerable logs) { - await repository.InsertAsync(logs.ToList()); + var insertLogs = logs.ToList(); + var newId = await GenerateIdAsync(); + foreach (var item in insertLogs) + { + item.Id = newId; + newId++; + } + await repository.InsertAsync(insertLogs); return true; } public async Task AddSysLogAsync(SysLog log) { + if (log.Id <= 0) + { + log.Id = await GenerateIdAsync(); + } await repository.InsertAsync(log); return true; } + private async Task GenerateIdAsync() + { + var count = await repository.MongodbQueryable.CountAsync(); + if (count == 0) + { + return 1; + } + var log = await repository.MongodbQueryable.OrderByDescending(x => x.Id).FirstAsync(); + return log.Id + 1; + } + public async Task Count(string appId, SysLogType? logType, DateTime? startTime, DateTime? endTime) { var query = repository.SearchFor(x => true); @@ -77,6 +99,16 @@ public Task> SearchPage(string appId, SysLogType? logType, DateTime query = query.Where(x => x.LogType == logType); } + if (pageIndex <= 0) + { + pageIndex = 1; + } + + if (pageSize <= 0) + { + pageSize = 1; + } + query = query.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize); return query.ToListAsync(); From 3c4b6fd65048b7997e7efe7340fb2b3a2f3b2296 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Fri, 15 Dec 2023 19:13:19 +0800 Subject: [PATCH 08/45] =?UTF-8?q?=E8=A1=A5=E5=AE=8C=E5=8D=95=E5=85=83?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AppServiceTests.cs | 3 +- .../ConfigServiceTests.cs | 1 + .../DatabaseFixture.cs | 2 + .../ServerNodeServiceTests.cs | 163 ++++++++++++++++ .../SettingServiceTests.cs | 182 ++++++++++++++++++ .../SysLogServiceTests.cs | 147 ++++++++++++++ 6 files changed, 497 insertions(+), 1 deletion(-) create mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/ServerNodeServiceTests.cs create mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/SettingServiceTests.cs create mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/SysLogServiceTests.cs diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/AppServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/AppServiceTests.cs index 66300ec8..454370da 100644 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/AppServiceTests.cs +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/AppServiceTests.cs @@ -6,10 +6,11 @@ public class AppServiceTests : DatabaseFixture private IAppService service; [SetUp] - public void TestInitialize() + public async Task TestInitialize() { service = new AppService(AppRepository, AppInheritancedRepository, ConfigRepository, ConfigPublishedRepository, UserAppAuthRepository, UserRepository); + await AppRepository.DeleteAsync(x => true); } [Test] diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/ConfigServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/ConfigServiceTests.cs index ebc88761..275d26af 100644 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/ConfigServiceTests.cs @@ -3,6 +3,7 @@ namespace AgileConfig.Server.Mongodb.ServiceTest; +[TestFixture] public class ConfigServiceTests : DatabaseFixture { private IConfigService service; diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs index 7c2b1f89..5acd6ddd 100644 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs @@ -23,4 +23,6 @@ public class DatabaseFixture protected IRepository UserRoleRepository => new Repository(ConnectionString); protected IRepository ServerNodeRepository => new Repository(ConnectionString); + + protected IRepository SysLogRepository => new Repository(ConnectionString); } \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/ServerNodeServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/ServerNodeServiceTests.cs new file mode 100644 index 00000000..4f5606bc --- /dev/null +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/ServerNodeServiceTests.cs @@ -0,0 +1,163 @@ +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.Mongodb.ServiceTest; + +public class ServerNodeServiceTests : DatabaseFixture +{ + private IServerNodeService service; + + [SetUp] + public async Task TestInitialize() + { + service = new ServerNodeService(ServerNodeRepository); + + await ServerNodeRepository.DeleteAsync(x => true); + + Console.WriteLine("TestInitialize"); + } + + [Test] + public async Task AddAsyncTest() + { + await ServerNodeRepository.DeleteAsync(x => true); + + var source = new ServerNode(); + source.Address = "1"; + source.CreateTime = DateTime.Now; + source.LastEchoTime = DateTime.Now; + source.Remark = "2"; + source.Status = NodeStatus.Offline; + + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + var node = await ServerNodeRepository.SearchFor(x => x.Address == "1").FirstOrDefaultAsync(); + Assert.IsNotNull(node); + + Assert.AreEqual(source.Address, node.Address); + // Assert.AreEqual(source.CreateTime, node.CreateTime); + // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); + Assert.AreEqual(source.Remark, node.Remark); + Assert.AreEqual(source.Status, node.Status); + } + + [Test] + public async Task DeleteAsyncTest() + { + await ServerNodeRepository.DeleteAsync(x => true); + + var source = new ServerNode(); + source.Address = "1"; + source.CreateTime = DateTime.Now; + source.LastEchoTime = DateTime.Now; + source.Remark = "2"; + source.Status = NodeStatus.Offline; + + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + var result1 = await service.DeleteAsync(source); + Assert.IsTrue(result1); + + var node = await ServerNodeRepository.SearchFor(x => x.Address == "1").FirstOrDefaultAsync(); + Assert.IsNull(node); + } + + [Test] + public async Task DeleteAsyncTest1() + { + await ServerNodeRepository.DeleteAsync(x => true); + + var source = new ServerNode(); + source.Address = "1"; + source.CreateTime = DateTime.Now; + source.LastEchoTime = DateTime.Now; + source.Remark = "2"; + source.Status = NodeStatus.Offline; + + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + var result1 = await service.DeleteAsync(source.Address); + Assert.IsTrue(result1); + + var node = await ServerNodeRepository.SearchFor(x => x.Address == "1").FirstOrDefaultAsync(); + Assert.IsNull(node); + } + + [Test] + public async Task GetAllNodesAsyncTest() + { + await ServerNodeRepository.DeleteAsync(x => true); + + var source = new ServerNode(); + source.Address = "1"; + source.CreateTime = DateTime.Now; + source.LastEchoTime = DateTime.Now; + source.Remark = "2"; + source.Status = NodeStatus.Offline; + + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + var nodes = await service.GetAllNodesAsync(); + Assert.IsNotNull(nodes); + + Assert.AreEqual(1, nodes.Count); + } + + [Test] + public async Task GetAsyncTest() + { + await ServerNodeRepository.DeleteAsync(x => true); + + var source = new ServerNode(); + source.Address = "1"; + source.CreateTime = DateTime.Now; + source.LastEchoTime = DateTime.Now; + source.Remark = "2"; + source.Status = NodeStatus.Offline; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + var node = await service.GetAsync(source.Address); + Assert.IsNotNull(node); + + Assert.AreEqual(source.Address, node.Address); + // Assert.AreEqual(source.CreateTime, node.CreateTime); + // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); + Assert.AreEqual(source.Remark, node.Remark); + Assert.AreEqual(source.Status, node.Status); + } + + [Test] + public async Task UpdateAsyncTest() + { + await ServerNodeRepository.DeleteAsync(x => true); + + var source = new ServerNode(); + source.Address = "1"; + source.CreateTime = DateTime.Now; + source.LastEchoTime = DateTime.Now; + source.Remark = "2"; + source.Status = NodeStatus.Offline; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + source.CreateTime = DateTime.Now; + source.LastEchoTime = DateTime.Now; + source.Remark = "3"; + source.Status = NodeStatus.Online; + var result1 = await service.UpdateAsync(source); + Assert.IsTrue(result); + + var node = await service.GetAsync(source.Address); + Assert.IsNotNull(node); + + Assert.AreEqual(source.Address, node.Address); + // Assert.AreEqual(source.CreateTime, node.CreateTime); + // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); + Assert.AreEqual(source.Remark, node.Remark); + Assert.AreEqual(source.Status, node.Status); + } +} \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/SettingServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/SettingServiceTests.cs new file mode 100644 index 00000000..1e54b755 --- /dev/null +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/SettingServiceTests.cs @@ -0,0 +1,182 @@ +namespace AgileConfig.Server.Mongodb.ServiceTest; + +public class SettingServiceTests : DatabaseFixture +{ + private ISettingService service; + + [SetUp] + public async Task TestInitialize() + { + service = new SettingService(SettingRepository, UserRepository, UserRoleRepository); + await SettingRepository.DeleteAsync(x => true); + Console.WriteLine("TestInitialize"); + } + + [Test] + public async Task AddAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Setting(); + source.Id = id; + source.Value = "123"; + source.CreateTime = DateTime.Now; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + var setting = await SettingRepository.FindAsync(id); + + Assert.IsNotNull(setting); + + Assert.AreEqual(source.Id, setting.Id); + Assert.AreEqual(source.Value, setting.Value); + } + + [Test] + public async Task DeleteAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Setting(); + source.Id = id; + source.Value = "123"; + source.CreateTime = DateTime.Now; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + result = await service.DeleteAsync(source); + Assert.IsTrue(result); + + var setting = await SettingRepository.FindAsync(id); + + Assert.IsNull(setting); + } + + [Test] + public async Task DeleteAsyncTest1() + { + var id = Guid.NewGuid().ToString(); + var source = new Setting(); + source.Id = id; + source.Value = "123"; + source.CreateTime = DateTime.Now; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + result = await service.DeleteAsync(id); + Assert.IsTrue(result); + + var setting = await SettingRepository.FindAsync(id); + + Assert.IsNull(setting); + } + + [Test] + public async Task GetAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Setting(); + source.Id = id; + source.Value = "123"; + source.CreateTime = DateTime.Now; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + var setting = await service.GetAsync(id); + + Assert.IsNotNull(setting); + + Assert.AreEqual(source.Id, setting.Id); + Assert.AreEqual(source.Value, setting.Value); + } + + [Test] + public async Task GetAllSettingsAsyncTest() + { + await SettingRepository.DeleteAsync(x => true); + var id = Guid.NewGuid().ToString(); + var source = new Setting(); + source.Id = id; + source.Value = "123"; + source.CreateTime = DateTime.Now; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + var id1 = Guid.NewGuid().ToString(); + var source1 = new Setting(); + source1.Id = id1; + source1.Value = "123"; + source1.CreateTime = DateTime.Now; + var result1 = await service.AddAsync(source1); + Assert.IsTrue(result1); + + var settings = await service.GetAllSettingsAsync(); + + Assert.IsNotNull(settings); + + Assert.AreEqual(2, settings.Count); + } + + [Test] + public async Task UpdateAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Setting(); + source.Id = id; + source.Value = "123"; + source.CreateTime = DateTime.Now; + var result = await service.AddAsync(source); + Assert.IsTrue(result); + + source.CreateTime = DateTime.Now; + source.Value = "321"; + var result1 = await service.UpdateAsync(source); + Assert.IsTrue(result1); + + var setting = await service.GetAsync(id); + Assert.IsNotNull(setting); + + Assert.AreEqual(source.Id, setting.Id); + Assert.AreEqual(source.Value, setting.Value); + } + + [Test] + public async Task SetAdminPasswordTest() + { + //fsq.Delete().Where("1=1").ExecuteAffrows(); + //var result = await service.SetSuperAdminPassword("123456"); + //Assert.IsTrue(result); + //var list = fsq.Select().Where("1=1").ToList(); + //Assert.IsNotNull(list); + //Assert.AreEqual(2, list.Count); + + //var pass = list.FirstOrDefault(s => s.Id == service.SuperAdminPasswordSettingKey); + //Assert.IsNotNull(pass); + //var salt = list.FirstOrDefault(s => s.Id == service.AdminPasswordHashSaltKey); + //Assert.IsNotNull(salt); + } + + [Test] + public async Task HasAdminPasswordTest() + { + //fsq.Delete().Where("1=1").ExecuteAffrows(); + //var result = await service.SetSuperAdminPassword("123456"); + //Assert.IsTrue(result); + + //var has = await service.HasSuperAdminPassword(); + //Assert.IsTrue(has); + //fsq.Delete().Where("1=1").ExecuteAffrows(); + //has = await service.HasSuperAdminPassword(); + //Assert.IsFalse(has); + } + + [Test] + public async Task ValidateAdminPasswordTest() + { + //fsq.Delete().Where("1=1").ExecuteAffrows(); + //var result = await service.SetSuperAdminPassword("123456"); + //Assert.IsTrue(result); + + //var v = await service.ValidateAdminPassword("123456"); + //Assert.IsTrue(v); + //v = await service.ValidateAdminPassword("1234561"); + //Assert.IsFalse(v); + } +} \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/SysLogServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/SysLogServiceTests.cs new file mode 100644 index 00000000..b9870878 --- /dev/null +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/SysLogServiceTests.cs @@ -0,0 +1,147 @@ +namespace AgileConfig.Server.Mongodb.ServiceTest; + +public class SysLogServiceTests : DatabaseFixture +{ + private ISysLogService service; + + [SetUp] + public async Task TestInitialize() + { + service = new SysLogService(SysLogRepository); + await SysLogRepository.DeleteAsync(x => true); + Console.WriteLine("TestInitialize"); + } + + [Test] + public async Task AddSysLogAsyncTest() + { + var source = new SysLog + { + AppId = "001", + LogType = SysLogType.Normal, + LogTime = DateTime.Now, + LogText = "123" + }; + + var result = await service.AddSysLogAsync(source); + Assert.IsTrue(result); + + var log = await SysLogRepository.FindAsync(source.Id); + + Assert.IsNotNull(log); + + Assert.AreEqual(source.Id, log.Id); + Assert.AreEqual(source.AppId, log.AppId); + Assert.AreEqual(source.LogType, log.LogType); + // Assert.AreEqual(source.LogTime, log.LogTime); + Assert.AreEqual(source.LogText, log.LogText); + } + + + [Test] + public async Task AddRangeAsyncTest() + { + var source = new SysLog + { + AppId = "001", + LogType = SysLogType.Normal, + LogTime = DateTime.Now, + LogText = "123" + }; + var source1 = new SysLog + { + AppId = "002", + LogType = SysLogType.Warn, + LogTime = DateTime.Now, + LogText = "124" + }; + var result = await service.AddRangeAsync(new List + { + source, source1 + }); + Assert.IsTrue(result); + + var log = await SysLogRepository.FindAsync(source.Id); + Assert.IsNotNull(log); + Assert.AreEqual(source.Id, log.Id); + Assert.AreEqual(source.AppId, log.AppId); + Assert.AreEqual(source.LogType, log.LogType); + // Assert.AreEqual(source.LogTime, log.LogTime); + Assert.AreEqual(source.LogText, log.LogText); + + var log1 = await SysLogRepository.FindAsync(source1.Id); + Assert.IsNotNull(log1); + Assert.AreEqual(source1.Id, log1.Id); + Assert.AreEqual(source1.AppId, log1.AppId); + Assert.AreEqual(source1.LogType, log1.LogType); + // Assert.AreEqual(source1.LogTime, log1.LogTime); + Assert.AreEqual(source1.LogText, log1.LogText); + } + + + [Test] + public async Task CountTest() + { + await SysLogRepository.DeleteAsync(x => true); + + var source = new SysLog + { + AppId = "001", + LogType = SysLogType.Normal, + LogTime = DateTime.Now, + LogText = "123" + }; + var source1 = new SysLog + { + AppId = "002", + LogType = SysLogType.Warn, + LogTime = DateTime.Now, + LogText = "124" + }; + var result = await service.AddRangeAsync(new List + { + source, source1 + }); + Assert.IsTrue(result); + + var count = await service.Count("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1)); + Assert.AreEqual(1, count); + + var count1 = await service.Count("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1)); + Assert.AreEqual(0, count1); + } + + [Test] + public async Task SearchPageTest() + { + await SysLogRepository.DeleteAsync(x => true); + + var source = new SysLog + { + AppId = "001", + LogType = SysLogType.Normal, + LogTime = DateTime.Now, + LogText = "123" + }; + var source1 = new SysLog + { + AppId = "002", + LogType = SysLogType.Warn, + LogTime = DateTime.Now, + LogText = "124" + }; + var result = await service.AddRangeAsync(new List + { + source, source1 + }); + Assert.IsTrue(result); + + var page = await service.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1), + 1, 0); + Assert.AreEqual(1, page.Count); + + var page1 = await service.SearchPage("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), + 1, 0); + Assert.AreEqual(0, page1.Count); + } +} \ No newline at end of file From a1349b8b8d9b22f2e056b94b731d345565a76df0 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sat, 23 Dec 2023 16:36:34 +0800 Subject: [PATCH 09/45] =?UTF-8?q?=E9=87=8D=E6=9E=84=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E8=AE=BF=E9=97=AE=E6=A8=A1=E5=9D=97=EF=BC=8C=E5=AE=9A=E4=B9=89?= =?UTF-8?q?=20Repository=20=E5=B1=82=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AgileConfig.sln | 16 ++- .../Controllers/AppController.cs | 25 ++-- .../Controllers/ReportController.cs | 6 +- .../Controllers/ServerNodeController.cs | 4 +- .../Controllers/api/NodeController.cs | 2 +- src/AgileConfig.Server.Common/IEntity.cs | 3 +- ...AgileConfig.Server.Data.Abstraction.csproj | 14 ++ .../IAppInheritancedRepository.cs | 8 ++ .../IAppRepository.cs | 8 ++ .../IConfigPublishedRepository.cs | 8 ++ .../IConfigRepository.cs | 8 ++ .../IPublishDetailRepository.cs | 8 ++ .../IPublishTimelineRepository.cs | 8 ++ .../IRepository.cs | 24 ++++ .../IServerNodeRepository.cs | 8 ++ .../IServiceInfoRepository.cs | 8 ++ .../ISettingRepository.cs | 8 ++ .../ISysLogRepository.cs | 8 ++ .../IUserAppAuthRepository.cs | 8 ++ .../IUserRepository.cs | 8 ++ .../IUserRoleRepository.cs | 8 ++ .../AgileConfig.Server.Data.Entity.csproj | 4 + src/AgileConfig.Server.Data.Entity/App.cs | 3 +- .../AppInheritanced.cs | 5 +- src/AgileConfig.Server.Data.Entity/Config.cs | 3 +- .../ConfigPublished.cs | 3 +- .../PublishDetail.cs | 5 +- .../PublishTimeline.cs | 3 +- .../ServerNode.cs | 5 +- .../ServiceInfo.cs | 3 +- src/AgileConfig.Server.Data.Entity/Setting.cs | 5 +- src/AgileConfig.Server.Data.Entity/SysLog.cs | 5 +- src/AgileConfig.Server.Data.Entity/User.cs | 3 +- .../UserAppAuth.cs | 5 +- .../UserRole.cs | 3 +- .../AgileConfig.Server.Data.Freesql.csproj | 1 + .../FreesqlRepository.cs | 71 ++++++++++ ...nfig.Server.Data.Repository.Freesql.csproj | 14 ++ .../AppInheritancedRepository.cs | 13 ++ .../AppRepository.cs | 13 ++ .../ConfigPublishedRepository.cs | 13 ++ .../ConfigRepository.cs | 13 ++ .../PublishDetailRepository.cs | 13 ++ .../PublishTimelineRepository.cs | 13 ++ .../ServerNodeRepository.cs | 13 ++ .../ServiceCollectionExt.cs | 28 ++++ .../ServiceInfoRepository.cs | 13 ++ .../SettingRepository.cs | 13 ++ .../SysLogRepository.cs | 13 ++ .../UserAppAuthRepository.cs | 13 ++ .../UserRepository.cs | 13 ++ .../UserRoleRepository.cs | 13 ++ .../IAppService.cs | 2 +- .../AppService.cs | 4 +- .../ConfigStatusUpdateRegister.cs | 8 +- .../ServiceInfoStatusUpdateRegister.cs | 12 +- .../EventRegisterService/SysLogRegister.cs | 4 +- .../RegisterCenterService.cs | 4 +- .../RemoteServerNodeProxy.cs | 6 +- .../ServerNodeService.cs | 18 +-- .../SettingService.cs | 2 +- .../UserService.cs | 2 +- src/AgileConfig.Server.Service/AppService.cs | 127 +++++++++--------- .../ConfigService.cs | 2 +- .../ConfigStatusUpdateRegister.cs | 15 ++- .../ServiceInfoStatusUpdateRegister.cs | 12 +- .../EventRegisterService/SysLogRegister.cs | 4 +- .../RemoteServerNodeProxy.cs | 6 +- .../ServerNodeService.cs | 16 +-- .../ServerNodeServiceTests.cs | 30 ++--- .../PostgreSQL/AppServiceTests.cs | 3 +- .../PostgreSQL/ConfigServiceTests.cs | 4 +- .../PostgreSQL/ServerNodeServiceTests.cs | 24 ++-- .../mysql/AppServiceTests.cs | 5 +- .../mysql/ConfigServiceTests.cs | 4 +- .../mysql/ServerNodeServiceTests.cs | 24 ++-- .../oracle/AppServiceTests.cs | 5 +- .../oracle/ConfigServiceTests.cs | 4 +- .../oracle/ServerNodeServiceTests.cs | 24 ++-- .../sqlite/AppServiceTests.cs | 3 +- .../sqlite/ConfigServiceTests.cs | 4 +- .../sqlite/ServerNodeServiceTests.cs | 24 ++-- .../sqlserver/AppServiceTests.cs | 3 +- .../sqlserver/ConfigServiceTests.cs | 3 +- .../sqlserver/ServerNodeServiceTests.cs | 30 ++--- 85 files changed, 729 insertions(+), 245 deletions(-) create mode 100644 src/AgileConfig.Server.Data.Abstraction/AgileConfig.Server.Data.Abstraction.csproj create mode 100644 src/AgileConfig.Server.Data.Abstraction/IAppInheritancedRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/IAppRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/IConfigPublishedRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/IConfigRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/IPublishDetailRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/IPublishTimelineRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/IRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/IServerNodeRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/IServiceInfoRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/ISettingRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/ISysLogRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/IUserAppAuthRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/IUserRepository.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/IUserRoleRepository.cs create mode 100644 src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/AgileConfig.Server.Data.Repository.Freesql.csproj create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/ServiceCollectionExt.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs diff --git a/AgileConfig.sln b/AgileConfig.sln index 0df69c50..852b076e 100644 --- a/AgileConfig.sln +++ b/AgileConfig.sln @@ -36,7 +36,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.ServiceT EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.CommonTests", "test\AgileConfig.Server.CommonTests\AgileConfig.Server.CommonTests.csproj", "{70724B0E-7D81-412C-BDA7-747F4845E990}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.OIDC", "src\AgileConfig.Server.OIDC\AgileConfig.Server.OIDC.csproj", "{E49A2006-6D07-4434-AEC1-27E356A767AE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.OIDC", "src\AgileConfig.Server.OIDC\AgileConfig.Server.OIDC.csproj", "{E49A2006-6D07-4434-AEC1-27E356A767AE}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Mongodb", "src\AgileConfig.Server.Data.Mongodb\AgileConfig.Server.Data.Mongodb.csproj", "{4803646E-8327-4F69-8BA5-2244CB58BBA2}" EndProject @@ -44,6 +44,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Mongodb. EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Mongodb.ServiceTest", "test\AgileConfig.Server.Mongodb.ServiceTest\AgileConfig.Server.Mongodb.ServiceTest.csproj", "{E35504A4-E032-4EEA-A53A-12C99B56680B}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Abstraction", "src\AgileConfig.Server.Data.Abstraction\AgileConfig.Server.Data.Abstraction.csproj", "{E8101403-72C9-40FB-BCEE-16ED5C23A495}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Repository.Freesql", "src\AgileConfig.Server.Data.Repository.Freesql\AgileConfig.Server.Data.Repository.Freesql.csproj", "{955F64CC-9EAC-4563-804D-6E2CF9547357}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -106,6 +110,14 @@ Global {E35504A4-E032-4EEA-A53A-12C99B56680B}.Debug|Any CPU.Build.0 = Debug|Any CPU {E35504A4-E032-4EEA-A53A-12C99B56680B}.Release|Any CPU.ActiveCfg = Release|Any CPU {E35504A4-E032-4EEA-A53A-12C99B56680B}.Release|Any CPU.Build.0 = Release|Any CPU + {E8101403-72C9-40FB-BCEE-16ED5C23A495}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E8101403-72C9-40FB-BCEE-16ED5C23A495}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E8101403-72C9-40FB-BCEE-16ED5C23A495}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E8101403-72C9-40FB-BCEE-16ED5C23A495}.Release|Any CPU.Build.0 = Release|Any CPU + {955F64CC-9EAC-4563-804D-6E2CF9547357}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {955F64CC-9EAC-4563-804D-6E2CF9547357}.Debug|Any CPU.Build.0 = Debug|Any CPU + {955F64CC-9EAC-4563-804D-6E2CF9547357}.Release|Any CPU.ActiveCfg = Release|Any CPU + {955F64CC-9EAC-4563-804D-6E2CF9547357}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -125,6 +137,8 @@ Global {4803646E-8327-4F69-8BA5-2244CB58BBA2} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {375B1F54-11CA-415D-ADCC-3B14684AE1DB} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {E35504A4-E032-4EEA-A53A-12C99B56680B} = {F277EC27-8C0E-4490-9645-F5F3244F9246} + {E8101403-72C9-40FB-BCEE-16ED5C23A495} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} + {955F64CC-9EAC-4563-804D-6E2CF9547357} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {7F10DB58-5B6F-4EAC-994F-14E8046B306F} diff --git a/src/AgileConfig.Server.Apisite/Controllers/AppController.cs b/src/AgileConfig.Server.Apisite/Controllers/AppController.cs index a7e8cdc4..0763e55a 100644 --- a/src/AgileConfig.Server.Apisite/Controllers/AppController.cs +++ b/src/AgileConfig.Server.Apisite/Controllers/AppController.cs @@ -53,7 +53,7 @@ public async Task Search(string name, string id, string group, st { query = query.Where(x => x.Group == group).ToList(); } - + var appvms = new List(); foreach (var app in query) { @@ -78,7 +78,7 @@ public async Task Search(string name, string id, string group, st } } - if (children.Count>0) + if (children.Count > 0) { first.children = children; } @@ -87,10 +87,10 @@ public async Task Search(string name, string id, string group, st appvms = appGroupList; } - + if (tableGrouped) { - if ( sortField == "group" && ascOrDesc.StartsWith("desc")) + if (sortField == "group" && ascOrDesc.StartsWith("desc")) { appvms = appvms.OrderByDescending(x => x.Group).ToList(); } @@ -146,7 +146,7 @@ public async Task Search(string name, string id, string group, st } } } - + var count = appvms.Count; var pageList = appvms.ToList().Skip((current - 1) * pageSize).Take(pageSize).ToList(); await AppendInheritancedInfo(pageList); @@ -158,7 +158,7 @@ public async Task Search(string name, string id, string group, st total = count, data = pageList }); - } + } private async Task AppToListVM(App item, bool appendInheritancedInfo) { @@ -203,13 +203,13 @@ private async Task AppendInheritancedInfo(List list) ? new List() : (inheritancedApps).Select(ia => ia.Name).ToList(); appListVm.AppAdminName = (await _userService.GetUserAsync(appListVm.AppAdmin))?.UserName; - if (appListVm.children!=null) + if (appListVm.children != null) { await AppendInheritancedInfo(appListVm.children); } } } - + [TypeFilter(typeof(PremissionCheckAttribute), Arguments = new object[] { "App.Add", Functions.App_Add })] [HttpPost] public async Task Add([FromBody] AppVM model) @@ -309,7 +309,7 @@ public async Task Edit([FromBody] AppVM model) app.Type = model.Inheritanced ? AppType.Inheritance : AppType.PRIVATE; app.AppAdmin = model.AppAdmin; app.Group = model.Group; - + var inheritanceApps = new List(); if (!model.Inheritanced && model.inheritancedApps != null) { @@ -546,7 +546,7 @@ public async Task GetUserAppAuth(string appId) { AppId = appId }; - result.EditConfigPermissionUsers = (await _appService.GetUserAppAuth(appId, _premissionService.EditConfigPermissionKey)).Select(x=>x.Id).ToList(); + result.EditConfigPermissionUsers = (await _appService.GetUserAppAuth(appId, _premissionService.EditConfigPermissionKey)).Select(x => x.Id).ToList(); result.PublishConfigPermissionUsers = (await _appService.GetUserAppAuth(appId, _premissionService.PublishConfigPermissionKey)).Select(x => x.Id).ToList(); return Json(new @@ -557,12 +557,13 @@ public async Task GetUserAppAuth(string appId) } [HttpGet] - public IActionResult GetAppGroups() + public async Task GetAppGroups() { + var groups = await _appService.GetAppGroups(); return Json(new { success = true, - data = _appService.GetAppGroups().OrderBy(x=>x) + data = groups.OrderBy(x => x) }); } } diff --git a/src/AgileConfig.Server.Apisite/Controllers/ReportController.cs b/src/AgileConfig.Server.Apisite/Controllers/ReportController.cs index dff408b7..e4e82399 100644 --- a/src/AgileConfig.Server.Apisite/Controllers/ReportController.cs +++ b/src/AgileConfig.Server.Apisite/Controllers/ReportController.cs @@ -73,11 +73,11 @@ public async Task SearchServerNodeClients(string address, int cur var nodes = await _serverNodeService.GetAllNodesAsync(); if (string.IsNullOrEmpty(address)) { - addressess.AddRange(nodes.Where(x=>x.Status == NodeStatus.Online).Select(n => n.Address)); + addressess.AddRange(nodes.Where(x=>x.Status == NodeStatus.Online).Select(n => n.Id.ToString())); } else { - if (nodes.Any(x=>x.Status == NodeStatus.Online && x.Address.Equals(address, StringComparison.CurrentCultureIgnoreCase))) + if (nodes.Any(x=>x.Status == NodeStatus.Online && x.Id.ToString().Equals(address, StringComparison.CurrentCultureIgnoreCase))) { addressess.Add(address); } @@ -162,7 +162,7 @@ public async Task RemoteNodesStatus() result.Add(new { n = serverNode, - server_status = await _remoteServerNodeProxy.GetClientsReportAsync(serverNode.Address) + server_status = await _remoteServerNodeProxy.GetClientsReportAsync(serverNode.Id.ToString()) }); } diff --git a/src/AgileConfig.Server.Apisite/Controllers/ServerNodeController.cs b/src/AgileConfig.Server.Apisite/Controllers/ServerNodeController.cs index 7a1a4d33..53c2eb70 100644 --- a/src/AgileConfig.Server.Apisite/Controllers/ServerNodeController.cs +++ b/src/AgileConfig.Server.Apisite/Controllers/ServerNodeController.cs @@ -50,7 +50,7 @@ public async Task Add([FromBody]ServerNodeVM model) } var node = new ServerNode(); - node.Address = model.Address.TrimEnd('/'); + node.Id = model.Address.TrimEnd('/'); node.Remark = model.Remark; node.Status = NodeStatus.Offline; node.CreateTime = DateTime.Now; @@ -62,7 +62,7 @@ public async Task Add([FromBody]ServerNodeVM model) param.node = node; param.userName = this.GetCurrentUserName(); TinyEventBus.Instance.Fire(EventKeys.ADD_NODE_SUCCESS, param); - await _remoteServerNodeProxy.TestEchoAsync(node.Address); + await _remoteServerNodeProxy.TestEchoAsync(node.Id); } return Json(new diff --git a/src/AgileConfig.Server.Apisite/Controllers/api/NodeController.cs b/src/AgileConfig.Server.Apisite/Controllers/api/NodeController.cs index eec6eb85..bd754487 100644 --- a/src/AgileConfig.Server.Apisite/Controllers/api/NodeController.cs +++ b/src/AgileConfig.Server.Apisite/Controllers/api/NodeController.cs @@ -38,7 +38,7 @@ public async Task>> GetAll() var vms = nodes.Select(x=> new ApiNodeVM { - Address = x.Address, + Address = x.Id, Remark = x.Remark, LastEchoTime = x.LastEchoTime, Status= x.Status diff --git a/src/AgileConfig.Server.Common/IEntity.cs b/src/AgileConfig.Server.Common/IEntity.cs index 203a33ea..65ab2035 100644 --- a/src/AgileConfig.Server.Common/IEntity.cs +++ b/src/AgileConfig.Server.Common/IEntity.cs @@ -2,7 +2,8 @@ namespace AgileConfig.Server.Common { - public interface IEntity + public interface IEntity { + T Id { get; set; } } } diff --git a/src/AgileConfig.Server.Data.Abstraction/AgileConfig.Server.Data.Abstraction.csproj b/src/AgileConfig.Server.Data.Abstraction/AgileConfig.Server.Data.Abstraction.csproj new file mode 100644 index 00000000..ef10d473 --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/AgileConfig.Server.Data.Abstraction.csproj @@ -0,0 +1,14 @@ + + + + net8.0 + enable + enable + + + + + + + + diff --git a/src/AgileConfig.Server.Data.Abstraction/IAppInheritancedRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IAppInheritancedRepository.cs new file mode 100644 index 00000000..122f2625 --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IAppInheritancedRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IAppInheritancedRepository : IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/IAppRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IAppRepository.cs new file mode 100644 index 00000000..a3c4bfcb --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IAppRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IAppRepository: IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/IConfigPublishedRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IConfigPublishedRepository.cs new file mode 100644 index 00000000..b833da5c --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IConfigPublishedRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IConfigPublishedRepository : IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/IConfigRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IConfigRepository.cs new file mode 100644 index 00000000..062bc4c1 --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IConfigRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IConfigRepository : IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/IPublishDetailRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IPublishDetailRepository.cs new file mode 100644 index 00000000..06319df8 --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IPublishDetailRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IPublishDetailRepository : IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/IPublishTimelineRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IPublishTimelineRepository.cs new file mode 100644 index 00000000..8c6154fb --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IPublishTimelineRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IPublishTimelineRepository : IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/IRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IRepository.cs new file mode 100644 index 00000000..a5fdf186 --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IRepository.cs @@ -0,0 +1,24 @@ +using AgileConfig.Server.Common; +using System.Linq.Expressions; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IRepository : IDisposable where T : IEntity + { + Task> AllAsync(); + Task GetAsync(T1 id); + + Task UpdateAsync(T entity); + Task UpdateAsync(IList entities); + + Task DeleteAsync(T entity); + + Task DeleteAsync(IList entities); + + Task InsertAsync(T entity); + + Task InsertAsync(IList entities); + + Task> QueryAsync(Expression> exp); + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/IServerNodeRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IServerNodeRepository.cs new file mode 100644 index 00000000..f97e4774 --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IServerNodeRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IServerNodeRepository : IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/IServiceInfoRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IServiceInfoRepository.cs new file mode 100644 index 00000000..de6d42de --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IServiceInfoRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IServiceInfoRepository : IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/ISettingRepository.cs b/src/AgileConfig.Server.Data.Abstraction/ISettingRepository.cs new file mode 100644 index 00000000..0bac356a --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/ISettingRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface ISettingRepository : IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/ISysLogRepository.cs b/src/AgileConfig.Server.Data.Abstraction/ISysLogRepository.cs new file mode 100644 index 00000000..ea0508b0 --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/ISysLogRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface ISysLogRepository : IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/IUserAppAuthRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IUserAppAuthRepository.cs new file mode 100644 index 00000000..ea2a3b00 --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IUserAppAuthRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IUserAppAuthRepository : IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/IUserRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IUserRepository.cs new file mode 100644 index 00000000..5d392afc --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IUserRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IUserRepository : IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/IUserRoleRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IUserRoleRepository.cs new file mode 100644 index 00000000..b635c7a6 --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IUserRoleRepository.cs @@ -0,0 +1,8 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IUserRoleRepository : IRepository + { + } +} diff --git a/src/AgileConfig.Server.Data.Entity/AgileConfig.Server.Data.Entity.csproj b/src/AgileConfig.Server.Data.Entity/AgileConfig.Server.Data.Entity.csproj index 4c0540b2..f0a576df 100644 --- a/src/AgileConfig.Server.Data.Entity/AgileConfig.Server.Data.Entity.csproj +++ b/src/AgileConfig.Server.Data.Entity/AgileConfig.Server.Data.Entity.csproj @@ -9,4 +9,8 @@ + + + + diff --git a/src/AgileConfig.Server.Data.Entity/App.cs b/src/AgileConfig.Server.Data.Entity/App.cs index 9fea9148..94b29032 100644 --- a/src/AgileConfig.Server.Data.Entity/App.cs +++ b/src/AgileConfig.Server.Data.Entity/App.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Text; using MongoDB.Bson.Serialization.Attributes; +using AgileConfig.Server.Common; namespace AgileConfig.Server.Data.Entity { @@ -27,7 +28,7 @@ public enum AppType [Table(Name = "agc_app")] [OraclePrimaryKeyName("agc_app_pk")] - public class App: IAppModel + public class App: IAppModel, IEntity { [Column(Name= "id" , StringLength = 36)] public string Id { get; set; } diff --git a/src/AgileConfig.Server.Data.Entity/AppInheritanced.cs b/src/AgileConfig.Server.Data.Entity/AppInheritanced.cs index c482de15..16ca48c2 100644 --- a/src/AgileConfig.Server.Data.Entity/AppInheritanced.cs +++ b/src/AgileConfig.Server.Data.Entity/AppInheritanced.cs @@ -1,4 +1,5 @@ -using FreeSql.DataAnnotations; +using AgileConfig.Server.Common; +using FreeSql.DataAnnotations; using System; using System.Collections.Generic; using System.Text; @@ -10,7 +11,7 @@ namespace AgileConfig.Server.Data.Entity /// [Table(Name = "agc_appInheritanced")] [OraclePrimaryKeyName("agc_appInheritanced_pk")] - public class AppInheritanced + public class AppInheritanced : IEntity { [Column(Name = "id", StringLength = 36)] public string Id { get; set; } diff --git a/src/AgileConfig.Server.Data.Entity/Config.cs b/src/AgileConfig.Server.Data.Entity/Config.cs index 4cca12ee..c50a10e1 100644 --- a/src/AgileConfig.Server.Data.Entity/Config.cs +++ b/src/AgileConfig.Server.Data.Entity/Config.cs @@ -1,6 +1,7 @@ using FreeSql.DataAnnotations; using System; using MongoDB.Bson.Serialization.Attributes; +using AgileConfig.Server.Common; namespace AgileConfig.Server.Data.Entity { @@ -40,7 +41,7 @@ public enum OnlineStatus [Table(Name = "agc_config")] [OraclePrimaryKeyName("agc_config_pk")] - public class Config + public class Config: IEntity { [Column(Name = "id", StringLength = 36)] public string Id { get; set; } diff --git a/src/AgileConfig.Server.Data.Entity/ConfigPublished.cs b/src/AgileConfig.Server.Data.Entity/ConfigPublished.cs index b6126101..82e792db 100644 --- a/src/AgileConfig.Server.Data.Entity/ConfigPublished.cs +++ b/src/AgileConfig.Server.Data.Entity/ConfigPublished.cs @@ -1,12 +1,13 @@ using FreeSql.DataAnnotations; using System; using MongoDB.Bson.Serialization.Attributes; +using AgileConfig.Server.Common; namespace AgileConfig.Server.Data.Entity { [Table(Name = "agc_config_published")] [OraclePrimaryKeyName("agc_config_published_pk")] - public class ConfigPublished + public class ConfigPublished : IEntity { [Column(Name = "id", StringLength = 36)] public string Id { get; set; } diff --git a/src/AgileConfig.Server.Data.Entity/PublishDetail.cs b/src/AgileConfig.Server.Data.Entity/PublishDetail.cs index 02e924dd..849dc3db 100644 --- a/src/AgileConfig.Server.Data.Entity/PublishDetail.cs +++ b/src/AgileConfig.Server.Data.Entity/PublishDetail.cs @@ -1,11 +1,12 @@ -using FreeSql.DataAnnotations; +using AgileConfig.Server.Common; +using FreeSql.DataAnnotations; using System; namespace AgileConfig.Server.Data.Entity { [Table(Name = "agc_publish_detail")] [OraclePrimaryKeyName("agc_publish_detail_pk")] - public class PublishDetail + public class PublishDetail: IEntity { [Column(Name = "id", StringLength = 36)] public string Id { get; set; } diff --git a/src/AgileConfig.Server.Data.Entity/PublishTimeline.cs b/src/AgileConfig.Server.Data.Entity/PublishTimeline.cs index 2b980b50..59a7d0d4 100644 --- a/src/AgileConfig.Server.Data.Entity/PublishTimeline.cs +++ b/src/AgileConfig.Server.Data.Entity/PublishTimeline.cs @@ -1,12 +1,13 @@ using FreeSql.DataAnnotations; using System; using MongoDB.Bson.Serialization.Attributes; +using AgileConfig.Server.Common; namespace AgileConfig.Server.Data.Entity { [Table(Name = "agc_publish_timeline")] [OraclePrimaryKeyName("agc_publish_timeline_pk")] - public class PublishTimeline + public class PublishTimeline: IEntity { [Column(Name = "id", StringLength = 36)] public string Id { get; set; } diff --git a/src/AgileConfig.Server.Data.Entity/ServerNode.cs b/src/AgileConfig.Server.Data.Entity/ServerNode.cs index af1f5788..4c03aba0 100644 --- a/src/AgileConfig.Server.Data.Entity/ServerNode.cs +++ b/src/AgileConfig.Server.Data.Entity/ServerNode.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Text; using MongoDB.Bson.Serialization.Attributes; +using AgileConfig.Server.Common; namespace AgileConfig.Server.Data.Entity { @@ -18,11 +19,11 @@ public enum NodeStatus [Table(Name = "agc_server_node")] [OraclePrimaryKeyName("agc_server_node_pk")] - public class ServerNode + public class ServerNode: IEntity { [BsonId] [Column(Name = "address", StringLength = 100, IsPrimary = true)] - public string Address { get; set; } + public string Id { get; set; } [Column(Name = "remark", StringLength = 50)] public string Remark { get; set; } diff --git a/src/AgileConfig.Server.Data.Entity/ServiceInfo.cs b/src/AgileConfig.Server.Data.Entity/ServiceInfo.cs index 8b3ca074..4c1043fb 100644 --- a/src/AgileConfig.Server.Data.Entity/ServiceInfo.cs +++ b/src/AgileConfig.Server.Data.Entity/ServiceInfo.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Text; using MongoDB.Bson.Serialization.Attributes; +using AgileConfig.Server.Common; namespace AgileConfig.Server.Data.Entity { @@ -27,7 +28,7 @@ public enum HeartBeatModes [Table(Name = "agc_service_info")] [OraclePrimaryKeyName("agc_serviceinfo_pk")] - public class ServiceInfo + public class ServiceInfo : IEntity { [Column(Name = "id", StringLength = 36)] public string Id { get; set; } diff --git a/src/AgileConfig.Server.Data.Entity/Setting.cs b/src/AgileConfig.Server.Data.Entity/Setting.cs index 8878fd5f..9d4f6fa4 100644 --- a/src/AgileConfig.Server.Data.Entity/Setting.cs +++ b/src/AgileConfig.Server.Data.Entity/Setting.cs @@ -1,14 +1,13 @@ using FreeSql.DataAnnotations; using System; -using System.Collections.Generic; -using System.Text; using MongoDB.Bson.Serialization.Attributes; +using AgileConfig.Server.Common; namespace AgileConfig.Server.Data.Entity { [Table(Name = "agc_setting")] [OraclePrimaryKeyName("agc_setting_pk")] - public class Setting + public class Setting: IEntity { [Column(Name = "id", StringLength = 36)] public string Id { get; set; } diff --git a/src/AgileConfig.Server.Data.Entity/SysLog.cs b/src/AgileConfig.Server.Data.Entity/SysLog.cs index 0b4938ee..825f56a9 100644 --- a/src/AgileConfig.Server.Data.Entity/SysLog.cs +++ b/src/AgileConfig.Server.Data.Entity/SysLog.cs @@ -1,8 +1,7 @@ using FreeSql.DataAnnotations; using System; -using System.Collections.Generic; -using System.Text; using MongoDB.Bson.Serialization.Attributes; +using AgileConfig.Server.Common; namespace AgileConfig.Server.Data.Entity { @@ -14,7 +13,7 @@ public enum SysLogType [Table(Name = "agc_sys_log")] [OraclePrimaryKeyName("agc_sys_log_pk")] - public class SysLog + public class SysLog: IEntity { [Column(Name = "id", IsIdentity = true)] public int Id { get; set; } diff --git a/src/AgileConfig.Server.Data.Entity/User.cs b/src/AgileConfig.Server.Data.Entity/User.cs index 4f3d000b..186fbaa2 100644 --- a/src/AgileConfig.Server.Data.Entity/User.cs +++ b/src/AgileConfig.Server.Data.Entity/User.cs @@ -1,12 +1,13 @@ using FreeSql.DataAnnotations; using System; using MongoDB.Bson.Serialization.Attributes; +using AgileConfig.Server.Common; namespace AgileConfig.Server.Data.Entity { [Table(Name = "agc_user")] [OraclePrimaryKeyName("agc_user_pk")] - public class User + public class User: IEntity { [Column(Name = "id", StringLength = 256)] public string Id { get; set; } diff --git a/src/AgileConfig.Server.Data.Entity/UserAppAuth.cs b/src/AgileConfig.Server.Data.Entity/UserAppAuth.cs index 6bdc5f0c..a07c9ab8 100644 --- a/src/AgileConfig.Server.Data.Entity/UserAppAuth.cs +++ b/src/AgileConfig.Server.Data.Entity/UserAppAuth.cs @@ -1,4 +1,5 @@ -using FreeSql.DataAnnotations; +using AgileConfig.Server.Common; +using FreeSql.DataAnnotations; using System; using System.Collections.Generic; using System.Text; @@ -7,7 +8,7 @@ namespace AgileConfig.Server.Data.Entity { [Table(Name = "agc_user_app_auth")] [OraclePrimaryKeyName("agc_user_app_auth_pk")] - public class UserAppAuth + public class UserAppAuth: IEntity { [Column(Name = "id", StringLength = 36)] public string Id { get; set; } diff --git a/src/AgileConfig.Server.Data.Entity/UserRole.cs b/src/AgileConfig.Server.Data.Entity/UserRole.cs index d03f9a5b..7188aa13 100644 --- a/src/AgileConfig.Server.Data.Entity/UserRole.cs +++ b/src/AgileConfig.Server.Data.Entity/UserRole.cs @@ -2,12 +2,13 @@ using System; using System.ComponentModel; using MongoDB.Bson.Serialization.Attributes; +using AgileConfig.Server.Common; namespace AgileConfig.Server.Data.Entity { [Table(Name = "agc_user_role")] [OraclePrimaryKeyName("agc_user_role_pk")] - public class UserRole + public class UserRole: IEntity { [Column(Name = "id", StringLength = 36)] public string Id { get; set; } diff --git a/src/AgileConfig.Server.Data.Freesql/AgileConfig.Server.Data.Freesql.csproj b/src/AgileConfig.Server.Data.Freesql/AgileConfig.Server.Data.Freesql.csproj index 4fb5adc6..f4a5e629 100644 --- a/src/AgileConfig.Server.Data.Freesql/AgileConfig.Server.Data.Freesql.csproj +++ b/src/AgileConfig.Server.Data.Freesql/AgileConfig.Server.Data.Freesql.csproj @@ -18,6 +18,7 @@ + diff --git a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs new file mode 100644 index 00000000..b6df981b --- /dev/null +++ b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs @@ -0,0 +1,71 @@ +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction; +using FreeSql; +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Threading.Tasks; + +namespace AgileConfig.Server.Data.Freesql +{ + public class FreesqlRepository : IRepository where T : class, IEntity + { + private readonly IFreeSql _freeSql; + private readonly IBaseRepository _repository; + public FreesqlRepository(IFreeSql freeSql) + { + _freeSql = freeSql; + _repository = freeSql.GetRepository(); + } + + public Task> AllAsync() + { + return _repository.Select.ToListAsync(); + } + + public Task DeleteAsync(T entity) + { + return _repository.DeleteAsync(entity); + } + + public Task DeleteAsync(IList entities) + { + return _repository.DeleteAsync(entities); + } + + public Task GetAsync(T1 id) + { + return _repository.Where(x => x.Id.Equals(id)).ToOneAsync(); + } + + public Task InsertAsync(T entity) + { + return _repository.InsertAsync(entity); + } + + public Task InsertAsync(IList entities) + { + return _repository.InsertAsync(entities); + } + + public Task> QueryAsync(Expression> exp) + { + return _repository.Where(exp).ToListAsync(); + } + + public Task UpdateAsync(T entity) + { + return _repository.UpdateAsync(entity); + } + + public Task UpdateAsync(IList entities) + { + return _repository.UpdateAsync(entities); + } + + public void Dispose() + { + _repository.Dispose(); + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/AgileConfig.Server.Data.Repository.Freesql.csproj b/src/AgileConfig.Server.Data.Repository.Freesql/AgileConfig.Server.Data.Repository.Freesql.csproj new file mode 100644 index 00000000..cc7c89ce --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/AgileConfig.Server.Data.Repository.Freesql.csproj @@ -0,0 +1,14 @@ + + + + net8.0 + enable + enable + + + + + + + + diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs new file mode 100644 index 00000000..e680ae75 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class AppInheritancedRepository : FreesqlRepository, IAppInheritancedRepository + { + public AppInheritancedRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs new file mode 100644 index 00000000..cff884dc --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class AppRepository : FreesqlRepository, IAppRepository + { + public AppRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs new file mode 100644 index 00000000..0482893c --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class ConfigPublishedRepository : FreesqlRepository, IConfigPublishedRepository + { + public ConfigPublishedRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs new file mode 100644 index 00000000..88e08380 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class ConfigRepository : FreesqlRepository, IConfigRepository + { + public ConfigRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs new file mode 100644 index 00000000..2048bbb2 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class PublishDetailRepository : FreesqlRepository, IPublishDetailRepository + { + public PublishDetailRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs new file mode 100644 index 00000000..a2198185 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class PublishTimelineRepository : FreesqlRepository, IPublishTimelineRepository + { + public PublishTimelineRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs new file mode 100644 index 00000000..0d2fc202 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class ServerNodeRepository : FreesqlRepository, IServerNodeRepository + { + public ServerNodeRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceCollectionExt.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceCollectionExt.cs new file mode 100644 index 00000000..fa82ccd9 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceCollectionExt.cs @@ -0,0 +1,28 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public static class ServiceCollectionExt + { + public static void AddFreeSqlRepository(this IServiceCollection sc) + { + sc.AddFreeRepository(); + + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs new file mode 100644 index 00000000..461b99ee --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class ServiceInfoRepository : FreesqlRepository, IServiceInfoRepository + { + public ServiceInfoRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs new file mode 100644 index 00000000..b2a913b6 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class SettingRepository : FreesqlRepository, ISettingRepository + { + public SettingRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs new file mode 100644 index 00000000..0d5eec94 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class SysLogRepository : FreesqlRepository, ISysLogRepository + { + public SysLogRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs new file mode 100644 index 00000000..9c403d0f --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class UserAppAuthRepository : FreesqlRepository, IUserAppAuthRepository + { + public UserAppAuthRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs new file mode 100644 index 00000000..866f8e57 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class UserRepository : FreesqlRepository, IUserRepository + { + public UserRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs new file mode 100644 index 00000000..17a53c96 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs @@ -0,0 +1,13 @@ +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql +{ + public class UserRoleRepository : FreesqlRepository, IUserRoleRepository + { + public UserRoleRepository(IFreeSql freeSql) : base(freeSql) + { + } + } +} diff --git a/src/AgileConfig.Server.IService/IAppService.cs b/src/AgileConfig.Server.IService/IAppService.cs index 884709cd..9d363ac6 100644 --- a/src/AgileConfig.Server.IService/IAppService.cs +++ b/src/AgileConfig.Server.IService/IAppService.cs @@ -32,6 +32,6 @@ public interface IAppService : IDisposable Task> GetUserAppAuth(string appId, string permission); - List GetAppGroups(); + Task> GetAppGroups(); } } diff --git a/src/AgileConfig.Server.Mongodb.Service/AppService.cs b/src/AgileConfig.Server.Mongodb.Service/AppService.cs index f5a8edea..63dbda21 100644 --- a/src/AgileConfig.Server.Mongodb.Service/AppService.cs +++ b/src/AgileConfig.Server.Mongodb.Service/AppService.cs @@ -165,9 +165,9 @@ public async Task> GetUserAppAuth(string appId, string permission) return await userRepository.SearchFor(x => userIds.Contains(x.Id)).ToListAsync(); } - public List GetAppGroups() + public async Task> GetAppGroups() { var groups = repository.SearchFor(x => true).GroupBy(x => x.Group).Select(x => x.Key); - return groups.Where(x => !string.IsNullOrEmpty(x)).ToList(); + return await groups.Where(x => !string.IsNullOrEmpty(x)).ToListAsync(); } } \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ConfigStatusUpdateRegister.cs b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ConfigStatusUpdateRegister.cs index d9daebc8..42259f8e 100644 --- a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ConfigStatusUpdateRegister.cs +++ b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ConfigStatusUpdateRegister.cs @@ -44,7 +44,7 @@ public void Register() } //all server cache - await _remoteServerNodeProxy.ClearConfigServiceCache(node.Address); + await _remoteServerNodeProxy.ClearConfigServiceCache(node.Id as string); } foreach (var node in nodes) @@ -57,7 +57,7 @@ public void Register() foreach (var item in noticeApps) { await _remoteServerNodeProxy.AppClientsDoActionAsync( - node.Address, + node.Id as string, item.Key, timelineNode.Env, item.Value); @@ -90,7 +90,7 @@ await _remoteServerNodeProxy.AppClientsDoActionAsync( foreach (var item in noticeApps) { - await _remoteServerNodeProxy.AppClientsDoActionAsync(node.Address, item.Key, + await _remoteServerNodeProxy.AppClientsDoActionAsync(node.Id.ToString(), item.Key, timelineNode.Env, item.Value); } @@ -116,7 +116,7 @@ private async Task> GetNeedNoticeInheritance var inheritancedFromApps = await _appService.GetInheritancedFromAppsAsync(appId); inheritancedFromApps.ForEach(x => { - needNoticeAppsActions.Add(x.Id, new WebsocketAction + needNoticeAppsActions.Add(x.Id as string, new WebsocketAction { Action = ActionConst.Reload, Module = ActionModule.ConfigCenter }); diff --git a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs index de8b9508..6a919872 100644 --- a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs +++ b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs @@ -40,14 +40,14 @@ public void Register() foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) { //clear cache - _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Address); + _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Id as string); //send ws action var act = new WebsocketAction() { Module = ActionModule.RegisterCenter, Action = ActionConst.Reload }; - _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Address, act); + _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Id as string, act); } }); }); @@ -59,14 +59,14 @@ public void Register() foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) { //clear cache - _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Address); + _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Id as string); //send ws action var act = new WebsocketAction() { Module = ActionModule.RegisterCenter, Action = ActionConst.Reload }; - _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Address, act); + _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Id as string, act); } }); }); @@ -78,14 +78,14 @@ public void Register() foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) { //clear cache - _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Address); + _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Id as string); //send ws action var act = new WebsocketAction() { Module = ActionModule.RegisterCenter, Action = ActionConst.Reload }; - _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Address, act); + _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Id as string, act); } }); }); diff --git a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/SysLogRegister.cs b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/SysLogRegister.cs index 5c4e57c1..93f9450f 100644 --- a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/SysLogRegister.cs +++ b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/SysLogRegister.cs @@ -340,7 +340,7 @@ public void Register() { LogTime = DateTime.Now, LogType = SysLogType.Normal, - LogText = $"用户:{userName} 添加节点:{node.Address}" + LogText = $"用户:{userName} 添加节点:{node.Id}" }; Task.Run(async () => { @@ -358,7 +358,7 @@ public void Register() { LogTime = DateTime.Now, LogType = SysLogType.Warn, - LogText = $"用户:{userName} 删除节点:{node.Address}" + LogText = $"用户:{userName} 删除节点:{node.Id}" }; Task.Run(async () => { diff --git a/src/AgileConfig.Server.Mongodb.Service/RegisterCenterService.cs b/src/AgileConfig.Server.Mongodb.Service/RegisterCenterService.cs index 926b92d9..02167097 100644 --- a/src/AgileConfig.Server.Mongodb.Service/RegisterCenterService.cs +++ b/src/AgileConfig.Server.Mongodb.Service/RegisterCenterService.cs @@ -78,7 +78,7 @@ public async Task UnRegisterAsync(string serviceUniqueId) return false; } - await serviceInfoRepository.DeleteAsync(oldEntity.Id); + await serviceInfoRepository.DeleteAsync(oldEntity.Id.ToString()); serviceInfoService.ClearCache(); @@ -105,7 +105,7 @@ public async Task UnRegisterByServiceIdAsync(string serviceId) return false; } - await serviceInfoRepository.DeleteAsync(oldEntity.Id); + await serviceInfoRepository.DeleteAsync(oldEntity.Id.ToString()); serviceInfoService.ClearCache(); diff --git a/src/AgileConfig.Server.Mongodb.Service/RemoteServerNodeProxy.cs b/src/AgileConfig.Server.Mongodb.Service/RemoteServerNodeProxy.cs index 15c5e7b4..868a09fb 100644 --- a/src/AgileConfig.Server.Mongodb.Service/RemoteServerNodeProxy.cs +++ b/src/AgileConfig.Server.Mongodb.Service/RemoteServerNodeProxy.cs @@ -190,7 +190,7 @@ public async Task TestEchoAsync(string address) var node = await serverNodeService.GetAsync(address); try { - var url = node.Address + "/home/echo"; + var url = node.Id + "/home/echo"; using var resp = await restClient.GetAsync(url); @@ -207,7 +207,7 @@ public async Task TestEchoAsync(string address) catch (Exception e) { node.Status = NodeStatus.Offline; - _logger.LogInformation(e, "Try test node {Address} echo , but fail", node.Address); + _logger.LogInformation(e, "Try test node {Address} echo , but fail", node.Id); } if (node.Status == NodeStatus.Offline) @@ -235,7 +235,7 @@ public Task TestEchoAsync() foreach (var node in nodes) { - await TestEchoAsync(node.Address); + await TestEchoAsync(node.Id as string); } await Task.Delay(5000 * 1); diff --git a/src/AgileConfig.Server.Mongodb.Service/ServerNodeService.cs b/src/AgileConfig.Server.Mongodb.Service/ServerNodeService.cs index c4e61e43..b94ce0c2 100644 --- a/src/AgileConfig.Server.Mongodb.Service/ServerNodeService.cs +++ b/src/AgileConfig.Server.Mongodb.Service/ServerNodeService.cs @@ -17,13 +17,13 @@ public async Task AddAsync(ServerNode node) public async Task DeleteAsync(ServerNode node) { - var result = await repository.DeleteAsync(x => x.Address == node.Address); + var result = await repository.DeleteAsync(x => x.Id == node.Id); return result.DeletedCount > 0; } public async Task DeleteAsync(string address) { - var result = await repository.DeleteAsync(x => x.Address == address); + var result = await repository.DeleteAsync(x => x.Id == address); return result.DeletedCount > 0; } @@ -39,7 +39,7 @@ public Task> GetAllNodesAsync() public Task GetAsync(string address) { - return repository.SearchFor(n => n.Address == address).FirstOrDefaultAsync(); + return repository.SearchFor(n => n.Id == address).FirstOrDefaultAsync(); } public async Task UpdateAsync(ServerNode node) @@ -78,10 +78,10 @@ public async Task InitWatchNodeAsync() } } - var existNodes = await repository.SearchFor(x => addresses.Contains(x.Address)).ToListAsync(); + var existNodes = await repository.SearchFor(x => addresses.Contains(x.Id)).ToListAsync(); var newNodes = addresses - .Where(x => existNodes.All(y => y.Address != x)) - .Select(x => new ServerNode { Address = x, CreateTime = DateTime.Now }) + .Where(x => existNodes.All(y => y.Id != x)) + .Select(x => new ServerNode { Id = x, CreateTime = DateTime.Now }) .ToList(); await repository.InsertAsync(newNodes); @@ -91,12 +91,12 @@ public async Task InitWatchNodeAsync() public async Task JoinAsync(string ip, int port, string desc) { var address = $"http://{ip}:{port}"; - var nodes = await repository.SearchFor(x => x.Address == address).ToListAsync(); + var nodes = await repository.SearchFor(x => x.Id == address).ToListAsync(); if (nodes.Count > 0) { nodes.ForEach(n => { - n.Address = address; + n.Id = address; n.Remark = desc; n.Status = NodeStatus.Online; }); @@ -105,7 +105,7 @@ public async Task JoinAsync(string ip, int port, string desc) { await repository.InsertAsync(new ServerNode { - Address = address, + Id = address, CreateTime = DateTime.Now, Remark = desc, Status = NodeStatus.Online, diff --git a/src/AgileConfig.Server.Mongodb.Service/SettingService.cs b/src/AgileConfig.Server.Mongodb.Service/SettingService.cs index b60adf9b..e9bf6bfe 100644 --- a/src/AgileConfig.Server.Mongodb.Service/SettingService.cs +++ b/src/AgileConfig.Server.Mongodb.Service/SettingService.cs @@ -27,7 +27,7 @@ public async Task AddAsync(Setting setting) public async Task DeleteAsync(Setting setting) { - var result = await repository.DeleteAsync(setting.Id); + var result = await repository.DeleteAsync(setting.Id.ToString()); return result.DeletedCount > 0; } diff --git a/src/AgileConfig.Server.Mongodb.Service/UserService.cs b/src/AgileConfig.Server.Mongodb.Service/UserService.cs index dc80d749..eb2a5e18 100644 --- a/src/AgileConfig.Server.Mongodb.Service/UserService.cs +++ b/src/AgileConfig.Server.Mongodb.Service/UserService.cs @@ -53,7 +53,7 @@ public async Task AddAsync(User user) public async Task DeleteAsync(User user) { - var result = await repository.DeleteAsync(user.Id); + var result = await repository.DeleteAsync(user.Id.ToString()); return result.DeletedCount > 0; } diff --git a/src/AgileConfig.Server.Service/AppService.cs b/src/AgileConfig.Server.Service/AppService.cs index 826315e9..e8f38c2c 100644 --- a/src/AgileConfig.Server.Service/AppService.cs +++ b/src/AgileConfig.Server.Service/AppService.cs @@ -3,112 +3,117 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; -using AgileConfig.Server.Data.Freesql; using System.Linq; +using AgileConfig.Server.Data.Abstraction; namespace AgileConfig.Server.Service { public class AppService : IAppService { - private FreeSqlContext _dbContext; - - public AppService(FreeSqlContext context) - { - _dbContext = context; + private readonly IAppRepository _appRepository; + private readonly IAppInheritancedRepository _appInheritancedRepository; + private readonly IConfigRepository _configRepository; + private readonly IConfigPublishedRepository _configPublishedRepository; + private readonly IUserRepository _userRepository; + private readonly IUserAppAuthRepository _userAppAuthRepository; + + public AppService( + IAppRepository repository, + IAppInheritancedRepository appInheritancedRepository, + IConfigRepository configRepository, + IConfigPublishedRepository configPublishedRepository, + IUserRepository userRepository, + IUserAppAuthRepository userAppAuthRepository) + { + _appRepository = repository; + _appInheritancedRepository = appInheritancedRepository; + _configRepository = configRepository; + _configPublishedRepository = configPublishedRepository; + _userRepository = userRepository; + _userAppAuthRepository = userAppAuthRepository; } public async Task AddAsync(App app) { - await _dbContext.Apps.AddAsync(app); - int x = await _dbContext.SaveChangesAsync(); - var result = x > 0; + await _appRepository.InsertAsync(app); - return result; + return true; } public async Task AddAsync(App app, List appInheritanceds) { - await _dbContext.Apps.AddAsync(app); + await _appRepository.InsertAsync(app); if (appInheritanceds != null) { - await _dbContext.AppInheritanceds.AddRangeAsync(appInheritanceds); + await _appInheritancedRepository.InsertAsync(appInheritanceds); } - int x = await _dbContext.SaveChangesAsync(); - var result = x > 0; - return result; + return true; } public async Task DeleteAsync(App app) { - app = await _dbContext.Apps.Where(a => a.Id == app.Id).ToOneAsync(); + app = await _appRepository.GetAsync(app.Id); if (app != null) { - _dbContext.Apps.Remove(app); + await _appRepository.DeleteAsync(app); //怕有的同学误删app导致要恢复,所以保留配置项吧。 - var configs = await _dbContext.Configs.Where(x => x.AppId == app.Id).ToListAsync(); + var configs = await _configRepository.QueryAsync(x => x.AppId == app.Id); foreach (var item in configs) { item.Status = ConfigStatus.Deleted; - await _dbContext.UpdateAsync(item); + await _configRepository.UpdateAsync(item); } //删除发布的配置项 - var publishedConfigs = await _dbContext.ConfigPublished - .Where(x => x.AppId == app.Id && x.Status == ConfigStatus.Enabled) - .ToListAsync(); + var publishedConfigs = await _configPublishedRepository + .QueryAsync(x => x.AppId == app.Id && x.Status == ConfigStatus.Enabled) + ; foreach (var item in publishedConfigs) { item.Status = ConfigStatus.Deleted; - await _dbContext.UpdateAsync(item); + await _configPublishedRepository.UpdateAsync(item); } } - int x = await _dbContext.SaveChangesAsync(); - var result = x > 0; - return result; + return true; } public async Task DeleteAsync(string appId) { - var app = await _dbContext.Apps.Where(a => a.Id == appId).ToOneAsync(); + var app = await _appRepository.GetAsync(appId); if (app != null) { - _dbContext.Apps.Remove(app); + await _appRepository.DeleteAsync(app); } - int x = await _dbContext.SaveChangesAsync(); - var result = x > 0; - return result; + return true; } public async Task GetAsync(string id) { - return await _dbContext.Apps.Where(a => a.Id == id).ToOneAsync(); + return await _appRepository.GetAsync(id); } public async Task> GetAllAppsAsync() { - return await _dbContext.Apps.Where(a => 1 == 1).ToListAsync(); + return await _appRepository.AllAsync(); } public async Task UpdateAsync(App app) { - _dbContext.Update(app); - var x = await _dbContext.SaveChangesAsync(); + await _appRepository.UpdateAsync(app); - var result = x > 0; - - return result; + return true; } public async Task CountEnabledAppsAsync() { - var q = await _dbContext.Apps.Where(a => a.Enabled == true).CountAsync(); + var q = await _appRepository.QueryAsync(a => a.Enabled == true); - return (int)q; + return q.Count; } public async Task> GetAllInheritancedAppsAsync() { - return await _dbContext.Apps.Where(a => a.Type == AppType.Inheritance).ToListAsync(); + return await _appRepository.QueryAsync(a => a.Type == AppType.Inheritance); } /// @@ -118,7 +123,7 @@ public async Task> GetAllInheritancedAppsAsync() /// public async Task> GetInheritancedAppsAsync(string appId) { - var appInheritanceds = await _dbContext.AppInheritanceds.Where(a => a.AppId == appId).ToListAsync(); + var appInheritanceds = await _appInheritancedRepository.QueryAsync(a => a.AppId == appId); appInheritanceds = appInheritanceds.OrderBy(a => a.Sort).ToList(); var apps = new List(); @@ -142,7 +147,7 @@ public async Task> GetInheritancedAppsAsync(string appId) /// public async Task> GetInheritancedFromAppsAsync(string appId) { - var appInheritanceds = await _dbContext.AppInheritanceds.Where(a => a.InheritancedAppId == appId).ToListAsync(); + var appInheritanceds = await _appInheritancedRepository.QueryAsync(a => a.InheritancedAppId == appId); appInheritanceds = appInheritanceds.OrderBy(a => a.Sort).ToList(); var apps = new List(); @@ -162,18 +167,15 @@ public async Task> GetInheritancedFromAppsAsync(string appId) public async Task UpdateAsync(App app, List appInheritanceds) { - _dbContext.Update(app); - var oldInheritancedApps = await _dbContext.AppInheritanceds.Where(a => a.AppId == app.Id).ToListAsync(); - _dbContext.RemoveRange(oldInheritancedApps); + await _appRepository.UpdateAsync(app); + var oldInheritancedApps = await _appInheritancedRepository.QueryAsync(a => a.AppId == app.Id); + await _appInheritancedRepository.DeleteAsync(oldInheritancedApps); if (appInheritanceds != null) { - await _dbContext.AddRangeAsync(appInheritanceds); + await _appInheritancedRepository.InsertAsync(appInheritanceds); } - var x = await _dbContext.SaveChangesAsync(); - - var result = x > 0; - return result; + return true; } public async Task SaveUserAppAuth(string appId, List userIds, string permission) @@ -193,27 +195,31 @@ public async Task SaveUserAppAuth(string appId, List userIds, stri Permission = permission }); } - await _dbContext.UserAppAuths.RemoveAsync(x => x.AppId == appId && x.Permission == permission); - await _dbContext.UserAppAuths.AddRangeAsync(userAppAuthList); - - await _dbContext.SaveChangesAsync(); + var removeApps = await _userAppAuthRepository.QueryAsync(x => x.AppId == appId && x.Permission == permission); + await _userAppAuthRepository.DeleteAsync(removeApps); + await _userAppAuthRepository.InsertAsync(userAppAuthList); return true; } public void Dispose() { - _dbContext.Dispose(); + _appInheritancedRepository.Dispose(); + _appRepository.Dispose(); + _configPublishedRepository.Dispose(); + _configRepository.Dispose(); + _userAppAuthRepository.Dispose(); + _userRepository.Dispose(); } public async Task> GetUserAppAuth(string appId, string permission) { - var auths = await _dbContext.UserAppAuths.Where(x => x.AppId == appId && x.Permission == permission).ToListAsync(); + var auths = await _userAppAuthRepository.QueryAsync(x => x.AppId == appId && x.Permission == permission); var users = new List(); foreach (var auth in auths) { - var user = await _dbContext.Users.Where(u => u.Id == auth.UserId).FirstAsync(); + var user = await _userRepository.GetAsync(auth.UserId); if (user != null) { users.Add(user); @@ -223,9 +229,10 @@ public async Task> GetUserAppAuth(string appId, string permission) return users; } - public List GetAppGroups() + public async Task> GetAppGroups() { - var groups = _dbContext.Apps.Select.GroupBy(x => x.Group).Select(x => x.Key) + var apps = await _appRepository.AllAsync(); + var groups = apps.GroupBy(x => x.Group).Select(x => x.Key) ; return groups.Where(x => !string.IsNullOrEmpty(x)).ToList(); } diff --git a/src/AgileConfig.Server.Service/ConfigService.cs b/src/AgileConfig.Server.Service/ConfigService.cs index 2dc9d9b4..66c3aab5 100644 --- a/src/AgileConfig.Server.Service/ConfigService.cs +++ b/src/AgileConfig.Server.Service/ConfigService.cs @@ -405,7 +405,7 @@ public async Task> GetPublishedConfigsByAppIdWithInhe { if (inheritanceApps[i].Enabled) { - apps.Add(inheritanceApps[i].Id); //后继承的排在后面 + apps.Add(inheritanceApps[i].Id as string); //后继承的排在后面 } } diff --git a/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs index 153f9db8..ab21a7d0 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Threading.Tasks; using Agile.Config.Protocol; using AgileConfig.Server.Common; @@ -24,7 +25,11 @@ private IServerNodeService NewServerNodeService() private IAppService NewAppService() { - return new AppService(new FreeSqlContext(FreeSQL.Instance)); + // todo + + throw new NotImplementedException(); + + //return new AppService(new FreeSqlContext(FreeSQL.Instance)); } private IConfigService NewConfigService() @@ -58,7 +63,7 @@ public void Register() } //all server cache - await _remoteServerNodeProxy.ClearConfigServiceCache(node.Address); + await _remoteServerNodeProxy.ClearConfigServiceCache(node.Id); } foreach (var node in nodes) @@ -71,7 +76,7 @@ public void Register() foreach (var item in noticeApps) { await _remoteServerNodeProxy.AppClientsDoActionAsync( - node.Address, + node.Id, item.Key, timelineNode.Env, item.Value); @@ -107,7 +112,7 @@ await _remoteServerNodeProxy.AppClientsDoActionAsync( foreach (var item in noticeApps) { - await _remoteServerNodeProxy.AppClientsDoActionAsync(node.Address, item.Key, + await _remoteServerNodeProxy.AppClientsDoActionAsync(node.Id, item.Key, timelineNode.Env, item.Value); } diff --git a/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs index fc001bcf..9c8b63f3 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs @@ -51,14 +51,14 @@ public void Register() foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) { //clear cache - _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Address); + _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Id); //send ws action var act = new WebsocketAction() { Module = ActionModule.RegisterCenter, Action = ActionConst.Reload }; - _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Address, act); + _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Id, act); } }); }); @@ -71,14 +71,14 @@ public void Register() foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) { //clear cache - _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Address); + _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Id); //send ws action var act = new WebsocketAction() { Module = ActionModule.RegisterCenter, Action = ActionConst.Reload }; - _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Address, act); + _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Id, act); } }); }); @@ -91,14 +91,14 @@ public void Register() foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) { //clear cache - _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Address); + _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Id); //send ws action var act = new WebsocketAction() { Module = ActionModule.RegisterCenter, Action = ActionConst.Reload }; - _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Address, act); + _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Id, act); } }); }); diff --git a/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs index 3158e16c..3372090f 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs @@ -398,7 +398,7 @@ public void Register() { LogTime = DateTime.Now, LogType = SysLogType.Normal, - LogText = $"用户:{userName} 添加节点:{node.Address}" + LogText = $"用户:{userName} 添加节点:{node.Id}" }; Task.Run(async () => { @@ -419,7 +419,7 @@ public void Register() { LogTime = DateTime.Now, LogType = SysLogType.Warn, - LogText = $"用户:{userName} 删除节点:{node.Address}" + LogText = $"用户:{userName} 删除节点:{node.Id}" }; Task.Run(async () => { diff --git a/src/AgileConfig.Server.Service/RemoteServerNodeProxy.cs b/src/AgileConfig.Server.Service/RemoteServerNodeProxy.cs index 1edb261c..2dea6f76 100644 --- a/src/AgileConfig.Server.Service/RemoteServerNodeProxy.cs +++ b/src/AgileConfig.Server.Service/RemoteServerNodeProxy.cs @@ -205,7 +205,7 @@ public async Task TestEchoAsync(string address) var node = await service.GetAsync(address); try { - var url = node.Address + "/home/echo"; + var url = node.Id + "/home/echo"; using var resp = await _restClient.GetAsync(url); @@ -222,7 +222,7 @@ public async Task TestEchoAsync(string address) catch (Exception e) { node.Status = NodeStatus.Offline; - _logger.LogInformation(e, "Try test node {0} echo , but fail .", node.Address); + _logger.LogInformation(e, "Try test node {0} echo , but fail .", node.Id); } if (node.Status == NodeStatus.Offline) @@ -254,7 +254,7 @@ public Task TestEchoAsync() foreach (var node in nodes) { - await TestEchoAsync(node.Address); + await TestEchoAsync(node.Id); } await Task.Delay(5000 * 1); diff --git a/src/AgileConfig.Server.Service/ServerNodeService.cs b/src/AgileConfig.Server.Service/ServerNodeService.cs index 2a87fd85..4f2084f7 100644 --- a/src/AgileConfig.Server.Service/ServerNodeService.cs +++ b/src/AgileConfig.Server.Service/ServerNodeService.cs @@ -28,7 +28,7 @@ public async Task AddAsync(ServerNode node) public async Task DeleteAsync(ServerNode node) { - node = await _dbContext.ServerNodes.Where(n => n.Address == node.Address).ToOneAsync(); + node = await _dbContext.ServerNodes.Where(n => n.Id == node.Id).ToOneAsync(); if (node != null) { _dbContext.ServerNodes.Remove(node); @@ -41,7 +41,7 @@ public async Task DeleteAsync(ServerNode node) public async Task DeleteAsync(string address) { - var node = await _dbContext.ServerNodes.Where(n => n.Address == address).ToOneAsync(); + var node = await _dbContext.ServerNodes.Where(n => n.Id == address).ToOneAsync(); if (node != null) { _dbContext.ServerNodes.Remove(node); @@ -64,7 +64,7 @@ public async Task> GetAllNodesAsync() public async Task GetAsync(string address) { - return await _dbContext.ServerNodes.Where(n => n.Address == address).ToOneAsync(); + return await _dbContext.ServerNodes.Where(n => n.Id == address).ToOneAsync(); } public async Task UpdateAsync(ServerNode node) @@ -107,12 +107,12 @@ public async Task InitWatchNodeAsync() foreach (var address in addresses) { - var node = await _dbContext.ServerNodes.Where(n => n.Address == address).ToOneAsync(); + var node = await _dbContext.ServerNodes.Where(n => n.Id == address).ToOneAsync(); if (node == null) { node = new ServerNode() { - Address = address, + Id = address, CreateTime = DateTime.Now, }; await _dbContext.ServerNodes.AddAsync(node); @@ -131,11 +131,11 @@ public async Task InitWatchNodeAsync() public async Task JoinAsync(string ip, int port, string desc) { var address = $"http://{ip}:{port}"; - var nodes = await _dbContext.ServerNodes.Where(x => x.Address == address).ToListAsync(); + var nodes = await _dbContext.ServerNodes.Where(x => x.Id == address).ToListAsync(); if (nodes.Count > 0) { nodes.ForEach(n => { - n.Address = address; + n.Id = address; n.Remark = desc; n.Status = NodeStatus.Online; }); @@ -143,7 +143,7 @@ public async Task JoinAsync(string ip, int port, string desc) else { await _dbContext.ServerNodes.AddAsync(new ServerNode { - Address = address, + Id = address, CreateTime = DateTime.Now, Remark = desc, Status = NodeStatus.Online, diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/ServerNodeServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/ServerNodeServiceTests.cs index 4f5606bc..25d05c00 100644 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.Mongodb.ServiceTest/ServerNodeServiceTests.cs @@ -22,7 +22,7 @@ public async Task AddAsyncTest() await ServerNodeRepository.DeleteAsync(x => true); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -31,10 +31,10 @@ public async Task AddAsyncTest() var result = await service.AddAsync(source); Assert.IsTrue(result); - var node = await ServerNodeRepository.SearchFor(x => x.Address == "1").FirstOrDefaultAsync(); + var node = await ServerNodeRepository.SearchFor(x => x.Id == "1").FirstOrDefaultAsync(); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); @@ -47,7 +47,7 @@ public async Task DeleteAsyncTest() await ServerNodeRepository.DeleteAsync(x => true); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -59,7 +59,7 @@ public async Task DeleteAsyncTest() var result1 = await service.DeleteAsync(source); Assert.IsTrue(result1); - var node = await ServerNodeRepository.SearchFor(x => x.Address == "1").FirstOrDefaultAsync(); + var node = await ServerNodeRepository.SearchFor(x => x.Id == "1").FirstOrDefaultAsync(); Assert.IsNull(node); } @@ -69,7 +69,7 @@ public async Task DeleteAsyncTest1() await ServerNodeRepository.DeleteAsync(x => true); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -78,10 +78,10 @@ public async Task DeleteAsyncTest1() var result = await service.AddAsync(source); Assert.IsTrue(result); - var result1 = await service.DeleteAsync(source.Address); + var result1 = await service.DeleteAsync(source.Id); Assert.IsTrue(result1); - var node = await ServerNodeRepository.SearchFor(x => x.Address == "1").FirstOrDefaultAsync(); + var node = await ServerNodeRepository.SearchFor(x => x.Id == "1").FirstOrDefaultAsync(); Assert.IsNull(node); } @@ -91,7 +91,7 @@ public async Task GetAllNodesAsyncTest() await ServerNodeRepository.DeleteAsync(x => true); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -112,7 +112,7 @@ public async Task GetAsyncTest() await ServerNodeRepository.DeleteAsync(x => true); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -120,10 +120,10 @@ public async Task GetAsyncTest() var result = await service.AddAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Address); + var node = await service.GetAsync(source.Id); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); @@ -136,7 +136,7 @@ public async Task UpdateAsyncTest() await ServerNodeRepository.DeleteAsync(x => true); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -151,10 +151,10 @@ public async Task UpdateAsyncTest() var result1 = await service.UpdateAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Address); + var node = await service.GetAsync(source.Id); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/AppServiceTests.cs index 9783fafd..1e6582bb 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/AppServiceTests.cs @@ -29,7 +29,8 @@ public void TestInitialize() .Build(); FluentApi.Config(fsq); freeSqlContext = new FreeSqlContext(fsq); - service = new AppService(freeSqlContext); + // todo + //service = new AppService(freeSqlContext); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ConfigServiceTests.cs index 9f53ac8a..0452465f 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ConfigServiceTests.cs @@ -35,7 +35,9 @@ public void TestInitialize() var cache = new Mock(); var config = new Config(); - service = new ConfigService( cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); + // todo + + //service = new ConfigService( cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs index 5e3d009c..429523c9 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs @@ -49,7 +49,7 @@ public async Task AddAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -63,7 +63,7 @@ public async Task AddAsyncTest() }).ToOne(); Assert.IsNotNull(node); - Assert.AreEqual(source.Address,node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); @@ -76,7 +76,7 @@ public async Task DeleteAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -101,7 +101,7 @@ public async Task DeleteAsyncTest1() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -110,7 +110,7 @@ public async Task DeleteAsyncTest1() var result = await service.AddAsync(source); Assert.IsTrue(result); - var result1 = await service.DeleteAsync(source.Address); + var result1 = await service.DeleteAsync(source.Id); Assert.IsTrue(result1); var node = fsq.Select(new @@ -126,7 +126,7 @@ public async Task GetAllNodesAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -147,7 +147,7 @@ public async Task GetAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -155,10 +155,10 @@ public async Task GetAsyncTest() var result = await service.AddAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Address); + var node = await service.GetAsync(source.Id); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); @@ -171,7 +171,7 @@ public async Task UpdateAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -186,10 +186,10 @@ public async Task UpdateAsyncTest() var result1 = await service.UpdateAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Address); + var node = await service.GetAsync(source.Id); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); diff --git a/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs index 201844f5..ad473766 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs @@ -28,7 +28,10 @@ public void TestInitialize() .UseAutoSyncStructure(true) .Build(); freeSqlContext = new FreeSqlContext(fsq); - service = new AppService(freeSqlContext); + + // todo + + //service = new AppService(freeSqlContext); fsq.Delete().Where("1=1"); } [TestMethod()] diff --git a/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs index a40185d7..cf6b8dd7 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs @@ -34,7 +34,9 @@ public void TestInitialize() var cache = new Mock(); var config = new Config(); - service = new ConfigService(cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); + // to do + + //service = new ConfigService(cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs index 4a909c37..e4ce7725 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs @@ -48,7 +48,7 @@ public async Task AddAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -62,7 +62,7 @@ public async Task AddAsyncTest() }).ToOne(); Assert.IsNotNull(node); - Assert.AreEqual(source.Address,node.Address); + Assert.AreEqual(source.Id, node.Id); //Assert.AreEqual(source.CreateTime, node.CreateTime); //Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); @@ -75,7 +75,7 @@ public async Task DeleteAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -100,7 +100,7 @@ public async Task DeleteAsyncTest1() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -109,7 +109,7 @@ public async Task DeleteAsyncTest1() var result = await service.AddAsync(source); Assert.IsTrue(result); - var result1 = await service.DeleteAsync(source.Address); + var result1 = await service.DeleteAsync(source.Id); Assert.IsTrue(result1); var node = fsq.Select(new @@ -125,7 +125,7 @@ public async Task GetAllNodesAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -146,7 +146,7 @@ public async Task GetAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -154,10 +154,10 @@ public async Task GetAsyncTest() var result = await service.AddAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Address); + var node = await service.GetAsync(source.Id); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); //Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); @@ -170,7 +170,7 @@ public async Task UpdateAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -185,10 +185,10 @@ public async Task UpdateAsyncTest() var result1 = await service.UpdateAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Address); + var node = await service.GetAsync(source.Id); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); diff --git a/test/AgileConfig.Server.ServiceTests/oracle/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/AppServiceTests.cs index f4d7b2a3..3f0a932b 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/AppServiceTests.cs @@ -29,7 +29,10 @@ public void TestInitialize() .Build(); FluentApi.Config(fsq); freeSqlContext = new FreeSqlContext(fsq); - service = new AppService(freeSqlContext); + + // todo + + //service = new AppService(freeSqlContext); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/oracle/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/ConfigServiceTests.cs index a057b488..afc25ac8 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/ConfigServiceTests.cs @@ -35,7 +35,9 @@ public void TestInitialize() var cache = new Mock(); var config = new Config(); - service = new ConfigService(cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); + // todo + + //service = new ConfigService(cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs index 1817ce79..93ea8ec8 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs @@ -49,7 +49,7 @@ public async Task AddAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -63,7 +63,7 @@ public async Task AddAsyncTest() }).ToOne(); Assert.IsNotNull(node); - Assert.AreEqual(source.Address,node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); @@ -76,7 +76,7 @@ public async Task DeleteAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -101,7 +101,7 @@ public async Task DeleteAsyncTest1() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -110,7 +110,7 @@ public async Task DeleteAsyncTest1() var result = await service.AddAsync(source); Assert.IsTrue(result); - var result1 = await service.DeleteAsync(source.Address); + var result1 = await service.DeleteAsync(source.Id); Assert.IsTrue(result1); var node = fsq.Select(new @@ -126,7 +126,7 @@ public async Task GetAllNodesAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -147,7 +147,7 @@ public async Task GetAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -155,10 +155,10 @@ public async Task GetAsyncTest() var result = await service.AddAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Address); + var node = await service.GetAsync(source.Id); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); @@ -171,7 +171,7 @@ public async Task UpdateAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -186,10 +186,10 @@ public async Task UpdateAsyncTest() var result1 = await service.UpdateAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Address); + var node = await service.GetAsync(source.Id); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs index 01049ca9..9b053e55 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs @@ -28,7 +28,8 @@ public void TestInitialize() .UseAutoSyncStructure(true) .Build(); freeSqlContext = new FreeSqlContext(fsq); - service = new AppService(freeSqlContext); + // todo + //service = new AppService(freeSqlContext); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs index c79f5425..197a0536 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs @@ -34,7 +34,9 @@ public void TestInitialize() var cache = new Mock(); var config = new Config(); - service = new ConfigService(cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); + // todo + + //service = new ConfigService(cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs index 527a85fd..b7365651 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs @@ -48,7 +48,7 @@ public async Task AddAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -62,7 +62,7 @@ public async Task AddAsyncTest() }).ToOne(); Assert.IsNotNull(node); - Assert.AreEqual(source.Address,node.Address); + Assert.AreEqual(source.Id, node.Id); Assert.AreEqual(source.CreateTime, node.CreateTime); Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); @@ -75,7 +75,7 @@ public async Task DeleteAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -100,7 +100,7 @@ public async Task DeleteAsyncTest1() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -109,7 +109,7 @@ public async Task DeleteAsyncTest1() var result = await service.AddAsync(source); Assert.IsTrue(result); - var result1 = await service.DeleteAsync(source.Address); + var result1 = await service.DeleteAsync(source.Id); Assert.IsTrue(result1); var node = fsq.Select(new @@ -125,7 +125,7 @@ public async Task GetAllNodesAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -146,7 +146,7 @@ public async Task GetAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -154,10 +154,10 @@ public async Task GetAsyncTest() var result = await service.AddAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Address); + var node = await service.GetAsync(source.Id); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); Assert.AreEqual(source.CreateTime, node.CreateTime); Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); @@ -170,7 +170,7 @@ public async Task UpdateAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -185,10 +185,10 @@ public async Task UpdateAsyncTest() var result1 = await service.UpdateAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Address); + var node = await service.GetAsync(source.Id); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); Assert.AreEqual(source.CreateTime, node.CreateTime); Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs index d17f1ff3..57683985 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs @@ -29,7 +29,8 @@ public void TestInitialize() .Build(); FluentApi.Config(fsq); freeSqlContext = new FreeSqlContext(fsq); - service = new AppService(freeSqlContext); + // todo + //service = new AppService(freeSqlContext); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/ConfigServiceTests.cs index a3ad01cb..b6d1b9ae 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/ConfigServiceTests.cs @@ -35,7 +35,8 @@ public void TestInitialize() var cache = new Mock(); var config = new Config(); - service = new ConfigService( cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); + // todo + //service = new ConfigService( cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs index 67e03011..bf18df40 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs @@ -49,7 +49,7 @@ public async Task AddAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -59,11 +59,11 @@ public async Task AddAsyncTest() Assert.IsTrue(result); var node = fsq.Select(new { - Address = "1" + Id = "1" }).ToOne(); Assert.IsNotNull(node); - Assert.AreEqual(source.Address,node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); @@ -76,7 +76,7 @@ public async Task DeleteAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -90,7 +90,7 @@ public async Task DeleteAsyncTest() var node = fsq.Select(new { - Address = "1" + Id = "1" }).ToOne(); Assert.IsNull(node); } @@ -101,7 +101,7 @@ public async Task DeleteAsyncTest1() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -110,12 +110,12 @@ public async Task DeleteAsyncTest1() var result = await service.AddAsync(source); Assert.IsTrue(result); - var result1 = await service.DeleteAsync(source.Address); + var result1 = await service.DeleteAsync(source.Id); Assert.IsTrue(result1); var node = fsq.Select(new { - Address = "1" + Id = "1" }).ToOne(); Assert.IsNull(node); } @@ -126,7 +126,7 @@ public async Task GetAllNodesAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -147,7 +147,7 @@ public async Task GetAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -155,10 +155,10 @@ public async Task GetAsyncTest() var result = await service.AddAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Address); + var node = await service.GetAsync(source.Id); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); @@ -171,7 +171,7 @@ public async Task UpdateAsyncTest() fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); - source.Address = "1"; + source.Id = "1"; source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "2"; @@ -186,10 +186,10 @@ public async Task UpdateAsyncTest() var result1 = await service.UpdateAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Address); + var node = await service.GetAsync(source.Id); Assert.IsNotNull(node); - Assert.AreEqual(source.Address, node.Address); + Assert.AreEqual(source.Id, node.Id); // Assert.AreEqual(source.CreateTime, node.CreateTime); // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); Assert.AreEqual(source.Remark, node.Remark); From f24e20c6235ad4c04505013240399cf39436c034 Mon Sep 17 00:00:00 2001 From: pengqian089 Date: Sat, 23 Dec 2023 18:36:49 +0800 Subject: [PATCH 10/45] =?UTF-8?q?=E9=87=8D=E6=96=B0=E5=AE=9E=E7=8E=B0=20Mo?= =?UTF-8?q?ngodb=20IRepository?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AgileConfig.sln | 7 ++ .../AgileConfig.Server.Data.Mongodb.csproj | 4 + .../MongodbRepository.cs | 91 +++++++++++++++++++ ...nfig.Server.Data.Repository.Mongodb.csproj | 9 ++ .../Class1.cs | 5 + 5 files changed, 116 insertions(+) create mode 100644 src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/AgileConfig.Server.Data.Repository.Mongodb.csproj create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/Class1.cs diff --git a/AgileConfig.sln b/AgileConfig.sln index 852b076e..4176ab09 100644 --- a/AgileConfig.sln +++ b/AgileConfig.sln @@ -48,6 +48,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Abs EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Repository.Freesql", "src\AgileConfig.Server.Data.Repository.Freesql\AgileConfig.Server.Data.Repository.Freesql.csproj", "{955F64CC-9EAC-4563-804D-6E2CF9547357}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Repository.Mongodb", "src\AgileConfig.Server.Data.Repository.Mongodb\AgileConfig.Server.Data.Repository.Mongodb.csproj", "{C6B7A5A6-7287-4A20-9336-EBE82A5256F1}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -118,6 +120,10 @@ Global {955F64CC-9EAC-4563-804D-6E2CF9547357}.Debug|Any CPU.Build.0 = Debug|Any CPU {955F64CC-9EAC-4563-804D-6E2CF9547357}.Release|Any CPU.ActiveCfg = Release|Any CPU {955F64CC-9EAC-4563-804D-6E2CF9547357}.Release|Any CPU.Build.0 = Release|Any CPU + {C6B7A5A6-7287-4A20-9336-EBE82A5256F1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C6B7A5A6-7287-4A20-9336-EBE82A5256F1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C6B7A5A6-7287-4A20-9336-EBE82A5256F1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C6B7A5A6-7287-4A20-9336-EBE82A5256F1}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -139,6 +145,7 @@ Global {E35504A4-E032-4EEA-A53A-12C99B56680B} = {F277EC27-8C0E-4490-9645-F5F3244F9246} {E8101403-72C9-40FB-BCEE-16ED5C23A495} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {955F64CC-9EAC-4563-804D-6E2CF9547357} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} + {C6B7A5A6-7287-4A20-9336-EBE82A5256F1} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {7F10DB58-5B6F-4EAC-994F-14E8046B306F} diff --git a/src/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj b/src/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj index 40fc815e..dc28253b 100644 --- a/src/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj +++ b/src/AgileConfig.Server.Data.Mongodb/AgileConfig.Server.Data.Mongodb.csproj @@ -13,4 +13,8 @@ + + + + diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs new file mode 100644 index 00000000..d05a1be3 --- /dev/null +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs @@ -0,0 +1,91 @@ +using System.Linq.Expressions; +using AgileConfig.Server.Common; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using MongoDB.Driver; +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.Data.Mongodb; + +public class MongodbRepository : Abstraction.IRepository + where TEntity : IEntity, new() +{ + private readonly MongodbAccess _access; + + public MongodbRepository(string? connectionString) + { + _access = new MongodbAccess(connectionString); + } + + [ActivatorUtilitiesConstructor] + public MongodbRepository(IConfiguration configuration) + { + var connectionString = configuration["db:conn"]; + _access = new MongodbAccess(connectionString); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + } + + public async Task> AllAsync() + { + return await _access.MongoQueryable.ToListAsync(); + } + + private Expression> GetIdPropertyFilter(TId id) + { + var expression = _access.MongoQueryable.Where(x => Equals(x.Id, id)).Expression; + return Expression.Lambda>(expression); + } + + public async Task GetAsync(TId id) + { + var filter = GetIdPropertyFilter(id); + return await (await _access.Collection.FindAsync(filter)).SingleOrDefaultAsync(); + } + + public async Task UpdateAsync(TEntity entity) + { + var filter = GetIdPropertyFilter(entity.Id); + await _access.Collection.ReplaceOneAsync(filter, entity); + } + + public async Task UpdateAsync(IList entities) + { + var writes = entities + .Select(x => new ReplaceOneModel(GetIdPropertyFilter(x.Id), x)) + .ToList(); + await _access.Collection.BulkWriteAsync(writes); + } + + public async Task DeleteAsync(TEntity entity) + { + var filter = GetIdPropertyFilter(entity.Id); + await _access.Collection.DeleteOneAsync(filter); + } + + public async Task DeleteAsync(IList entities) + { + var filter = Builders.Filter.In(x => x.Id, entities.Select(y => y.Id)); + await _access.Collection.DeleteManyAsync(filter); + } + + public async Task InsertAsync(TEntity entity) + { + await _access.Collection.InsertOneAsync(entity); + return entity; + } + + public async Task InsertAsync(IList entities) + { + if(entities.Count > 0) + await _access.Collection.InsertManyAsync(entities); + } + + public async Task> QueryAsync(Expression> exp) + { + return await _access.MongoQueryable.Where(exp).ToListAsync(); + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/AgileConfig.Server.Data.Repository.Mongodb.csproj b/src/AgileConfig.Server.Data.Repository.Mongodb/AgileConfig.Server.Data.Repository.Mongodb.csproj new file mode 100644 index 00000000..3a635329 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/AgileConfig.Server.Data.Repository.Mongodb.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/Class1.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/Class1.cs new file mode 100644 index 00000000..aee0e2b8 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/Class1.cs @@ -0,0 +1,5 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class Class1 +{ +} \ No newline at end of file From 238a80d657e70853bba622b0431bd89cbda67ddb Mon Sep 17 00:00:00 2001 From: pengqian089 Date: Sat, 23 Dec 2023 18:58:59 +0800 Subject: [PATCH 11/45] Mongodb Repository Implement --- ...nfig.Server.Data.Repository.Mongodb.csproj | 5 +++++ .../AppInheritancedRepository.cs | 13 ++++++++++++ .../AppRepository.cs | 13 ++++++++++++ .../Class1.cs | 5 ----- .../ConfigPublishedRepository.cs | 13 ++++++++++++ .../ConfigRepository.cs | 13 ++++++++++++ .../MongodbRepositoryExt.cs | 21 +++++++++++++++++++ .../PublishDetailRepository.cs | 13 ++++++++++++ .../PublishTimelineRepository.cs | 13 ++++++++++++ .../ServerNodeRepository.cs | 13 ++++++++++++ .../ServiceInfoRepository.cs | 13 ++++++++++++ .../SettingRepository.cs | 13 ++++++++++++ .../SysLogRepository.cs | 13 ++++++++++++ .../UserAppAuthRepository.cs | 13 ++++++++++++ .../UserRepository.cs | 13 ++++++++++++ .../UserRoleRepository.cs | 13 ++++++++++++ .../Usings.cs | 5 +++++ 17 files changed, 200 insertions(+), 5 deletions(-) create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/AppInheritancedRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/AppRepository.cs delete mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/Class1.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/ConfigPublishedRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/ConfigRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/PublishDetailRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/PublishTimelineRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/ServerNodeRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/ServiceInfoRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/SettingRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/SysLogRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/UserAppAuthRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/UserRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/UserRoleRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/Usings.cs diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/AgileConfig.Server.Data.Repository.Mongodb.csproj b/src/AgileConfig.Server.Data.Repository.Mongodb/AgileConfig.Server.Data.Repository.Mongodb.csproj index 3a635329..ef554dcd 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/AgileConfig.Server.Data.Repository.Mongodb.csproj +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/AgileConfig.Server.Data.Repository.Mongodb.csproj @@ -6,4 +6,9 @@ enable + + + + + diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/AppInheritancedRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/AppInheritancedRepository.cs new file mode 100644 index 00000000..a28de534 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/AppInheritancedRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class AppInheritancedRepository : MongodbRepository, IAppInheritancedRepository +{ + public AppInheritancedRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public AppInheritancedRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/AppRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/AppRepository.cs new file mode 100644 index 00000000..0085b33c --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/AppRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class AppRepository: MongodbRepository, IAppRepository +{ + public AppRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public AppRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/Class1.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/Class1.cs deleted file mode 100644 index aee0e2b8..00000000 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/Class1.cs +++ /dev/null @@ -1,5 +0,0 @@ -namespace AgileConfig.Server.Data.Repository.Mongodb; - -public class Class1 -{ -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigPublishedRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigPublishedRepository.cs new file mode 100644 index 00000000..319ea636 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigPublishedRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class ConfigPublishedRepository : MongodbRepository, IConfigPublishedRepository +{ + public ConfigPublishedRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public ConfigPublishedRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigRepository.cs new file mode 100644 index 00000000..baece651 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/ConfigRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class ConfigRepository: MongodbRepository, IConfigRepository +{ + public ConfigRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public ConfigRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs new file mode 100644 index 00000000..8c4d37ea --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs @@ -0,0 +1,21 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public static class MongodbRepositoryExt +{ + public static void AddMongodbRepository(this IServiceCollection services) + { + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/PublishDetailRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/PublishDetailRepository.cs new file mode 100644 index 00000000..23c29e5e --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/PublishDetailRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class PublishDetailRepository: MongodbRepository, IPublishDetailRepository +{ + public PublishDetailRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public PublishDetailRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/PublishTimelineRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/PublishTimelineRepository.cs new file mode 100644 index 00000000..402b1247 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/PublishTimelineRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class PublishTimelineRepository: MongodbRepository, IPublishTimelineRepository +{ + public PublishTimelineRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public PublishTimelineRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/ServerNodeRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/ServerNodeRepository.cs new file mode 100644 index 00000000..580f355c --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/ServerNodeRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class ServerNodeRepository: MongodbRepository, IServerNodeRepository +{ + public ServerNodeRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public ServerNodeRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/ServiceInfoRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/ServiceInfoRepository.cs new file mode 100644 index 00000000..c6f72023 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/ServiceInfoRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class ServiceInfoRepository: MongodbRepository, IServiceInfoRepository +{ + public ServiceInfoRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public ServiceInfoRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/SettingRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/SettingRepository.cs new file mode 100644 index 00000000..3641addf --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/SettingRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class SettingRepository: MongodbRepository, ISettingRepository +{ + public SettingRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public SettingRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/SysLogRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/SysLogRepository.cs new file mode 100644 index 00000000..d4dca8f3 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/SysLogRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class SysLogRepository: MongodbRepository, ISysLogRepository +{ + public SysLogRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public SysLogRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/UserAppAuthRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/UserAppAuthRepository.cs new file mode 100644 index 00000000..ef2da811 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/UserAppAuthRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class UserAppAuthRepository: MongodbRepository, IUserAppAuthRepository +{ + public UserAppAuthRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public UserAppAuthRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/UserRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/UserRepository.cs new file mode 100644 index 00000000..fcae1cab --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/UserRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class UserRepository: MongodbRepository, IUserRepository +{ + public UserRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public UserRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/UserRoleRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/UserRoleRepository.cs new file mode 100644 index 00000000..e2b2f0e0 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/UserRoleRepository.cs @@ -0,0 +1,13 @@ +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class UserRoleRepository: MongodbRepository, IUserRoleRepository +{ + public UserRoleRepository(string? connectionString) : base(connectionString) + { + } + + [ActivatorUtilitiesConstructor] + public UserRoleRepository(IConfiguration configuration) : base(configuration) + { + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/Usings.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/Usings.cs new file mode 100644 index 00000000..94afc197 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/Usings.cs @@ -0,0 +1,5 @@ +global using AgileConfig.Server.Data.Abstraction; +global using AgileConfig.Server.Data.Entity; +global using AgileConfig.Server.Data.Mongodb; +global using Microsoft.Extensions.Configuration; +global using Microsoft.Extensions.DependencyInjection; \ No newline at end of file From 17bda7d87ff916d216301ee9cfc23e662adbe0c2 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 24 Dec 2023 02:05:23 +0800 Subject: [PATCH 12/45] =?UTF-8?q?=E9=87=8D=E6=9E=84=20ConfigService;=20?= =?UTF-8?q?=E9=87=8D=E6=9E=84=20FreesqlRepository=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AgileConfig.Server.Apisite.csproj | 2 + .../Controllers/ConfigController.cs | 2 +- src/AgileConfig.Server.Apisite/Startup.cs | 39 ++- src/AgileConfig.Server.Common/EnvAccessor.cs | 35 ++ .../EnvFreeSqlFactory.cs | 17 + .../FreesqlRepository.cs | 7 +- .../IFreeSqlFactory.cs | 7 + .../ServiceCollectionExt.cs | 6 +- .../AppInheritancedRepository.cs | 2 +- .../AppRepository.cs | 2 +- .../ConfigPublishedRepository.cs | 2 +- .../ConfigRepository.cs | 2 +- .../PublishDetailRepository.cs | 2 +- .../PublishTimelineRepository.cs | 2 +- .../ServerNodeRepository.cs | 2 +- .../ServiceInfoRepository.cs | 2 +- .../SettingRepository.cs | 2 +- .../SysLogRepository.cs | 2 +- .../UserAppAuthRepository.cs | 2 +- .../UserRepository.cs | 2 +- .../UserRoleRepository.cs | 2 +- .../IConfigService.cs | 2 +- .../ConfigService.cs | 306 +++++++++--------- .../ConfigService.cs | 306 ++++++++---------- .../ConfigStatusUpdateRegister.cs | 8 +- 25 files changed, 396 insertions(+), 367 deletions(-) create mode 100644 src/AgileConfig.Server.Common/EnvAccessor.cs create mode 100644 src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs create mode 100644 src/AgileConfig.Server.Data.Freesql/IFreeSqlFactory.cs diff --git a/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj b/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj index a6dd4940..f01b98d8 100644 --- a/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj +++ b/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj @@ -38,6 +38,8 @@ + + diff --git a/src/AgileConfig.Server.Apisite/Controllers/ConfigController.cs b/src/AgileConfig.Server.Apisite/Controllers/ConfigController.cs index 630b3bfb..aed619e3 100644 --- a/src/AgileConfig.Server.Apisite/Controllers/ConfigController.cs +++ b/src/AgileConfig.Server.Apisite/Controllers/ConfigController.cs @@ -572,7 +572,7 @@ public async Task Publish([FromBody] PublishLogVM model, string e var appId = model.AppId; var userId = await this.GetCurrentUserId(_userService); - var ret = _configService.Publish(appId, model.Ids, model.Log, userId, env); + var ret = await _configService.Publish(appId, model.Ids, model.Log, userId, env); if (ret.result) { diff --git a/src/AgileConfig.Server.Apisite/Startup.cs b/src/AgileConfig.Server.Apisite/Startup.cs index 7c1c993f..35b31442 100644 --- a/src/AgileConfig.Server.Apisite/Startup.cs +++ b/src/AgileConfig.Server.Apisite/Startup.cs @@ -20,6 +20,7 @@ using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; +using AgileConfig.Server.Data.Repository.Freesql; namespace AgileConfig.Server.Apisite { @@ -62,9 +63,9 @@ public void ConfigureServices(IServiceCollection services) { services.AddDefaultHttpClient(IsTrustSSL(Configuration)); services.AddRestClient(); - + services.AddMemoryCache(); - + services.AddCors(); services.AddMvc().AddRazorRuntimeCompilation(); @@ -73,20 +74,17 @@ public void ConfigureServices(IServiceCollection services) AddSwaggerService(services); } - if (string.Equals(Configuration["db:provider"], "mongodb", StringComparison.OrdinalIgnoreCase)) - { - services.AddBusinessForMongoServices(); - } - else - { - services.AddFreeSqlDbContext(); - services.AddBusinessServices(); - } - + services.AddEnvAccessor(); + + // Add freesqlRepositories or other repositories + AddDataRepositories(services); + + services.AddBusinessServices(); + services.ConfigureOptions(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(); - + services.AddHostedService(); services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = true); @@ -159,5 +157,20 @@ private void AddSwaggerMiddleWare(IApplicationBuilder app) } + private void AddDataRepositories(IServiceCollection services) + { + if (string.Equals(Configuration["db:provider"], "mongodb", StringComparison.OrdinalIgnoreCase)) + { + // todo + + // services.AddMongoRepository(); + } + else + { + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + } + } + } } diff --git a/src/AgileConfig.Server.Common/EnvAccessor.cs b/src/AgileConfig.Server.Common/EnvAccessor.cs new file mode 100644 index 00000000..e2451885 --- /dev/null +++ b/src/AgileConfig.Server.Common/EnvAccessor.cs @@ -0,0 +1,35 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using System.Linq; + +namespace AgileConfig.Server.Common +{ + public interface IEnvAccessor + { + string Env { get; } + } + + public class EnvAccessor : IEnvAccessor + { + public EnvAccessor(IHttpContextAccessor httpContextAccessor) + { + var env = httpContextAccessor.HttpContext.Request.Query["env"].FirstOrDefault(); + if (string.IsNullOrEmpty(env)) + { + env = "DEV"; + } + Env = env; + } + public string Env { get; } + } + + public static class EnvAccessorServiceCollectionExtension + { + public static IServiceCollection AddEnvAccessor(this IServiceCollection services) + { + services.AddSingleton(); + + return services; + } + } +} diff --git a/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs b/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs new file mode 100644 index 00000000..da07a6cb --- /dev/null +++ b/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs @@ -0,0 +1,17 @@ +using AgileConfig.Server.Common; + +namespace AgileConfig.Server.Data.Freesql +{ + public class EnvFreeSqlFactory : IFreeSqlFactory + { + private readonly IEnvAccessor _envAccessor; + public EnvFreeSqlFactory(IEnvAccessor envAccessor) + { + _envAccessor = envAccessor; + } + public IFreeSql Create() + { + return FreeSQL.GetInstance(_envAccessor.Env); + } + } +} diff --git a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs index b6df981b..5ddb651a 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs @@ -3,6 +3,7 @@ using FreeSql; using System; using System.Collections.Generic; +using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; @@ -10,12 +11,10 @@ namespace AgileConfig.Server.Data.Freesql { public class FreesqlRepository : IRepository where T : class, IEntity { - private readonly IFreeSql _freeSql; private readonly IBaseRepository _repository; - public FreesqlRepository(IFreeSql freeSql) + public FreesqlRepository(IFreeSqlFactory freeFactory) { - _freeSql = freeSql; - _repository = freeSql.GetRepository(); + _repository = freeFactory.Create().GetRepository(); } public Task> AllAsync() diff --git a/src/AgileConfig.Server.Data.Freesql/IFreeSqlFactory.cs b/src/AgileConfig.Server.Data.Freesql/IFreeSqlFactory.cs new file mode 100644 index 00000000..8d1d2600 --- /dev/null +++ b/src/AgileConfig.Server.Data.Freesql/IFreeSqlFactory.cs @@ -0,0 +1,7 @@ +namespace AgileConfig.Server.Data.Freesql +{ + public interface IFreeSqlFactory + { + IFreeSql Create(); + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs b/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs index 20011bb3..c56e0461 100644 --- a/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs +++ b/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs @@ -7,11 +7,9 @@ namespace AgileConfig.Server.Data.Freesql { public static class ServiceCollectionExt { - public static void AddFreeSqlDbContext(this IServiceCollection sc) + public static void AddFreeSqlFactory(this IServiceCollection sc) { - sc.AddFreeDbContext(options => options.UseFreeSql(FreeSQL.Instance)); - //sc.AddSingleton(FreeSQL.Instance); - //sc.AddScoped(); + sc.AddSingleton(); } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs index e680ae75..ddc43eb9 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class AppInheritancedRepository : FreesqlRepository, IAppInheritancedRepository { - public AppInheritancedRepository(IFreeSql freeSql) : base(freeSql) + public AppInheritancedRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs index cff884dc..b25ae228 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class AppRepository : FreesqlRepository, IAppRepository { - public AppRepository(IFreeSql freeSql) : base(freeSql) + public AppRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs index 0482893c..a24f19a2 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class ConfigPublishedRepository : FreesqlRepository, IConfigPublishedRepository { - public ConfigPublishedRepository(IFreeSql freeSql) : base(freeSql) + public ConfigPublishedRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs index 88e08380..876a2410 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class ConfigRepository : FreesqlRepository, IConfigRepository { - public ConfigRepository(IFreeSql freeSql) : base(freeSql) + public ConfigRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs index 2048bbb2..bace3a36 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class PublishDetailRepository : FreesqlRepository, IPublishDetailRepository { - public PublishDetailRepository(IFreeSql freeSql) : base(freeSql) + public PublishDetailRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs index a2198185..55660104 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class PublishTimelineRepository : FreesqlRepository, IPublishTimelineRepository { - public PublishTimelineRepository(IFreeSql freeSql) : base(freeSql) + public PublishTimelineRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs index 0d2fc202..c7c0892a 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class ServerNodeRepository : FreesqlRepository, IServerNodeRepository { - public ServerNodeRepository(IFreeSql freeSql) : base(freeSql) + public ServerNodeRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs index 461b99ee..57175349 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class ServiceInfoRepository : FreesqlRepository, IServiceInfoRepository { - public ServiceInfoRepository(IFreeSql freeSql) : base(freeSql) + public ServiceInfoRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs index b2a913b6..9d9b6732 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class SettingRepository : FreesqlRepository, ISettingRepository { - public SettingRepository(IFreeSql freeSql) : base(freeSql) + public SettingRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs index 0d5eec94..0be250ec 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class SysLogRepository : FreesqlRepository, ISysLogRepository { - public SysLogRepository(IFreeSql freeSql) : base(freeSql) + public SysLogRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs index 9c403d0f..286f93eb 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class UserAppAuthRepository : FreesqlRepository, IUserAppAuthRepository { - public UserAppAuthRepository(IFreeSql freeSql) : base(freeSql) + public UserAppAuthRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs index 866f8e57..466b1733 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class UserRepository : FreesqlRepository, IUserRepository { - public UserRepository(IFreeSql freeSql) : base(freeSql) + public UserRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs index 17a53c96..8466ae44 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class UserRoleRepository : FreesqlRepository, IUserRoleRepository { - public UserRoleRepository(IFreeSql freeSql) : base(freeSql) + public UserRoleRepository(IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.IService/IConfigService.cs b/src/AgileConfig.Server.IService/IConfigService.cs index 5039d14e..c484de01 100644 --- a/src/AgileConfig.Server.IService/IConfigService.cs +++ b/src/AgileConfig.Server.IService/IConfigService.cs @@ -22,7 +22,7 @@ public interface IConfigService: IDisposable /// /// /// - (bool result, string publishTimelineId) Publish(string appId,string[] ids, string log, string operatorr, string env); + Task<(bool result, string publishTimelineId)> Publish(string appId,string[] ids, string log, string operatorr, string env); Task GetAsync(string id, string env); diff --git a/src/AgileConfig.Server.Mongodb.Service/ConfigService.cs b/src/AgileConfig.Server.Mongodb.Service/ConfigService.cs index 5b0d16bc..d2d96c2a 100644 --- a/src/AgileConfig.Server.Mongodb.Service/ConfigService.cs +++ b/src/AgileConfig.Server.Mongodb.Service/ConfigService.cs @@ -419,159 +419,163 @@ public void Dispose() /// 发布日志 /// 操作员 /// - public (bool result, string publishTimelineId) Publish(string appId, string[] ids, string log, string operatorr, + public Task<(bool result, string publishTimelineId)> Publish(string appId, string[] ids, string log, string operatorr, string env) { - lock (Lockobj) - { - var waitPublishConfigs = GetRepository(env).SearchFor(x => - x.AppId == appId && - x.Env == env && - x.Status == ConfigStatus.Enabled && - x.EditStatus != EditStatus.Commit).ToList(); - if (ids != null && ids.Any()) - { - //如果ids传值了,过滤一下 - waitPublishConfigs = waitPublishConfigs.Where(x => ids.Contains(x.Id)).ToList(); - } - - //这里默认admin console 实例只部署一个,如果部署多个同步操作,高并发的时候这个version会有问题 - var versionMax = GetRepository(env).SearchFor(x => x.AppId == appId).Max(x => x.Version); - - var user = userService.GetUser(operatorr); - - var publishTimelineNode = new PublishTimeline(); - publishTimelineNode.AppId = appId; - publishTimelineNode.Id = Guid.NewGuid().ToString("N"); - publishTimelineNode.PublishTime = DateTime.Now; - publishTimelineNode.PublishUserId = user.Id; - publishTimelineNode.PublishUserName = user.UserName; - publishTimelineNode.Version = versionMax + 1; - publishTimelineNode.Log = log; - publishTimelineNode.Env = env; - - var publishDetails = new List(); - waitPublishConfigs.ForEach(x => - { - publishDetails.Add(new PublishDetail() - { - AppId = appId, - ConfigId = x.Id, - Description = x.Description, - EditStatus = x.EditStatus, - Group = x.Group, - Id = Guid.NewGuid().ToString("N"), - Key = x.Key, - Value = x.Value, - PublishTimelineId = publishTimelineNode.Id, - Version = publishTimelineNode.Version, - Env = env - }); - - if (x.EditStatus == EditStatus.Deleted) - { - x.OnlineStatus = OnlineStatus.WaitPublish; - x.Status = ConfigStatus.Deleted; - } - else - { - x.OnlineStatus = OnlineStatus.Online; - x.Status = ConfigStatus.Enabled; - } - - x.EditStatus = EditStatus.Commit; - x.OnlineStatus = OnlineStatus.Online; - }); - - //当前发布的配置 - var publishedConfigs = GetRepository(env) - .SearchFor(x => x.Status == ConfigStatus.Enabled && x.AppId == appId && x.Env == env).ToList(); - //复制一份新版本,最后插入发布表 - var publishedConfigsCopy = new List(); - publishedConfigs.ForEach(x => - { - publishedConfigsCopy.Add(new ConfigPublished() - { - AppId = x.AppId, - ConfigId = x.ConfigId, - Group = x.Group, - Id = Guid.NewGuid().ToString("N"), - Key = x.Key, - PublishTimelineId = publishTimelineNode.Id, - PublishTime = publishTimelineNode.PublishTime, - Status = ConfigStatus.Enabled, - Version = publishTimelineNode.Version, - Value = x.Value, - Env = x.Env - }); - x.Status = ConfigStatus.Deleted; - }); - - publishDetails.ForEach(x => - { - if (x.EditStatus == EditStatus.Add) - { - publishedConfigsCopy.Add(new ConfigPublished() - { - AppId = x.AppId, - ConfigId = x.ConfigId, - Group = x.Group, - Id = Guid.NewGuid().ToString("N"), - Key = x.Key, - PublishTimelineId = publishTimelineNode.Id, - PublishTime = publishTimelineNode.PublishTime, - Status = ConfigStatus.Enabled, - Value = x.Value, - Version = publishTimelineNode.Version, - Env = env - }); - } - - if (x.EditStatus == EditStatus.Edit) - { - var oldEntity = publishedConfigsCopy.FirstOrDefault(c => c.ConfigId == x.ConfigId); - if (oldEntity == null) - { - //do nothing - } - else - { - //edit - oldEntity.Version = publishTimelineNode.Version; - oldEntity.Group = x.Group; - oldEntity.Key = x.Key; - oldEntity.Value = x.Value; - oldEntity.PublishTime = publishTimelineNode.PublishTime; - } - } - - if (x.EditStatus == EditStatus.Deleted) - { - var oldEntity = publishedConfigsCopy.FirstOrDefault(c => c.ConfigId == x.ConfigId); - if (oldEntity == null) - { - //do nothing - } - else - { - //remove - publishedConfigsCopy.Remove(oldEntity); - } - } - }); - - GetRepository(env).Update(waitPublishConfigs); - GetRepository(env).Insert(publishTimelineNode); - GetRepository(env).Insert(publishDetails); - GetRepository(env).Update(publishedConfigs); - GetRepository(env).Insert(publishedConfigsCopy); - - - ClearAppPublishedConfigsMd5Cache(appId, env); - ClearAppPublishedConfigsMd5CacheWithInheritanced(appId, env); - - return (true, publishTimelineNode.Id); - } + return null; + + // remove + + //lock (Lockobj) + //{ + // var waitPublishConfigs = GetRepository(env).SearchFor(x => + // x.AppId == appId && + // x.Env == env && + // x.Status == ConfigStatus.Enabled && + // x.EditStatus != EditStatus.Commit).ToList(); + // if (ids != null && ids.Any()) + // { + // //如果ids传值了,过滤一下 + // waitPublishConfigs = waitPublishConfigs.Where(x => ids.Contains(x.Id)).ToList(); + // } + + // //这里默认admin console 实例只部署一个,如果部署多个同步操作,高并发的时候这个version会有问题 + // var versionMax = GetRepository(env).SearchFor(x => x.AppId == appId).Max(x => x.Version); + + // var user = userService.GetUser(operatorr); + + // var publishTimelineNode = new PublishTimeline(); + // publishTimelineNode.AppId = appId; + // publishTimelineNode.Id = Guid.NewGuid().ToString("N"); + // publishTimelineNode.PublishTime = DateTime.Now; + // publishTimelineNode.PublishUserId = user.Id; + // publishTimelineNode.PublishUserName = user.UserName; + // publishTimelineNode.Version = versionMax + 1; + // publishTimelineNode.Log = log; + // publishTimelineNode.Env = env; + + // var publishDetails = new List(); + // waitPublishConfigs.ForEach(x => + // { + // publishDetails.Add(new PublishDetail() + // { + // AppId = appId, + // ConfigId = x.Id, + // Description = x.Description, + // EditStatus = x.EditStatus, + // Group = x.Group, + // Id = Guid.NewGuid().ToString("N"), + // Key = x.Key, + // Value = x.Value, + // PublishTimelineId = publishTimelineNode.Id, + // Version = publishTimelineNode.Version, + // Env = env + // }); + + // if (x.EditStatus == EditStatus.Deleted) + // { + // x.OnlineStatus = OnlineStatus.WaitPublish; + // x.Status = ConfigStatus.Deleted; + // } + // else + // { + // x.OnlineStatus = OnlineStatus.Online; + // x.Status = ConfigStatus.Enabled; + // } + + // x.EditStatus = EditStatus.Commit; + // x.OnlineStatus = OnlineStatus.Online; + // }); + + // //当前发布的配置 + // var publishedConfigs = GetRepository(env) + // .SearchFor(x => x.Status == ConfigStatus.Enabled && x.AppId == appId && x.Env == env).ToList(); + // //复制一份新版本,最后插入发布表 + // var publishedConfigsCopy = new List(); + // publishedConfigs.ForEach(x => + // { + // publishedConfigsCopy.Add(new ConfigPublished() + // { + // AppId = x.AppId, + // ConfigId = x.ConfigId, + // Group = x.Group, + // Id = Guid.NewGuid().ToString("N"), + // Key = x.Key, + // PublishTimelineId = publishTimelineNode.Id, + // PublishTime = publishTimelineNode.PublishTime, + // Status = ConfigStatus.Enabled, + // Version = publishTimelineNode.Version, + // Value = x.Value, + // Env = x.Env + // }); + // x.Status = ConfigStatus.Deleted; + // }); + + // publishDetails.ForEach(x => + // { + // if (x.EditStatus == EditStatus.Add) + // { + // publishedConfigsCopy.Add(new ConfigPublished() + // { + // AppId = x.AppId, + // ConfigId = x.ConfigId, + // Group = x.Group, + // Id = Guid.NewGuid().ToString("N"), + // Key = x.Key, + // PublishTimelineId = publishTimelineNode.Id, + // PublishTime = publishTimelineNode.PublishTime, + // Status = ConfigStatus.Enabled, + // Value = x.Value, + // Version = publishTimelineNode.Version, + // Env = env + // }); + // } + + // if (x.EditStatus == EditStatus.Edit) + // { + // var oldEntity = publishedConfigsCopy.FirstOrDefault(c => c.ConfigId == x.ConfigId); + // if (oldEntity == null) + // { + // //do nothing + // } + // else + // { + // //edit + // oldEntity.Version = publishTimelineNode.Version; + // oldEntity.Group = x.Group; + // oldEntity.Key = x.Key; + // oldEntity.Value = x.Value; + // oldEntity.PublishTime = publishTimelineNode.PublishTime; + // } + // } + + // if (x.EditStatus == EditStatus.Deleted) + // { + // var oldEntity = publishedConfigsCopy.FirstOrDefault(c => c.ConfigId == x.ConfigId); + // if (oldEntity == null) + // { + // //do nothing + // } + // else + // { + // //remove + // publishedConfigsCopy.Remove(oldEntity); + // } + // } + // }); + + // GetRepository(env).Update(waitPublishConfigs); + // GetRepository(env).Insert(publishTimelineNode); + // GetRepository(env).Insert(publishDetails); + // GetRepository(env).Update(publishedConfigs); + // GetRepository(env).Insert(publishedConfigsCopy); + + + // ClearAppPublishedConfigsMd5Cache(appId, env); + // ClearAppPublishedConfigsMd5CacheWithInheritanced(appId, env); + + // return (true, publishTimelineNode.Id); + //} } public async Task IsPublishedAsync(string configId, string env) diff --git a/src/AgileConfig.Server.Service/ConfigService.cs b/src/AgileConfig.Server.Service/ConfigService.cs index 66c3aab5..ce0740b8 100644 --- a/src/AgileConfig.Server.Service/ConfigService.cs +++ b/src/AgileConfig.Server.Service/ConfigService.cs @@ -7,8 +7,10 @@ using System.Linq; using System.Text; using Microsoft.Extensions.Caching.Memory; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction; +using System.Linq.Expressions; +using System.Threading; namespace AgileConfig.Server.Service { @@ -18,21 +20,28 @@ public class ConfigService : IConfigService private readonly IAppService _appService; private readonly ISettingService _settingService; private readonly IUserService _userService; - - public ConfigService(IMemoryCache memoryCache, IAppService appService, ISettingService settingService, - IUserService userService) + private readonly IConfigRepository _configRepository; + private readonly IConfigPublishedRepository _configPublishedRepository; + private readonly IPublishDetailRepository _publishDetailRepository; + private readonly IPublishTimelineRepository _publishTimelineRepository; + + public ConfigService(IMemoryCache memoryCache, + IAppService appService, + ISettingService settingService, + IUserService userService, + IConfigRepository configRepository, + IConfigPublishedRepository configPublishedRepository, + IPublishDetailRepository publishDetailRepository, + IPublishTimelineRepository publishTimelineRepository) { _memoryCache = memoryCache; _appService = appService; _settingService = settingService; _userService = userService; - } - - public ConfigService(IAppService appService, ISettingService settingService, IUserService userService) - { - _appService = appService; - _settingService = settingService; - _userService = userService; + _configRepository = configRepository; + _configPublishedRepository = configPublishedRepository; + _publishDetailRepository = publishDetailRepository; + _publishTimelineRepository = publishTimelineRepository; } public async Task IfEnvEmptySetDefaultAsync(string env) @@ -58,49 +67,33 @@ public async Task AddAsync(Config config, string env) config.Value = ""; } - using var dbcontext = FreeSqlDbContextFactory.Create(env); + await _configRepository.InsertAsync(config); - await dbcontext.Configs.AddAsync(config); - int x = await dbcontext.SaveChangesAsync(); - - var result = x > 0; - - return result; + return true; } public async Task UpdateAsync(Config config, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - await dbcontext.UpdateAsync(config); - var x = await dbcontext.SaveChangesAsync(); - - var result = x > 0; + await _configRepository.UpdateAsync(config); - return result; + return true; } public async Task UpdateAsync(List configs, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); foreach (var item in configs) { - await dbcontext.UpdateAsync(item); + await _configRepository.UpdateAsync(item); } - var x = await dbcontext.SaveChangesAsync(); - - var result = x > 0; - - return result; + return true; } public async Task CancelEdit(List ids, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - foreach (var configId in ids) { - var config = await dbcontext.Configs.Where(c => c.Id == configId).ToOneAsync(); + var config = await _configRepository.GetAsync(configId); ; if (config == null) { @@ -114,7 +107,7 @@ public async Task CancelEdit(List ids, string env) if (config.EditStatus == EditStatus.Add) { - await dbcontext.Configs.RemoveAsync(x => x.Id == configId); + await _configRepository.DeleteAsync(config); } if (config.EditStatus == EditStatus.Deleted || config.EditStatus == EditStatus.Edit) @@ -136,117 +129,96 @@ public async Task CancelEdit(List ids, string env) config.OnlineStatus = OnlineStatus.Online; } - await dbcontext.Configs.UpdateAsync(config); + await _configRepository.UpdateAsync(config); } } - var result = await dbcontext.SaveChangesAsync(); - - return result > 0; + return true; } public async Task DeleteAsync(Config config, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - config = await dbcontext.Configs.Where(c => c.Id == config.Id).ToOneAsync(); + config = await _configRepository.GetAsync(config.Id); if (config != null) { - dbcontext.Configs.Remove(config); + await _configRepository.DeleteAsync(config); } - int x = await dbcontext.SaveChangesAsync(); - - var result = x > 0; - - return result; + return true; } public async Task DeleteAsync(string configId, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var config = await dbcontext.Configs.Where(c => c.Id == configId).ToOneAsync(); + var config = await _configRepository.GetAsync(configId); if (config != null) { - dbcontext.Configs.Remove(config); + await _configRepository.DeleteAsync(config); } - int x = await dbcontext.SaveChangesAsync(); - - var result = x > 0; - - return result; + return true; } public async Task GetAsync(string id, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var config = await dbcontext.Configs.Where(c => c.Id == id).ToOneAsync(); + var config = await _configRepository.GetAsync(id); return config; } public async Task> GetAllConfigsAsync(string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - return await dbcontext.Configs.Where(c => c.Status == ConfigStatus.Enabled && c.Env == env).ToListAsync(); + return await _configRepository.QueryAsync(c => c.Status == ConfigStatus.Enabled && c.Env == env); } public async Task GetByAppIdKeyEnv(string appId, string group, string key, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); + Expression> exp = (c) => c.AppId == appId && + c.Key == key && + c.Env == env && + c.Status == ConfigStatus.Enabled; - var q = dbcontext.Configs.Where(c => - c.AppId == appId && - c.Key == key && - c.Env == env && - c.Status == ConfigStatus.Enabled - ); if (string.IsNullOrEmpty(group)) { - q = q.Where(c => c.Group == "" || c.Group == null); + Expression> exp1 = c => c.Group == "" || c.Group == null; + exp.And(exp1); } else { - q = q.Where(c => c.Group == group); + Expression> exp1 = c => c.Group == group; + exp.And(exp1); } - return await q.FirstAsync(); + var configs = await _configRepository.QueryAsync(exp); + + return configs.FirstOrDefault(); } public async Task> GetByAppIdAsync(string appId, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - return await dbcontext.Configs.Where(c => + return await _configRepository.QueryAsync(c => c.AppId == appId && c.Status == ConfigStatus.Enabled && c.Env == env - ).ToListAsync(); + ); } public async Task> Search(string appId, string group, string key, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var q = dbcontext.Configs.Where(c => c.Status == ConfigStatus.Enabled && c.Env == env); + Expression> exp = c => c.Status == ConfigStatus.Enabled && c.Env == env; if (!string.IsNullOrEmpty(appId)) { - q = q.Where(c => c.AppId == appId); + exp = exp.And(c => c.AppId == appId); } if (!string.IsNullOrEmpty(group)) { - q = q.Where(c => c.Group.Contains(group)); + exp = exp.And(c => c.Group.Contains(group)); } if (!string.IsNullOrEmpty(key)) { - q = q.Where(c => c.Key.Contains(key)); + exp = exp.And(c => c.Key.Contains(key)); } - return await q.ToListAsync(); + return await _configRepository.QueryAsync(exp); } public async Task CountEnabledConfigsAsync() @@ -263,11 +235,10 @@ public async Task CountEnabledConfigsAsync() public async Task CountEnabledConfigsAsync(string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); //这里计算所有的配置 - var q = await dbcontext.Configs.Where(c => c.Status == ConfigStatus.Enabled && c.Env == env).CountAsync(); + var q = await _configRepository.QueryAsync(c => c.Status == ConfigStatus.Enabled && c.Env == env); - return (int)q; + return q.Count; } public string GenerateKey(Config config) @@ -297,12 +268,10 @@ public string GenerateKey(ConfigPublished config) /// public async Task AppPublishedConfigsMd5(string appId, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var configs = await dbcontext.ConfigPublished.Where(c => + var configs = await _configPublishedRepository.QueryAsync(c => c.AppId == appId && c.Status == ConfigStatus.Enabled && c.Env == env - ).ToListAsync(); + ); var keyStr = string.Join('&', configs.Select(c => GenerateKey(c)).ToArray().OrderBy(k => k, StringComparer.Ordinal)); var valStr = string.Join('&', configs.Select(c => c.Value).ToArray().OrderBy(v => v, StringComparer.Ordinal)); @@ -357,26 +326,20 @@ private void ClearAppPublishedConfigsMd5CacheWithInheritanced(string appId, stri public async Task AddRangeAsync(List configs, string env) { - configs.ForEach(x => { + configs.ForEach(x => + { if (x.Value == null) { x.Value = ""; } }); - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - await dbcontext.Configs.AddRangeAsync(configs); - int x = await dbcontext.SaveChangesAsync(); + await _configRepository.InsertAsync(configs); - var result = x > 0; - if (result) - { - ClearAppPublishedConfigsMd5Cache(configs.First().AppId, env); - ClearAppPublishedConfigsMd5CacheWithInheritanced(configs.First().AppId, env); - } + ClearAppPublishedConfigsMd5Cache(configs.First().AppId, env); + ClearAppPublishedConfigsMd5CacheWithInheritanced(configs.First().AppId, env); - return result; + return true; } /// @@ -476,7 +439,7 @@ public void Dispose() _userService?.Dispose(); } - private static readonly object Lockobj = new object(); + private static readonly SemaphoreSlim _lock = new SemaphoreSlim(1, 1); /// /// 发布当前待发布的配置项 @@ -486,24 +449,24 @@ public void Dispose() /// 发布日志 /// 操作员 /// - public (bool result, string publishTimelineId) Publish(string appId, string[] ids, string log, string operatorr, string env) + public async Task<(bool result, string publishTimelineId)> Publish(string appId, string[] ids, string log, string operatorr, string env) { - lock (Lockobj) + await _lock.WaitAsync(); + try { - using var dbcontext = FreeSqlDbContextFactory.Create(env); + var waitPublishConfigs = await _configRepository.QueryAsync(x => + x.AppId == appId && + x.Env == env && + x.Status == ConfigStatus.Enabled && + x.EditStatus != EditStatus.Commit); - var waitPublishConfigs = dbcontext.Configs.Where(x => - x.AppId == appId && - x.Env == env && - x.Status == ConfigStatus.Enabled && - x.EditStatus != EditStatus.Commit).ToList(); if (ids != null && ids.Any()) { //如果ids传值了,过滤一下 waitPublishConfigs = waitPublishConfigs.Where(x => ids.Contains(x.Id)).ToList(); } //这里默认admin console 实例只部署一个,如果部署多个同步操作,高并发的时候这个version会有问题 - var versionMax = dbcontext.PublishTimeline.Select.Where(x => x.AppId == appId).Max(x => x.Version); + var versionMax = (await _publishTimelineRepository.QueryAsync(x => x.AppId == appId)).Max(x => x.Version); var user = _userService.GetUser(operatorr); @@ -551,8 +514,8 @@ public void Dispose() }); //当前发布的配置 - var publishedConfigs = dbcontext.ConfigPublished - .Where(x => x.Status == ConfigStatus.Enabled && x.AppId == appId && x.Env == env).ToList(); + var publishedConfigs = await _configPublishedRepository + .QueryAsync(x => x.Status == ConfigStatus.Enabled && x.AppId == appId && x.Env == env); //复制一份新版本,最后插入发布表 var publishedConfigsCopy = new List(); publishedConfigs.ForEach(x => @@ -627,114 +590,102 @@ public void Dispose() } }); - dbcontext.Configs.UpdateRange(waitPublishConfigs); - dbcontext.PublishTimeline.Add(publishTimelineNode); - dbcontext.PublishDetail.AddRange(publishDetails); - dbcontext.ConfigPublished.UpdateRange(publishedConfigs); - dbcontext.ConfigPublished.AddRange(publishedConfigsCopy); - - var result = dbcontext.SaveChanges(); + await _configRepository.UpdateAsync(waitPublishConfigs); + await _publishTimelineRepository.InsertAsync(publishTimelineNode); + await _publishDetailRepository.InsertAsync(publishDetails); + await _configPublishedRepository.UpdateAsync(publishedConfigs); + await _configPublishedRepository.InsertAsync(publishedConfigsCopy); ClearAppPublishedConfigsMd5Cache(appId, env); ClearAppPublishedConfigsMd5CacheWithInheritanced(appId, env); - return (result > 0, publishTimelineNode.Id); + return (true, publishTimelineNode.Id); + } + catch (Exception exc) + { + throw; + } + finally + { + _lock.Release(); } } public async Task IsPublishedAsync(string configId, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var any = await dbcontext.ConfigPublished.Select.AnyAsync( + var any = await _configPublishedRepository.QueryAsync( x => x.ConfigId == configId && x.Env == env && x.Status == ConfigStatus.Enabled); - return any; + return any.Count > 0; } public async Task> GetPublishDetailByPublishTimelineIdAsync(string publishTimelineId, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var list = await dbcontext.PublishDetail - .Where(x => x.PublishTimelineId == publishTimelineId && x.Env == env).ToListAsync(); + var list = await _publishDetailRepository + .QueryAsync(x => x.PublishTimelineId == publishTimelineId && x.Env == env); return list; } public async Task GetPublishTimeLineNodeAsync(string publishTimelineId, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var one = await dbcontext.PublishTimeline.Where(x => x.Id == publishTimelineId && x.Env == env) - .FirstAsync(); + var one = (await _publishTimelineRepository.QueryAsync(x => x.Id == publishTimelineId && x.Env == env)) + .FirstOrDefault(); return one; } public async Task> GetPublishTimelineHistoryAsync(string appId, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var list = await dbcontext.PublishTimeline.Where(x => x.AppId == appId && x.Env == env).ToListAsync(); + var list = await _publishTimelineRepository.QueryAsync(x => x.AppId == appId && x.Env == env); return list; } public async Task> GetPublishDetailListAsync(string appId, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var list = await dbcontext.PublishDetail.Where(x => x.AppId == appId && x.Env == env).ToListAsync(); + var list = await _publishDetailRepository.QueryAsync(x => x.AppId == appId && x.Env == env); return list; } public async Task> GetConfigPublishedHistory(string configId, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var list = await dbcontext.PublishDetail.Where(x => x.ConfigId == configId && x.Env == env).ToListAsync(); + var list = await _publishDetailRepository.QueryAsync(x => x.ConfigId == configId && x.Env == env); return list; } public async Task> GetPublishedConfigsAsync(string appId, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var list = await dbcontext.ConfigPublished - .Where(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env).ToListAsync(); + var list = await _configPublishedRepository + .QueryAsync(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env); return list; } public async Task GetPublishedConfigAsync(string configId, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var one = await dbcontext.ConfigPublished.Where(x => x.ConfigId == configId + var one = (await _configPublishedRepository.QueryAsync(x => x.ConfigId == configId && x.Status == ConfigStatus.Enabled && x.Env == env - ).ToOneAsync(); + )).FirstOrDefault(); return one; } public async Task RollbackAsync(string publishTimelineId, string env) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); + var publishNode = (await _publishTimelineRepository.QueryAsync(x => x.Id == publishTimelineId && x.Env == env)).FirstOrDefault(); - var publishNode = await dbcontext.PublishTimeline.Where(x => x.Id == publishTimelineId && x.Env == env) - .ToOneAsync(); var version = publishNode.Version; var appId = publishNode.AppId; - var latest = await dbcontext.PublishTimeline.Where(x => x.AppId == appId && x.Env == env) - .OrderByDescending(x => x.Version).ToOneAsync(); + var latest = (await _publishTimelineRepository.QueryAsync(x => x.AppId == appId && x.Env == env)) + .OrderByDescending(x => x.Version).FirstOrDefault(); if (latest.Id == publishTimelineId) { @@ -742,10 +693,10 @@ public async Task RollbackAsync(string publishTimelineId, string env) return true; } - var publishedConfigs = await dbcontext.ConfigPublished - .Where(x => x.AppId == appId && x.Version == version && x.Env == env).ToListAsync(); - var currentConfigs = await dbcontext.Configs - .Where(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env).ToListAsync(); + var publishedConfigs = await _configPublishedRepository + .QueryAsync(x => x.AppId == appId && x.Version == version && x.Env == env); + var currentConfigs = await _configRepository + .QueryAsync(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env); //把当前的全部软删除 foreach (var item in currentConfigs) @@ -753,38 +704,41 @@ public async Task RollbackAsync(string publishTimelineId, string env) item.Status = ConfigStatus.Deleted; } - await dbcontext.Configs.UpdateRangeAsync(currentConfigs); + await _configRepository.UpdateAsync(currentConfigs); //根据id把所有发布项目设置为启用 var now = DateTime.Now; foreach (var item in publishedConfigs) { - var config = await dbcontext.Configs.Where(x => x.AppId == appId && x.Id == item.ConfigId).ToOneAsync(); + var config = (await _configRepository.QueryAsync(x => x.AppId == appId && x.Id == item.ConfigId)).FirstOrDefault(); config.Status = ConfigStatus.Enabled; config.Value = item.Value; config.UpdateTime = now; config.EditStatus = EditStatus.Commit; config.OnlineStatus = OnlineStatus.Online; - await dbcontext.Configs.UpdateAsync(config); + await _configRepository.UpdateAsync(config); } //删除version之后的版本 - await dbcontext.ConfigPublished.RemoveAsync(x => x.AppId == appId && x.Env == env && x.Version > version); + var configPublishedConfigs = await _configPublishedRepository.QueryAsync(x => x.AppId == appId && x.Env == env && x.Version > version); + await _configPublishedRepository.DeleteAsync(configPublishedConfigs); //设置为发布状态 foreach (var item in publishedConfigs) { item.Status = ConfigStatus.Enabled; - await dbcontext.ConfigPublished.UpdateAsync(item); + await _configPublishedRepository.UpdateAsync(item); } //删除发布时间轴version之后的版本 - await dbcontext.PublishTimeline.RemoveAsync(x => x.AppId == appId && x.Env == env && x.Version > version); - await dbcontext.PublishDetail.RemoveAsync(x => x.AppId == appId && x.Env == env && x.Version > version); + var deletePublishTimeLineItems = await _publishTimelineRepository.QueryAsync(x => x.AppId == appId && x.Env == env && x.Version > version); + await _publishTimelineRepository.DeleteAsync(deletePublishTimeLineItems); + var deletePublishDetailItems = await _publishDetailRepository.QueryAsync(x => x.PublishTimelineId == publishTimelineId && x.Env == env); + await _publishDetailRepository.DeleteAsync(deletePublishDetailItems); ClearAppPublishedConfigsMd5Cache(appId, env); ClearAppPublishedConfigsMd5CacheWithInheritanced(appId, env); - return await dbcontext.SaveChangesAsync() > 0; + return true; } public async Task EnvSync(string appId, string currentEnv, List toEnvs) @@ -864,10 +818,8 @@ public async Task>> GetKvListAsync(string appI private async Task SaveFromDictAsync(IDictionary dict, string appId, string env, bool isPatch) { - using var dbcontext = FreeSqlDbContextFactory.Create(env); - - var currentConfigs = await dbcontext.Configs - .Where(x => x.AppId == appId && x.Env == env && x.Status == ConfigStatus.Enabled).ToListAsync(); + var currentConfigs = await _configRepository + .QueryAsync(x => x.AppId == appId && x.Env == env && x.Status == ConfigStatus.Enabled); var addConfigs = new List(); var updateConfigs = new List(); var deleteConfigs = new List(); @@ -945,21 +897,19 @@ private async Task SaveFromDictAsync(IDictionary dict, str if (addConfigs.Any()) { - await dbcontext.Configs.AddRangeAsync(addConfigs); + await _configRepository.InsertAsync(addConfigs); } if (updateConfigs.Any()) { - await dbcontext.Configs.UpdateRangeAsync(updateConfigs); + await _configRepository.UpdateAsync(updateConfigs); } if (deleteConfigs.Any()) { - await dbcontext.Configs.UpdateRangeAsync(deleteConfigs); + await _configRepository.UpdateAsync(deleteConfigs); } - await dbcontext.SaveChangesAsync(); - return true; } diff --git a/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs index ab21a7d0..a6ed8288 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs @@ -34,8 +34,12 @@ private IAppService NewAppService() private IConfigService NewConfigService() { - return new ConfigService(NewAppService(), new SettingService(new FreeSqlContext(FreeSQL.Instance)), - new UserService(new FreeSqlContext(FreeSQL.Instance))); + // todo + + throw new NotImplementedException(); + + //return new ConfigService(null, NewAppService(), new SettingService(new FreeSqlContext(FreeSQL.Instance)), + // new UserService(new FreeSqlContext(FreeSQL.Instance))); } public void Register() From 01ab14a755cb1e421a3caa693dce6e7f021ee891 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 24 Dec 2023 02:28:55 +0800 Subject: [PATCH 13/45] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20EnvAccessor=20?= =?UTF-8?q?=E8=AF=BB=E5=8F=96=20env=20=E7=9A=84=20bug=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/AgileConfig.Server.Common/EnvAccessor.cs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/AgileConfig.Server.Common/EnvAccessor.cs b/src/AgileConfig.Server.Common/EnvAccessor.cs index e2451885..99d4bfb6 100644 --- a/src/AgileConfig.Server.Common/EnvAccessor.cs +++ b/src/AgileConfig.Server.Common/EnvAccessor.cs @@ -11,16 +11,23 @@ public interface IEnvAccessor public class EnvAccessor : IEnvAccessor { + private IHttpContextAccessor _httpContextAccessor; public EnvAccessor(IHttpContextAccessor httpContextAccessor) { - var env = httpContextAccessor.HttpContext.Request.Query["env"].FirstOrDefault(); - if (string.IsNullOrEmpty(env)) + _httpContextAccessor = httpContextAccessor; + } + public string Env + { + get { - env = "DEV"; + var env = _httpContextAccessor.HttpContext.Request.Query["env"].FirstOrDefault(); + if (string.IsNullOrEmpty(env)) + { + env = "DEV"; + } + return env; } - Env = env; } - public string Env { get; } } public static class EnvAccessorServiceCollectionExtension From c6f6982a79a4e24d79e25aa807b5f6b443960108 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Mon, 25 Dec 2023 14:42:03 +0800 Subject: [PATCH 14/45] =?UTF-8?q?=E7=A7=BB=E9=99=A4=20Mongodb=20Service?= =?UTF-8?q?=EF=BC=8C=E4=BD=BF=E7=94=A8=20Mongodb=20Repository?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AgileConfig.sln | 14 - .../AgileConfig.Server.Apisite.csproj | 2 +- src/AgileConfig.Server.Apisite/Startup.cs | 9 +- .../AdmBasicAuthService.cs | 29 - .../AgileConfig.Server.Mongodb.Service.csproj | 20 - .../AppBasicAuthService.cs | 97 -- .../AppService.cs | 173 --- .../ConfigService.cs | 1000 ----------------- .../ConfigStatusUpdateRegister.cs | 128 --- .../EventRegisterService/EventRegister.cs | 19 - .../ServiceInfoStatusUpdateRegister.cs | 139 --- .../EventRegisterService/SysLogRegister.cs | 475 -------- .../JwtService.cs | 67 -- .../MongodbServiceExtensions.cs | 49 - .../PermissionService.cs | 230 ---- .../RegisterCenterService.cs | 153 --- .../RemoteServerNodeProxy.cs | 272 ----- .../ServerNodeService.cs | 117 -- .../ServiceHealthCheckService.cs | 204 ---- .../ServiceInfoService.cs | 145 --- .../SettingService.cs | 181 --- .../SysLogService.cs | 116 -- .../UserService.cs | 104 -- ...leConfig.Server.Mongodb.ServiceTest.csproj | 27 - .../AppServiceTests.cs | 337 ------ .../ConfigServiceTests.cs | 835 -------------- .../DatabaseFixture.cs | 28 - .../GlobalUsings.cs | 6 - .../ServerNodeServiceTests.cs | 163 --- .../SettingServiceTests.cs | 182 --- .../SysLogServiceTests.cs | 147 --- 31 files changed, 3 insertions(+), 5465 deletions(-) delete mode 100644 src/AgileConfig.Server.Mongodb.Service/AdmBasicAuthService.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj delete mode 100644 src/AgileConfig.Server.Mongodb.Service/AppBasicAuthService.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/AppService.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/ConfigService.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ConfigStatusUpdateRegister.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/EventRegisterService/EventRegister.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/EventRegisterService/SysLogRegister.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/JwtService.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/PermissionService.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/RegisterCenterService.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/RemoteServerNodeProxy.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/ServerNodeService.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/ServiceHealthCheckService.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/ServiceInfoService.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/SettingService.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/SysLogService.cs delete mode 100644 src/AgileConfig.Server.Mongodb.Service/UserService.cs delete mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/AgileConfig.Server.Mongodb.ServiceTest.csproj delete mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/AppServiceTests.cs delete mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/ConfigServiceTests.cs delete mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs delete mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/GlobalUsings.cs delete mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/ServerNodeServiceTests.cs delete mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/SettingServiceTests.cs delete mode 100644 test/AgileConfig.Server.Mongodb.ServiceTest/SysLogServiceTests.cs diff --git a/AgileConfig.sln b/AgileConfig.sln index 4176ab09..9c9334c3 100644 --- a/AgileConfig.sln +++ b/AgileConfig.sln @@ -40,10 +40,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.OIDC", " EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Mongodb", "src\AgileConfig.Server.Data.Mongodb\AgileConfig.Server.Data.Mongodb.csproj", "{4803646E-8327-4F69-8BA5-2244CB58BBA2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Mongodb.Service", "src\AgileConfig.Server.Mongodb.Service\AgileConfig.Server.Mongodb.Service.csproj", "{375B1F54-11CA-415D-ADCC-3B14684AE1DB}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Mongodb.ServiceTest", "test\AgileConfig.Server.Mongodb.ServiceTest\AgileConfig.Server.Mongodb.ServiceTest.csproj", "{E35504A4-E032-4EEA-A53A-12C99B56680B}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Abstraction", "src\AgileConfig.Server.Data.Abstraction\AgileConfig.Server.Data.Abstraction.csproj", "{E8101403-72C9-40FB-BCEE-16ED5C23A495}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Repository.Freesql", "src\AgileConfig.Server.Data.Repository.Freesql\AgileConfig.Server.Data.Repository.Freesql.csproj", "{955F64CC-9EAC-4563-804D-6E2CF9547357}" @@ -104,14 +100,6 @@ Global {4803646E-8327-4F69-8BA5-2244CB58BBA2}.Debug|Any CPU.Build.0 = Debug|Any CPU {4803646E-8327-4F69-8BA5-2244CB58BBA2}.Release|Any CPU.ActiveCfg = Release|Any CPU {4803646E-8327-4F69-8BA5-2244CB58BBA2}.Release|Any CPU.Build.0 = Release|Any CPU - {375B1F54-11CA-415D-ADCC-3B14684AE1DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {375B1F54-11CA-415D-ADCC-3B14684AE1DB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {375B1F54-11CA-415D-ADCC-3B14684AE1DB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {375B1F54-11CA-415D-ADCC-3B14684AE1DB}.Release|Any CPU.Build.0 = Release|Any CPU - {E35504A4-E032-4EEA-A53A-12C99B56680B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E35504A4-E032-4EEA-A53A-12C99B56680B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E35504A4-E032-4EEA-A53A-12C99B56680B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E35504A4-E032-4EEA-A53A-12C99B56680B}.Release|Any CPU.Build.0 = Release|Any CPU {E8101403-72C9-40FB-BCEE-16ED5C23A495}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E8101403-72C9-40FB-BCEE-16ED5C23A495}.Debug|Any CPU.Build.0 = Debug|Any CPU {E8101403-72C9-40FB-BCEE-16ED5C23A495}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -141,8 +129,6 @@ Global {70724B0E-7D81-412C-BDA7-747F4845E990} = {F277EC27-8C0E-4490-9645-F5F3244F9246} {E49A2006-6D07-4434-AEC1-27E356A767AE} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {4803646E-8327-4F69-8BA5-2244CB58BBA2} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} - {375B1F54-11CA-415D-ADCC-3B14684AE1DB} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} - {E35504A4-E032-4EEA-A53A-12C99B56680B} = {F277EC27-8C0E-4490-9645-F5F3244F9246} {E8101403-72C9-40FB-BCEE-16ED5C23A495} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {955F64CC-9EAC-4563-804D-6E2CF9547357} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {C6B7A5A6-7287-4A20-9336-EBE82A5256F1} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} diff --git a/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj b/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj index f01b98d8..27aebb1f 100644 --- a/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj +++ b/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj @@ -40,7 +40,7 @@ - + diff --git a/src/AgileConfig.Server.Apisite/Startup.cs b/src/AgileConfig.Server.Apisite/Startup.cs index 35b31442..fa20b7c5 100644 --- a/src/AgileConfig.Server.Apisite/Startup.cs +++ b/src/AgileConfig.Server.Apisite/Startup.cs @@ -1,14 +1,11 @@ using System; using System.IO; using System.Net; -using System.Net.Http; -using System.Text; using AgileConfig.Server.Apisite.UIExtension; using AgileConfig.Server.Apisite.Websocket; using AgileConfig.Server.Common; using AgileConfig.Server.Common.RestClient; using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Mongodb.Service; using AgileConfig.Server.OIDC; using AgileConfig.Server.Service; using Microsoft.AspNetCore.Authentication.JwtBearer; @@ -18,9 +15,9 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.Data.Repository.Mongodb; namespace AgileConfig.Server.Apisite { @@ -161,9 +158,7 @@ private void AddDataRepositories(IServiceCollection services) { if (string.Equals(Configuration["db:provider"], "mongodb", StringComparison.OrdinalIgnoreCase)) { - // todo - - // services.AddMongoRepository(); + services.AddMongodbRepository(); } else { diff --git a/src/AgileConfig.Server.Mongodb.Service/AdmBasicAuthService.cs b/src/AgileConfig.Server.Mongodb.Service/AdmBasicAuthService.cs deleted file mode 100644 index e408a064..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/AdmBasicAuthService.cs +++ /dev/null @@ -1,29 +0,0 @@ -using AgileConfig.Server.Common; -using AgileConfig.Server.IService; -using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Logging; - -namespace AgileConfig.Server.Mongodb.Service; - -public class AdmBasicAuthService(IUserService userService, ILoggerFactory lf) : IAdmBasicAuthService -{ - private readonly ILogger _logger = lf.CreateLogger(); - - public async Task ValidAsync(HttpRequest httpRequest) - { - var userPassword = httpRequest.GetUserNamePasswordFromBasicAuthorization(); - if (string.IsNullOrEmpty(userPassword.Item1)||string.IsNullOrEmpty(userPassword.Item2)) - { - _logger.LogWarning("Basic auth header have no username or password"); - return false; - } - - var result = await userService.ValidateUserPassword(userPassword.Item1, userPassword.Item2); - return result; - } - - public (string, string) GetUserNamePassword(HttpRequest httpRequest) - { - return httpRequest.GetUserNamePasswordFromBasicAuthorization(); - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj b/src/AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj deleted file mode 100644 index cf79b219..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/AgileConfig.Server.Mongodb.Service.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - net8.0 - enable - enable - - - - - - - - - - - - - - diff --git a/src/AgileConfig.Server.Mongodb.Service/AppBasicAuthService.cs b/src/AgileConfig.Server.Mongodb.Service/AppBasicAuthService.cs deleted file mode 100644 index cd0c6ba8..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/AppBasicAuthService.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System.Text; -using AgileConfig.Server.IService; -using Microsoft.AspNetCore.Http; - -namespace AgileConfig.Server.Mongodb.Service; - -public class AppBasicAuthService(IAppService appService) : IAppBasicAuthService -{ - /// - /// 从request中解析出appid、secret - /// - /// - /// - public (string, string) GetAppIdSecret(HttpRequest httpRequest) - { - var authorization = httpRequest.Headers["Authorization"]; - if (string.IsNullOrEmpty(authorization)) - { - return ("", ""); - } - - var authStr = authorization.First(); - //去掉basic_ - if (!authStr.StartsWith("Basic ")) - { - return ("", ""); - ; - } - - authStr = authStr.Substring(6, authStr.Length - 6); - byte[] base64Decode = null; - try - { - base64Decode = Convert.FromBase64String(authStr); - } - catch - { - return ("", ""); - } - - var base64Str = Encoding.UTF8.GetString(base64Decode); - - if (string.IsNullOrEmpty(base64Str)) - { - return ("", ""); - } - - var appId = ""; - var sec = ""; - - - var baseAuthArr = base64Str.Split(':'); - - if (baseAuthArr.Length > 0) - { - appId = baseAuthArr[0]; - } - - if (baseAuthArr.Length > 1) - { - sec = baseAuthArr[1]; - } - - return (appId, sec); - } - - public (string, string) GetUserNamePassword(HttpRequest httpRequest) - { - throw new NotImplementedException(); - } - - public async Task ValidAsync(HttpRequest httpRequest) - { - var appIdSecret = GetAppIdSecret(httpRequest); - var appId = appIdSecret.Item1; - var sec = appIdSecret.Item2; - if (string.IsNullOrEmpty(appIdSecret.Item1)) - { - return false; - } - - var app = await appService.GetAsync(appId); - if (app == null) - { - return false; - } - - if (!app.Enabled) - { - return false; - } - - var txt = $"{app.Id}:{app.Secret}"; - - return txt == $"{appId}:{sec}"; - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/AppService.cs b/src/AgileConfig.Server.Mongodb.Service/AppService.cs deleted file mode 100644 index 63dbda21..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/AppService.cs +++ /dev/null @@ -1,173 +0,0 @@ -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Mongodb; -using AgileConfig.Server.IService; -using MongoDB.Driver; -using MongoDB.Driver.Linq; - -namespace AgileConfig.Server.Mongodb.Service; - -public class AppService( - IRepository repository, - IRepository appInheritancedRepository, - IRepository configRepository, - IRepository configPublishedRepository, - IRepository userAppAuthRepository, - IRepository userRepository):IAppService -{ - public void Dispose() - { - GC.SuppressFinalize(this); - } - - public Task GetAsync(string id) - { - return repository.FindAsync(id); - } - - public async Task AddAsync(App app) - { - await repository.InsertAsync(app); - return true; - } - - public async Task AddAsync(App app, List? appInheritanceds) - { - await repository.InsertAsync(app); - if (appInheritanceds != null) - { - await appInheritancedRepository.InsertAsync(appInheritanceds); - } - - return true; - } - - public async Task DeleteAsync(App app) - { - var app2 = await repository.FindAsync(app.Id); - if (app2 != null) - { - await repository.DeleteAsync(app2.Id); - //怕有的同学误删app导致要恢复,所以保留配置项吧。 - var update = Builders.Update.Set(x => x.Status, ConfigStatus.Deleted); - await configRepository.UpdateAsync(x => x.AppId == app2.Id, update); - //删除发布的配置项 - var publishedConfigUpdate = Builders.Update.Set(x => x.Status, ConfigStatus.Deleted); - await configPublishedRepository.UpdateAsync(x => x.AppId == app2.Id && x.Status == ConfigStatus.Enabled, - publishedConfigUpdate); - } - - return true; - } - - public async Task DeleteAsync(string appId) - { - var result = await repository.DeleteAsync(appId); - return result.DeletedCount > 0; - } - - public async Task UpdateAsync(App app, List? appInheritanceds) - { - await repository.UpdateAsync(app); - await appInheritancedRepository.DeleteAsync(x => x.AppId == app.Id); - if (appInheritanceds != null) - { - await appInheritancedRepository.InsertAsync(appInheritanceds); - } - - return true; - } - - public async Task UpdateAsync(App app) - { - var result = await repository.UpdateAsync(app); - return result.ModifiedCount > 0; - } - - public Task> GetAllAppsAsync() - { - return repository.SearchFor(x => true).ToListAsync(); - } - - public Task> GetAllInheritancedAppsAsync() - { - return repository.SearchFor(x => x.Type == AppType.Inheritance).ToListAsync(); - } - - public Task CountEnabledAppsAsync() - { - return repository.SearchFor(x => x.Enabled == true).CountAsync(); - } - - public async Task> GetInheritancedAppsAsync(string appId) - { - var appInheritanceds =await appInheritancedRepository.SearchFor(x => x.AppId == appId) - .OrderBy(x => x.Sort) - .ToListAsync(); - - var apps = new List(); - - foreach (var item in appInheritanceds) - { - var app = await GetAsync(item.InheritancedAppId); - if (app is { Enabled: true }) - { - apps.Add(app); - } - } - - return apps; - } - - public async Task> GetInheritancedFromAppsAsync(string appId) - { - var appInheritanceds = await appInheritancedRepository.SearchFor(a => a.InheritancedAppId == appId).ToListAsync(); - appInheritanceds = appInheritanceds.OrderBy(a => a.Sort).ToList(); - - var apps = new List(); - - foreach (var item in appInheritanceds) - { - var app = await GetAsync(item.AppId); - if (app is { Enabled: true }) - { - apps.Add(app); - } - } - - return apps; - } - - public async Task SaveUserAppAuth(string appId, List? userIds, string permission) - { - var userAppAuthList = new List(); - userIds ??= new List(); - foreach (var userId in userIds) - { - userAppAuthList.Add(new UserAppAuth - { - Id = Guid.NewGuid().ToString("N"), - AppId = appId, - UserId = userId, - Permission = permission - }); - } - await userAppAuthRepository.DeleteAsync(x => x.AppId == appId && x.Permission == permission); - await userAppAuthRepository.InsertAsync(userAppAuthList); - - return true; - } - - public async Task> GetUserAppAuth(string appId, string permission) - { - var auths = await userAppAuthRepository.SearchFor(x => x.AppId == appId && x.Permission == permission).ToListAsync(); - - var userIds = auths.Select(x => x.UserId).Distinct().ToList(); - return await userRepository.SearchFor(x => userIds.Contains(x.Id)).ToListAsync(); - } - - public async Task> GetAppGroups() - { - var groups = repository.SearchFor(x => true).GroupBy(x => x.Group).Select(x => x.Key); - return await groups.Where(x => !string.IsNullOrEmpty(x)).ToListAsync(); - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/ConfigService.cs b/src/AgileConfig.Server.Mongodb.Service/ConfigService.cs deleted file mode 100644 index d2d96c2a..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/ConfigService.cs +++ /dev/null @@ -1,1000 +0,0 @@ -using System.Text; -using AgileConfig.Server.Common; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Mongodb; -using AgileConfig.Server.IService; -using Microsoft.Extensions.Caching.Memory; -using Microsoft.Extensions.Configuration; -using MongoDB.Driver; -using MongoDB.Driver.Linq; - -namespace AgileConfig.Server.Mongodb.Service; - -public class ConfigService( - IConfiguration configuration, - IMemoryCache memoryCache, - IAppService appService, - ISettingService settingService, - IUserService userService) - : IConfigService -{ - public async Task IfEnvEmptySetDefaultAsync(string env) - { - if (!string.IsNullOrEmpty(env)) - { - return env; - } - - var envList = await settingService.GetEnvironmentList(); - if (envList == null || envList.Length == 0) - { - return ""; - } - - return envList[0]; - } - - - private IRepository GetRepository(string env) where T : new() - { - if (string.IsNullOrEmpty(env)) - { - //如果没有环境,使用默认连接 - return new Repository(configuration["db:conn"]); - } - - //是否配置的环境的连接 - var envDbProvider = configuration[$"db:env:{env}:provider"]; - if (string.IsNullOrEmpty(envDbProvider) || - string.Equals(envDbProvider, "mongodb", StringComparison.OrdinalIgnoreCase)) - { - //如果没有配置对应环境的连接,使用默认连接 - return new Repository(configuration["db:conn"]); - } - - Console.WriteLine("create env:{env} mongodb repository"); - return new Repository(configuration[$"db:env:{env}:conn"]); - } - - public async Task AddAsync(Config config, string env) - { - config.Value ??= ""; - await GetRepository(env).InsertAsync(config); - return true; - } - - public async Task UpdateAsync(Config config, string env) - { - var result = await GetRepository(env).UpdateAsync(config); - return result.ModifiedCount > 0; - } - - public async Task UpdateAsync(List configs, string env) - { - foreach (var item in configs) - { - await GetRepository(env).UpdateAsync(item); - } - - return true; - } - - public async Task CancelEdit(List ids, string env) - { - foreach (var configId in ids) - { - var config = await GetRepository(env).SearchFor(c => c.Id == configId).FirstOrDefaultAsync(); - if (config == null) - { - throw new Exception("Can not find config by id " + configId); - } - - if (config.EditStatus == EditStatus.Commit) - { - continue; - } - - if (config.EditStatus == EditStatus.Add) - { - await GetRepository(env).DeleteAsync(x => x.Id == configId); - } - - if (config.EditStatus is EditStatus.Deleted or EditStatus.Edit) - { - config.OnlineStatus = OnlineStatus.Online; - config.EditStatus = EditStatus.Commit; - config.UpdateTime = DateTime.Now; - - var publishedConfig = await GetPublishedConfigAsync(configId, env); - if (publishedConfig == null) - { - // - throw new Exception("Can not find published config by id " + configId); - } - - //reset value - config.Value = publishedConfig.Value; - config.OnlineStatus = OnlineStatus.Online; - - await GetRepository(env).UpdateAsync(config); - } - } - - return true; - } - - public async Task DeleteAsync(Config config, string env) - { - var result = await GetRepository(env).DeleteAsync(x => x.Id == config.Id); - - return result.DeletedCount > 0; - } - - public async Task DeleteAsync(string configId, string env) - { - var result = await GetRepository(env).DeleteAsync(configId); - - return result.DeletedCount > 0; - } - - public async Task GetAsync(string id, string env) - { - var config = await GetRepository(env).FindAsync(id); - return config; - } - - public Task> GetAllConfigsAsync(string env) - { - return GetRepository(env).SearchFor(c => c.Status == ConfigStatus.Enabled && c.Env == env) - .ToListAsync(); - } - - public async Task GetByAppIdKeyEnv(string appId, string group, string key, string env) - { - var q = GetRepository(env).SearchFor(c => - c.AppId == appId && - c.Key == key && - c.Env == env && - c.Status == ConfigStatus.Enabled - ); - if (string.IsNullOrEmpty(group)) - { - q = q.Where(c => c.Group == "" || c.Group == null); - } - else - { - q = q.Where(c => c.Group == group); - } - - return await q.FirstOrDefaultAsync(); - } - - public Task> GetByAppIdAsync(string appId, string env) - { - return GetRepository(env).SearchFor(c => - c.AppId == appId && c.Status == ConfigStatus.Enabled && c.Env == env - ).ToListAsync(); - } - - public Task> Search(string appId, string group, string key, string env) - { - var q = GetRepository(env).SearchFor(c => c.Status == ConfigStatus.Enabled && c.Env == env); - if (!string.IsNullOrEmpty(appId)) - { - q = q.Where(c => c.AppId == appId); - } - - if (!string.IsNullOrEmpty(group)) - { - q = q.Where(c => c.Group.Contains(group)); - } - - if (!string.IsNullOrEmpty(key)) - { - q = q.Where(c => c.Key.Contains(key)); - } - - return q.ToListAsync(); - } - - public async Task CountEnabledConfigsAsync() - { - int count = 0; - var envs = await settingService.GetEnvironmentList(); - foreach (var e in envs) - { - count += await CountEnabledConfigsAsync(e); - } - - return count; - } - - public async Task CountEnabledConfigsAsync(string env) - { - //这里计算所有的配置 - var q = await GetRepository(env).SearchFor(c => c.Status == ConfigStatus.Enabled && c.Env == env) - .CountAsync(); - - return (int)q; - } - - public string GenerateKey(Config config) - { - if (string.IsNullOrEmpty(config.Group)) - { - return config.Key; - } - - return $"{config.Group}:{config.Key}"; - } - - public string GenerateKey(ConfigPublished config) - { - if (string.IsNullOrEmpty(config.Group)) - { - return config.Key; - } - - return $"{config.Group}:{config.Key}"; - } - - /// - /// 获取当前app的配置集合的md5版本 - /// - /// - /// - public async Task AppPublishedConfigsMd5(string appId, string env) - { - var configs = await GetRepository(env).SearchFor(c => - c.AppId == appId && c.Status == ConfigStatus.Enabled - && c.Env == env - ).ToListAsync(); - - var keyStr = string.Join('&', - configs.Select(c => GenerateKey(c)).ToArray().OrderBy(k => k, StringComparer.Ordinal)); - var valStr = string.Join('&', configs.Select(c => c.Value).ToArray().OrderBy(v => v, StringComparer.Ordinal)); - var txt = $"{keyStr}&{valStr}"; - - return Encrypt.Md5(txt); - } - - /// - /// 获取当前app的配置集合的md5版本,1分钟缓存 - /// - /// - /// - public async Task AppPublishedConfigsMd5Cache(string appId, string env) - { - var cacheKey = AppPublishedConfigsMd5CacheKey(appId, env); - if (memoryCache != null && memoryCache.TryGetValue(cacheKey, out string md5)) - { - return md5; - } - - md5 = await AppPublishedConfigsMd5(appId, env); - - var cacheOp = new MemoryCacheEntryOptions() - .SetAbsoluteExpiration(TimeSpan.FromSeconds(60)); - memoryCache?.Set(cacheKey, md5, cacheOp); - - return md5; - } - - private string AppPublishedConfigsMd5CacheKey(string appId, string env) - { - return $"ConfigService_AppPublishedConfigsMd5Cache_{appId}_{env}"; - } - - private string AppPublishedConfigsMd5CacheKeyWithInheritanced(string appId, string env) - { - return $"ConfigService_AppPublishedConfigsMd5CacheWithInheritanced_{appId}_{env}"; - } - - private void ClearAppPublishedConfigsMd5Cache(string appId, string env) - { - var cacheKey = AppPublishedConfigsMd5CacheKey(appId, env); - memoryCache?.Remove(cacheKey); - } - - private void ClearAppPublishedConfigsMd5CacheWithInheritanced(string appId, string env) - { - var cacheKey = AppPublishedConfigsMd5CacheKeyWithInheritanced(appId, env); - memoryCache?.Remove(cacheKey); - } - - public async Task AddRangeAsync(List configs, string env) - { - configs.ForEach(x => { x.Value ??= ""; }); - - - await GetRepository(env).InsertAsync(configs); - ClearAppPublishedConfigsMd5Cache(configs.First().AppId, env); - ClearAppPublishedConfigsMd5CacheWithInheritanced(configs.First().AppId, env); - return true; - } - - /// - /// 获取app的配置项继承的app配置合并进来 - /// - /// - /// - public async Task> GetPublishedConfigsByAppIdWithInheritanced(string appId, string env) - { - var configs = await GetPublishedConfigsByAppIdWithInheritanced_Dictionary(appId, env); - - return configs.Values.ToList(); - } - - /// - /// 获取app的配置项继承的app配置合并进来转换为字典 - /// - /// - /// - public async Task> GetPublishedConfigsByAppIdWithInheritanced_Dictionary( - string appId, string env) - { - var apps = new List(); - var inheritanceApps = await appService.GetInheritancedAppsAsync(appId); - for (int i = 0; i < inheritanceApps.Count; i++) - { - if (inheritanceApps[i].Enabled) - { - apps.Add(inheritanceApps[i].Id); //后继承的排在后面 - } - } - - apps.Add(appId); //本应用放在最后 - - var configs = new Dictionary(); - //读取所有继承的配置跟本app的配置 - for (int i = 0; i < apps.Count; i++) - { - var id = apps[i]; - var publishConfigs = await GetPublishedConfigsAsync(id, env); - for (int j = 0; j < publishConfigs.Count; j++) - { - var config = publishConfigs[j].Convert(); - var key = GenerateKey(config); - if (configs.ContainsKey(key)) - { - //后面的覆盖前面的 - configs[key] = config; - } - else - { - configs.Add(key, config); - } - } - } - - return configs; - } - - public async Task AppPublishedConfigsMd5WithInheritanced(string appId, string env) - { - var configs = await GetPublishedConfigsByAppIdWithInheritanced(appId, env); - - var keyStr = string.Join('&', - configs.Select(c => GenerateKey(c)).ToArray().OrderBy(k => k, StringComparer.Ordinal)); - var valStr = string.Join('&', configs.Select(c => c.Value).ToArray().OrderBy(v => v, StringComparer.Ordinal)); - var txt = $"{keyStr}&{valStr}"; - - return Encrypt.Md5(txt); - } - - /// - /// 获取当前app的配置集合的md5版本,1分钟缓存 集合了继承app的配置 - /// - /// - /// - public async Task AppPublishedConfigsMd5CacheWithInheritanced(string appId, string env) - { - var cacheKey = AppPublishedConfigsMd5CacheKeyWithInheritanced(appId, env); - if (memoryCache != null && memoryCache.TryGetValue(cacheKey, out string md5)) - { - return md5; - } - - md5 = await AppPublishedConfigsMd5WithInheritanced(appId, env); - - var cacheOp = new MemoryCacheEntryOptions() - .SetAbsoluteExpiration(TimeSpan.FromSeconds(60)); - memoryCache?.Set(cacheKey, md5, cacheOp); - - return md5; - } - - public void Dispose() - { - GC.SuppressFinalize(this); - } - - private static readonly object Lockobj = new object(); - - /// - /// 发布当前待发布的配置项 - /// - /// 应用id - /// 待发布的id列表 - /// 发布日志 - /// 操作员 - /// - public Task<(bool result, string publishTimelineId)> Publish(string appId, string[] ids, string log, string operatorr, - string env) - { - return null; - - // remove - - //lock (Lockobj) - //{ - // var waitPublishConfigs = GetRepository(env).SearchFor(x => - // x.AppId == appId && - // x.Env == env && - // x.Status == ConfigStatus.Enabled && - // x.EditStatus != EditStatus.Commit).ToList(); - // if (ids != null && ids.Any()) - // { - // //如果ids传值了,过滤一下 - // waitPublishConfigs = waitPublishConfigs.Where(x => ids.Contains(x.Id)).ToList(); - // } - - // //这里默认admin console 实例只部署一个,如果部署多个同步操作,高并发的时候这个version会有问题 - // var versionMax = GetRepository(env).SearchFor(x => x.AppId == appId).Max(x => x.Version); - - // var user = userService.GetUser(operatorr); - - // var publishTimelineNode = new PublishTimeline(); - // publishTimelineNode.AppId = appId; - // publishTimelineNode.Id = Guid.NewGuid().ToString("N"); - // publishTimelineNode.PublishTime = DateTime.Now; - // publishTimelineNode.PublishUserId = user.Id; - // publishTimelineNode.PublishUserName = user.UserName; - // publishTimelineNode.Version = versionMax + 1; - // publishTimelineNode.Log = log; - // publishTimelineNode.Env = env; - - // var publishDetails = new List(); - // waitPublishConfigs.ForEach(x => - // { - // publishDetails.Add(new PublishDetail() - // { - // AppId = appId, - // ConfigId = x.Id, - // Description = x.Description, - // EditStatus = x.EditStatus, - // Group = x.Group, - // Id = Guid.NewGuid().ToString("N"), - // Key = x.Key, - // Value = x.Value, - // PublishTimelineId = publishTimelineNode.Id, - // Version = publishTimelineNode.Version, - // Env = env - // }); - - // if (x.EditStatus == EditStatus.Deleted) - // { - // x.OnlineStatus = OnlineStatus.WaitPublish; - // x.Status = ConfigStatus.Deleted; - // } - // else - // { - // x.OnlineStatus = OnlineStatus.Online; - // x.Status = ConfigStatus.Enabled; - // } - - // x.EditStatus = EditStatus.Commit; - // x.OnlineStatus = OnlineStatus.Online; - // }); - - // //当前发布的配置 - // var publishedConfigs = GetRepository(env) - // .SearchFor(x => x.Status == ConfigStatus.Enabled && x.AppId == appId && x.Env == env).ToList(); - // //复制一份新版本,最后插入发布表 - // var publishedConfigsCopy = new List(); - // publishedConfigs.ForEach(x => - // { - // publishedConfigsCopy.Add(new ConfigPublished() - // { - // AppId = x.AppId, - // ConfigId = x.ConfigId, - // Group = x.Group, - // Id = Guid.NewGuid().ToString("N"), - // Key = x.Key, - // PublishTimelineId = publishTimelineNode.Id, - // PublishTime = publishTimelineNode.PublishTime, - // Status = ConfigStatus.Enabled, - // Version = publishTimelineNode.Version, - // Value = x.Value, - // Env = x.Env - // }); - // x.Status = ConfigStatus.Deleted; - // }); - - // publishDetails.ForEach(x => - // { - // if (x.EditStatus == EditStatus.Add) - // { - // publishedConfigsCopy.Add(new ConfigPublished() - // { - // AppId = x.AppId, - // ConfigId = x.ConfigId, - // Group = x.Group, - // Id = Guid.NewGuid().ToString("N"), - // Key = x.Key, - // PublishTimelineId = publishTimelineNode.Id, - // PublishTime = publishTimelineNode.PublishTime, - // Status = ConfigStatus.Enabled, - // Value = x.Value, - // Version = publishTimelineNode.Version, - // Env = env - // }); - // } - - // if (x.EditStatus == EditStatus.Edit) - // { - // var oldEntity = publishedConfigsCopy.FirstOrDefault(c => c.ConfigId == x.ConfigId); - // if (oldEntity == null) - // { - // //do nothing - // } - // else - // { - // //edit - // oldEntity.Version = publishTimelineNode.Version; - // oldEntity.Group = x.Group; - // oldEntity.Key = x.Key; - // oldEntity.Value = x.Value; - // oldEntity.PublishTime = publishTimelineNode.PublishTime; - // } - // } - - // if (x.EditStatus == EditStatus.Deleted) - // { - // var oldEntity = publishedConfigsCopy.FirstOrDefault(c => c.ConfigId == x.ConfigId); - // if (oldEntity == null) - // { - // //do nothing - // } - // else - // { - // //remove - // publishedConfigsCopy.Remove(oldEntity); - // } - // } - // }); - - // GetRepository(env).Update(waitPublishConfigs); - // GetRepository(env).Insert(publishTimelineNode); - // GetRepository(env).Insert(publishDetails); - // GetRepository(env).Update(publishedConfigs); - // GetRepository(env).Insert(publishedConfigsCopy); - - - // ClearAppPublishedConfigsMd5Cache(appId, env); - // ClearAppPublishedConfigsMd5CacheWithInheritanced(appId, env); - - // return (true, publishTimelineNode.Id); - //} - } - - public async Task IsPublishedAsync(string configId, string env) - { - var any = await GetRepository(env).SearchFor( - x => x.ConfigId == configId - && x.Env == env - && x.Status == ConfigStatus.Enabled).AnyAsync(); - - return any; - } - - public async Task> GetPublishDetailByPublishTimelineIdAsync(string publishTimelineId, - string env) - { - var list = await GetRepository(env) - .SearchFor(x => x.PublishTimelineId == publishTimelineId && x.Env == env).ToListAsync(); - - return list; - } - - public async Task GetPublishTimeLineNodeAsync(string publishTimelineId, string env) - { - var one = await GetRepository(env).SearchFor(x => x.Id == publishTimelineId && x.Env == env) - .FirstAsync(); - - return one; - } - - public async Task> GetPublishTimelineHistoryAsync(string appId, string env) - { - var list = await GetRepository(env).SearchFor(x => x.AppId == appId && x.Env == env) - .ToListAsync(); - - return list; - } - - public async Task> GetPublishDetailListAsync(string appId, string env) - { - var list = await GetRepository(env).SearchFor(x => x.AppId == appId && x.Env == env) - .ToListAsync(); - - return list; - } - - public async Task> GetConfigPublishedHistory(string configId, string env) - { - var list = await GetRepository(env).SearchFor(x => x.ConfigId == configId && x.Env == env) - .ToListAsync(); - - return list; - } - - public async Task> GetPublishedConfigsAsync(string appId, string env) - { - var list = await GetRepository(env) - .SearchFor(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env).ToListAsync(); - - return list; - } - - public async Task GetPublishedConfigAsync(string configId, string env) - { - var one = await GetRepository(env) - .SearchFor(x => x.ConfigId == configId && x.Status == ConfigStatus.Enabled && x.Env == env) - .FirstOrDefaultAsync(); - return one; - } - - public async Task RollbackAsync(string publishTimelineId, string env) - { - var publishNode = await GetRepository(env) - .SearchFor(x => x.Id == publishTimelineId && x.Env == env) - .FirstAsync(); - var version = publishNode.Version; - var appId = publishNode.AppId; - - var latest = await GetRepository(env).SearchFor(x => x.AppId == appId && x.Env == env) - .OrderByDescending(x => x.Version).FirstAsync(); - - if (latest.Id == publishTimelineId) - { - //当前版本直接返回true - return true; - } - - var publishedConfigs = await GetRepository(env) - .SearchFor(x => x.AppId == appId && x.Version == version && x.Env == env).ToListAsync(); - var currentConfigs = await GetRepository(env) - .SearchFor(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env).ToListAsync(); - - //把当前的全部软删除 - foreach (var item in currentConfigs) - { - item.Status = ConfigStatus.Deleted; - } - - await GetRepository(env).UpdateAsync(currentConfigs); - //根据id把所有发布项目设置为启用 - var now = DateTime.Now; - foreach (var item in publishedConfigs) - { - var config = await GetRepository(env).SearchFor(x => x.AppId == appId && x.Id == item.ConfigId) - .FirstAsync(); - config.Status = ConfigStatus.Enabled; - config.Value = item.Value; - config.UpdateTime = now; - config.EditStatus = EditStatus.Commit; - config.OnlineStatus = OnlineStatus.Online; - - await GetRepository(env).UpdateAsync(config); - } - - //删除version之后的版本 - await GetRepository(env) - .DeleteAsync(x => x.AppId == appId && x.Env == env && x.Version > version); - //设置为发布状态 - foreach (var item in publishedConfigs) - { - item.Status = ConfigStatus.Enabled; - await GetRepository(env).UpdateAsync(item); - } - - //删除发布时间轴version之后的版本 - await GetRepository(env) - .DeleteAsync(x => x.AppId == appId && x.Env == env && x.Version > version); - await GetRepository(env) - .DeleteAsync(x => x.AppId == appId && x.Env == env && x.Version > version); - - ClearAppPublishedConfigsMd5Cache(appId, env); - ClearAppPublishedConfigsMd5CacheWithInheritanced(appId, env); - - return true; - } - - public async Task EnvSync(string appId, string currentEnv, List toEnvs) - { - var currentEnvConfigs = await this.GetByAppIdAsync(appId, currentEnv); - - foreach (var env in toEnvs) - { - var envConfigs = await this.GetByAppIdAsync(appId, env); - var addRanges = new List(); - var updateRanges = new List(); - foreach (var currentEnvConfig in currentEnvConfigs) - { - var envConfig = envConfigs.FirstOrDefault(x => GenerateKey(x) == GenerateKey(currentEnvConfig)); - if (envConfig == null) - { - //没有相同的配置,则添加 - currentEnvConfig.Id = Guid.NewGuid().ToString("N"); - currentEnvConfig.Env = env; - currentEnvConfig.CreateTime = DateTime.Now; - currentEnvConfig.UpdateTime = DateTime.Now; - currentEnvConfig.Status = ConfigStatus.Enabled; - currentEnvConfig.EditStatus = EditStatus.Add; - currentEnvConfig.OnlineStatus = OnlineStatus.WaitPublish; //全部设置为待发布状态 - addRanges.Add(currentEnvConfig); - } - else - { - // 如果有了相同的键,如果值不同,则更新 - if (envConfig.Value != currentEnvConfig.Value) - { - envConfig.UpdateTime = DateTime.Now; - envConfig.Value = currentEnvConfig.Value; - if (envConfig.EditStatus == EditStatus.Commit) - { - envConfig.EditStatus = EditStatus.Edit; - } - - envConfig.OnlineStatus = OnlineStatus.WaitPublish; - envConfig.Description = currentEnvConfig.Description; - updateRanges.Add(envConfig); - } - } - } - - if (addRanges.Count > 0) - { - await this.AddRangeAsync(addRanges, env); - } - - if (updateRanges.Count > 0) - { - await this.UpdateAsync(updateRanges, env); - } - } - - return true; - } - - /// - /// 获取配置项转换成键值对列表形式 - /// - /// - /// - /// - public async Task>> GetKvListAsync(string appId, string env) - { - var configs = await GetByAppIdAsync(appId, env); - var kvList = new List>(); - foreach (var config in configs) - { - kvList.Add(new KeyValuePair(GenerateKey(config), config.Value)); - } - - return kvList; - } - - private async Task SaveFromDictAsync(IDictionary dict, string appId, string env, bool isPatch) - { - var currentConfigs = await GetRepository(env) - .SearchFor(x => x.AppId == appId && x.Env == env && x.Status == ConfigStatus.Enabled).ToListAsync(); - var addConfigs = new List(); - var updateConfigs = new List(); - var deleteConfigs = new List(); - - var now = DateTime.Now; - - foreach (var kv in dict) - { - var key = kv.Key; - var value = kv.Value; - var config = currentConfigs.FirstOrDefault(x => GenerateKey(x) == key); - if (config == null) - { - var gk = SplitJsonKey(key); - addConfigs.Add(new Config - { - Id = Guid.NewGuid().ToString("N"), - AppId = appId, - Env = env, - Key = gk.Item2, - Group = gk.Item1, - Value = value, - CreateTime = now, - Status = ConfigStatus.Enabled, - EditStatus = EditStatus.Add, - OnlineStatus = OnlineStatus.WaitPublish - }); - } - else if (config.Value != kv.Value) - { - config.Value = value; - config.UpdateTime = now; - if (config.OnlineStatus == OnlineStatus.Online) - { - config.EditStatus = EditStatus.Edit; - config.OnlineStatus = OnlineStatus.WaitPublish; - } - else - { - if (config.EditStatus == EditStatus.Add) - { - //do nothing - } - - if (config.EditStatus == EditStatus.Edit) - { - //do nothing - } - - if (config.EditStatus == EditStatus.Deleted) - { - //上一次是删除状态,现在恢复为编辑状态 - config.EditStatus = EditStatus.Edit; - } - } - - updateConfigs.Add(config); - } - } - - if (!isPatch) //补丁模式不删除现有配置,只有全量模式才删除 - { - var keys = dict.Keys.ToList(); - foreach (var item in currentConfigs) - { - var key = GenerateKey(item); - if (!keys.Contains(key)) - { - item.EditStatus = EditStatus.Deleted; - item.OnlineStatus = OnlineStatus.WaitPublish; - deleteConfigs.Add(item); - } - } - } - - if (addConfigs.Any()) - { - await GetRepository(env).InsertAsync(addConfigs); - } - - if (updateConfigs.Any()) - { - await GetRepository(env).UpdateAsync(updateConfigs); - } - - if (deleteConfigs.Any()) - { - await GetRepository(env).UpdateAsync(deleteConfigs); - } - - return true; - } - - /// - /// 保存json字符串为配置项 - /// - /// - /// - /// - /// - /// - /// - public async Task SaveJsonAsync(string json, string appId, string env, bool isPatch) - { - if (string.IsNullOrEmpty(json)) - { - throw new ArgumentNullException("json"); - } - - byte[] byteArray = Encoding.UTF8.GetBytes(json); - using var stream = new MemoryStream(byteArray); - var dict = JsonConfigurationFileParser.Parse(stream); - - return await SaveFromDictAsync(dict, appId, env, isPatch); - } - - public (bool, string) ValidateKvString(string kvStr) - { - StringReader sr = new StringReader(kvStr); - int row = 0; - var dict = new Dictionary(); - while (true) - { - var line = sr.ReadLine(); - if (line == null) - { - break; - } - - row++; - //必须要有=号 - if (line.IndexOf('=') < 0) - { - return (false, $"第 {row} 行缺少等号。"); - } - - var index = line.IndexOf('='); - var key = line.Substring(0, index); - if (dict.ContainsKey(key)) - { - return (false, $"键 {key} 重复。"); - } - - dict.Add(key, ""); - } - - return (true, ""); - } - - public void ClearCache() - { - if (memoryCache != null && memoryCache is MemoryCache memCache) - { - memCache.Compact(1.0); - } - } - - public async Task SaveKvListAsync(string kvString, string appId, string env, bool isPatch) - { - if (kvString == null) - { - throw new ArgumentNullException(nameof(kvString)); - } - - StringReader sr = new StringReader(kvString); - var dict = new Dictionary(); - while (true) - { - var line = sr.ReadLine(); - if (line == null) - { - break; - } - - var index = line.IndexOf('='); - if (index < 0) - { - continue; - } - - var key = line.Substring(0, index); - var val = line.Substring(index + 1, line.Length - index - 1); - - dict.Add(key, val); - } - - return await SaveFromDictAsync(dict, appId, env, isPatch); - } - - private (string, string) SplitJsonKey(string key) - { - if (string.IsNullOrEmpty(key)) - { - throw new ArgumentNullException(nameof(key)); - } - - var index = key.LastIndexOf(':'); - if (index >= 0) - { - var group = key.Substring(0, index); - var newkey = key.Substring(index + 1, key.Length - index - 1); - - return (group, newkey); - } - - return ("", key); - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ConfigStatusUpdateRegister.cs b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ConfigStatusUpdateRegister.cs deleted file mode 100644 index 42259f8e..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ConfigStatusUpdateRegister.cs +++ /dev/null @@ -1,128 +0,0 @@ -using Agile.Config.Protocol; -using AgileConfig.Server.Common; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.IService; - -namespace AgileConfig.Server.Mongodb.Service.EventRegisterService; - -internal class ConfigStatusUpdateRegister : IEventRegister -{ - private readonly IRemoteServerNodeProxy _remoteServerNodeProxy; - private readonly IServerNodeService _serverNodeService; - private readonly IAppService _appService; - - public ConfigStatusUpdateRegister( - IRemoteServerNodeProxy remoteServerNodeProxy, - IServerNodeService serverNodeService, - IAppService appService) - { - _remoteServerNodeProxy = remoteServerNodeProxy; - _serverNodeService = serverNodeService; - _appService = appService; - } - - public void Register() - { - TinyEventBus.Instance.Register(EventKeys.PUBLISH_CONFIG_SUCCESS, (param) => - { - dynamic param_dy = param; - PublishTimeline timelineNode = param_dy.publishTimelineNode; - if (timelineNode != null) - { - Task.Run(async () => - { - var nodes = await _serverNodeService.GetAllNodesAsync(); - var noticeApps = await GetNeedNoticeInheritancedFromAppsAction(timelineNode.AppId); - noticeApps.Add(timelineNode.AppId, - new WebsocketAction { Action = ActionConst.Reload, Module = ActionModule.ConfigCenter }); - - foreach (var node in nodes) - { - if (node.Status == NodeStatus.Offline) - { - continue; - } - - //all server cache - await _remoteServerNodeProxy.ClearConfigServiceCache(node.Id as string); - } - - foreach (var node in nodes) - { - if (node.Status == NodeStatus.Offline) - { - continue; - } - - foreach (var item in noticeApps) - { - await _remoteServerNodeProxy.AppClientsDoActionAsync( - node.Id as string, - item.Key, - timelineNode.Env, - item.Value); - } - } - }); - } - }); - - TinyEventBus.Instance.Register(EventKeys.ROLLBACK_CONFIG_SUCCESS, (param) => - { - dynamic param_dy = param; - PublishTimeline timelineNode = param_dy.timelineNode; - if (timelineNode != null) - { - Task.Run(async () => - { - var nodes = await _serverNodeService.GetAllNodesAsync(); - var noticeApps = await GetNeedNoticeInheritancedFromAppsAction(timelineNode.AppId); - noticeApps.Add(timelineNode.AppId, - new WebsocketAction - { Action = ActionConst.Reload, Module = ActionModule.ConfigCenter }); - - foreach (var node in nodes) - { - if (node.Status == NodeStatus.Offline) - { - continue; - } - - foreach (var item in noticeApps) - { - await _remoteServerNodeProxy.AppClientsDoActionAsync(node.Id.ToString(), item.Key, - timelineNode.Env, - item.Value); - } - } - }); - } - }); - } - - /// - /// 根据当前配置计算需要通知的应用 - /// - /// - private async Task> GetNeedNoticeInheritancedFromAppsAction(string appId) - { - Dictionary needNoticeAppsActions = new Dictionary - { - }; - - var currentApp = await _appService.GetAsync(appId); - if (currentApp.Type == AppType.Inheritance) - { - var inheritancedFromApps = await _appService.GetInheritancedFromAppsAsync(appId); - inheritancedFromApps.ForEach(x => - { - needNoticeAppsActions.Add(x.Id as string, new WebsocketAction - { - Action = ActionConst.Reload, Module = ActionModule.ConfigCenter - }); - }); - } - - return needNoticeAppsActions; - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/EventRegister.cs b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/EventRegister.cs deleted file mode 100644 index c3d518e3..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/EventRegister.cs +++ /dev/null @@ -1,19 +0,0 @@ -using AgileConfig.Server.Common.RestClient; -using AgileConfig.Server.IService; -using Microsoft.Extensions.Logging; - -namespace AgileConfig.Server.Mongodb.Service.EventRegisterService; - -public class EventRegister(EventRegisterResolver eventRegisterResolver) : IEventRegister -{ - private readonly IEventRegister? _configStatusUpdateRegister = eventRegisterResolver(nameof(ConfigStatusUpdateRegister)); - private readonly IEventRegister? _sysLogRegister = eventRegisterResolver(nameof(SysLogRegister)); - private readonly IEventRegister? _serviceInfoStatusUpdateRegister = eventRegisterResolver(nameof(ServiceInfoStatusUpdateRegister)); - - public void Register() - { - _configStatusUpdateRegister?.Register(); - _sysLogRegister?.Register(); - _serviceInfoStatusUpdateRegister?.Register(); - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs deleted file mode 100644 index 6a919872..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System.Net; -using Agile.Config.Protocol; -using AgileConfig.Server.Common; -using AgileConfig.Server.Common.RestClient; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.IService; -using Microsoft.Extensions.Logging; - -namespace AgileConfig.Server.Mongodb.Service.EventRegisterService; - -internal class ServiceInfoStatusUpdateRegister : IEventRegister -{ - private readonly IRemoteServerNodeProxy _remoteServerNodeProxy; - private readonly IServerNodeService _serverNodeService; - private readonly IServiceInfoService _serviceInfoService; - private readonly IRestClient _restClient; - private ILogger _logger; - - public ServiceInfoStatusUpdateRegister( - IRemoteServerNodeProxy remoteServerNodeProxy, - IServerNodeService serverNodeService, - IServiceInfoService serviceInfoService, - ILoggerFactory loggerFactory, - IRestClient restClient) - { - _remoteServerNodeProxy = remoteServerNodeProxy; - _serverNodeService = serverNodeService; - _serviceInfoService = serviceInfoService; - _restClient = restClient; - _logger = loggerFactory.CreateLogger(); - } - - public void Register() - { - TinyEventBus.Instance.Register(EventKeys.REGISTER_A_SERVICE, (param) => - { - Task.Run(async () => - { - var serverNodes = await _serverNodeService.GetAllNodesAsync(); - foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) - { - //clear cache - _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Id as string); - //send ws action - var act = new WebsocketAction() - { - Module = ActionModule.RegisterCenter, - Action = ActionConst.Reload - }; - _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Id as string, act); - } - }); - }); - TinyEventBus.Instance.Register(EventKeys.UNREGISTER_A_SERVICE, (param) => - { - Task.Run(async () => - { - var serverNodes = await _serverNodeService.GetAllNodesAsync(); - foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) - { - //clear cache - _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Id as string); - //send ws action - var act = new WebsocketAction() - { - Module = ActionModule.RegisterCenter, - Action = ActionConst.Reload - }; - _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Id as string, act); - } - }); - }); - TinyEventBus.Instance.Register(EventKeys.UPDATE_SERVICE_STATUS, (param) => - { - Task.Run(async () => - { - var serverNodes = await _serverNodeService.GetAllNodesAsync(); - foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) - { - //clear cache - _ = _remoteServerNodeProxy.ClearServiceInfoCache(serverNode.Id as string); - //send ws action - var act = new WebsocketAction() - { - Module = ActionModule.RegisterCenter, - Action = ActionConst.Reload - }; - _ = _remoteServerNodeProxy.AllClientsDoActionAsync(serverNode.Id as string, act); - } - }); - }); - TinyEventBus.Instance.Register(EventKeys.UPDATE_SERVICE_STATUS, (param) => - { - Task.Run(async () => - { - dynamic paramObj = param; - string id = paramObj.UniqueId; - var service = await _serviceInfoService.GetByUniqueIdAsync(id); - if (service != null && !string.IsNullOrWhiteSpace(service.AlarmUrl) && - service.Status == ServiceStatus.Unhealthy) - { - //如果是下线发送通知 - _ = SendServiceOfflineMessageAsync(service); - } - }); - }); - } - - private async Task SendServiceOfflineMessageAsync(ServiceInfo service) - { - var msg = new - { - UniqueId = service.Id, - service.ServiceId, - service.ServiceName, - Time = DateTime.Now, - Status = ServiceStatus.Unhealthy.ToString(), - Message = "服务不健康" - }; - - try - { - await FunctionUtil.TRYAsync(async () => - { - var content = new StringContent(""); - content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); - using var resp = await _restClient.PostAsync(service.AlarmUrl, null); - - resp.EnsureSuccessStatusCode(); - - return resp.StatusCode == HttpStatusCode.OK; - }, 5); - } - catch (Exception e) - { - _logger.LogError(e, $"try to send message to alarm url {service.AlarmUrl} failed"); - } - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/SysLogRegister.cs b/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/SysLogRegister.cs deleted file mode 100644 index 93f9450f..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/EventRegisterService/SysLogRegister.cs +++ /dev/null @@ -1,475 +0,0 @@ -using AgileConfig.Server.Common; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.IService; - -namespace AgileConfig.Server.Mongodb.Service.EventRegisterService; - -internal class SysLogRegister(ISysLogService sysLogService) : IEventRegister -{ - public void Register() - { - TinyEventBus.Instance.Register(EventKeys.USER_LOGIN_SUCCESS, (param) => - { - dynamic param_dy = param as dynamic; - string userName = param_dy.userName; - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - LogText = $"{userName} 登录成功" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - - TinyEventBus.Instance.Register(EventKeys.INIT_SUPERADMIN_PASSWORD_SUCCESS, (parm) => - { - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - LogText = $"超级管理员密码初始化成功" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - - TinyEventBus.Instance.Register(EventKeys.RESET_USER_PASSWORD_SUCCESS, (param) => - { - dynamic param_dy = param as dynamic; - User user = param_dy.user; - string userName = param_dy.userName; - - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - LogText = $"用户 {userName} 重置 {user.UserName} 的密码为默认密码 " - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - - TinyEventBus.Instance.Register(EventKeys.CHANGE_USER_PASSWORD_SUCCESS, (param) => - { - dynamic param_dy = param as dynamic; - string userName = param_dy.userName; - - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - LogText = $"修改用户 {userName} 的密码成功" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - - TinyEventBus.Instance.Register(EventKeys.ADD_APP_SUCCESS, (param) => - { - dynamic param_dy = param; - App app = param_dy.app; - string userName = param_dy.userName; - if (app != null) - { - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - LogText = $"用户:{userName} 新增应用【AppId:{app.Id}】【AppName:{app.Name}】" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - } - }); - - // app - TinyEventBus.Instance.Register(EventKeys.EDIT_APP_SUCCESS, (param) => - { - dynamic param_dy = param; - App app = param_dy.app; - string userName = param_dy.userName; - if (app != null) - { - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - LogText = $"用户:{userName} 编辑应用【AppId:{app.Id}】【AppName:{app.Name}】" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - } - }); - - TinyEventBus.Instance.Register(EventKeys.DISABLE_OR_ENABLE_APP_SUCCESS, (param) => - { - dynamic param_dy = param; - App app = param_dy.app; - string userName = param_dy.userName; - if (app != null) - { - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - LogText = $"用户:{userName} {(app.Enabled ? "启用" : "禁用")}应用【AppId:{app.Id}】" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - } - }); - - TinyEventBus.Instance.Register(EventKeys.DELETE_APP_SUCCESS, (param) => - { - dynamic param_dy = param; - App app = param_dy.app; - string userName = param_dy.userName; - if (app != null) - { - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Warn, - LogText = $"用户:{userName} 删除应用【AppId:{app.Id}】" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - } - }); - - //config - TinyEventBus.Instance.Register(EventKeys.ADD_CONFIG_SUCCESS, (param) => - { - dynamic param_dy = param; - Config config = param_dy.config; - string userName = param_dy.userName; - - if (config != null) - { - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - AppId = config.AppId, - LogText = - $"用户:{userName} 新增配置【Group:{config.Group}】【Key:{config.Key}】【AppId:{config.AppId}】【Env:{config.Env}】【待发布】" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - } - }); - TinyEventBus.Instance.Register(EventKeys.EDIT_CONFIG_SUCCESS, (param) => - { - dynamic param_dy = param; - Config config = param_dy.config; - string userName = param_dy.userName; - - if (config != null) - { - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - AppId = config.AppId, - LogText = - $"用户:{userName} 编辑配置【Group:{config.Group}】【Key:{config.Key}】【AppId:{config.AppId}】【Env:{config.Env}】【待发布】" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - } - }); - - TinyEventBus.Instance.Register(EventKeys.DELETE_CONFIG_SUCCESS, (param) => - { - dynamic param_dy = param; - Config config = param_dy.config; - string userName = param_dy.userName; - - if (config != null) - { - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Warn, - AppId = config.AppId, - LogText = - $"用户:{userName} 删除配置【Group:{config.Group}】【Key:{config.Key}】【AppId:{config.AppId}】【Env:{config.Env}】【待发布】" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - } - }); - TinyEventBus.Instance.Register(EventKeys.DELETE_CONFIG_SOME_SUCCESS, (param) => - { - dynamic param_dy = param; - string userName = param_dy.userName; - string appId = param_dy.appId; - string env = param_dy.env; - if (appId != null) - { - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Warn, - AppId = appId, - LogText = $"用户:{userName} 批量删除配置【Env:{env}】" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - } - }); - - TinyEventBus.Instance.Register(EventKeys.PUBLISH_CONFIG_SUCCESS, (param) => - { - dynamic param_dy = param; - PublishTimeline node = param_dy.publishTimelineNode; - string userName = param_dy.userName; - string env = param_dy.env; - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - AppId = node.AppId, - LogText = - $"用户:{userName} 发布配置【AppId:{node.AppId}】【Env:{env}】【版本:{node.PublishTime.Value:yyyyMMddHHmmss}】" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - TinyEventBus.Instance.Register(EventKeys.ROLLBACK_CONFIG_SUCCESS, (param) => - { - dynamic param_dy = param; - string userName = param_dy.userName; - PublishTimeline timelineNode = param_dy.timelineNode; - string env = param_dy.env; - - if (timelineNode != null) - { - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Warn, - AppId = timelineNode.AppId, - LogText = - $"{userName} 回滚应用【{timelineNode.AppId}】【Env:{env}】至发布版本【{timelineNode.PublishTime.Value:yyyyMMddHHmmss}】" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - } - }); - TinyEventBus.Instance.Register(EventKeys.CANCEL_EDIT_CONFIG_SUCCESS, (param) => - { - dynamic param_dy = param; - string userName = param_dy.userName; - Config config = param_dy.config; - - if (config != null) - { - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - AppId = config.AppId, - LogText = - $"{userName} 撤销编辑状态的配置【Group:{config.Group}】【Key:{config.Key}】【AppId:{config.AppId}】【Env:{config.Env}】" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - } - }); - TinyEventBus.Instance.Register(EventKeys.CANCEL_EDIT_CONFIG_SOME_SUCCESS, (param) => - { - dynamic param_dy = param; - string userName = param_dy.userName; - string appId = param_dy.appId; - string env = param_dy.env; - - if (appId != null) - { - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - AppId = appId, - LogText = $"{userName} 批量撤销编辑状态的配置【Env:{env}】" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - } - }); - TinyEventBus.Instance.Register(EventKeys.ADD_NODE_SUCCESS, (param) => - { - dynamic param_dy = param; - ServerNode node = param_dy.node; - string userName = param_dy.userName; - - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - LogText = $"用户:{userName} 添加节点:{node.Id}" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - - TinyEventBus.Instance.Register(EventKeys.DELETE_NODE_SUCCESS, (param) => - { - dynamic param_dy = param; - ServerNode node = param_dy.node; - string userName = param_dy.userName; - - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Warn, - LogText = $"用户:{userName} 删除节点:{node.Id}" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - - TinyEventBus.Instance.Register(EventKeys.ADD_USER_SUCCESS, (param) => - { - dynamic param_dy = param; - User user = param_dy.user; - string userName = param_dy.userName; - - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - LogText = $"用户:{userName} 添加用户:{user.UserName} 成功" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - - TinyEventBus.Instance.Register(EventKeys.EDIT_USER_SUCCESS, (param) => - { - dynamic param_dy = param; - User user = param_dy.user; - string userName = param_dy.userName; - - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - LogText = $"用户:{userName} 编辑用户:{user.UserName} 成功" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - - TinyEventBus.Instance.Register(EventKeys.DELETE_USER_SUCCESS, (param) => - { - dynamic param_dy = param; - User user = param_dy.user; - string userName = param_dy.userName; - - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Warn, - LogText = $"用户:{userName} 删除用户:{user.UserName} 成功" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - - TinyEventBus.Instance.Register(EventKeys.DISCONNECT_CLIENT_SUCCESS, (param) => - { - dynamic param_dy = param; - string clientId = param_dy.clientId; - string userName = param_dy.userName; - - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Warn, - LogText = $"用户:{userName} 断开客户端 {clientId} 成功" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - - //service info envets - TinyEventBus.Instance.Register(EventKeys.REGISTER_A_SERVICE, (param) => - { - dynamic param_dy = param; - string serviceId = param_dy.ServiceId; - string serviceName = param_dy.ServiceName; - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - LogText = $"服务:【{serviceId}】【{serviceName}】 注册成功" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - TinyEventBus.Instance.Register(EventKeys.UNREGISTER_A_SERVICE, (param) => - { - dynamic param_dy = param; - string serviceId = param_dy.ServiceId; - string serviceName = param_dy.ServiceName; - var log = new SysLog - { - LogTime = DateTime.Now, - LogType = SysLogType.Normal, - LogText = $"服务:【{serviceId}】【{serviceName}】 卸载成功" - }; - Task.Run(async () => - { - await sysLogService.AddSysLogAsync(log); - }); - }); - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/JwtService.cs b/src/AgileConfig.Server.Mongodb.Service/JwtService.cs deleted file mode 100644 index 0bbd5e4f..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/JwtService.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.IdentityModel.Tokens.Jwt; -using System.Security.Claims; -using System.Text; -using AgileConfig.Server.Common; -using AgileConfig.Server.IService; -using Microsoft.IdentityModel.Tokens; - -namespace AgileConfig.Server.Mongodb.Service; - -public class JwtService(ISettingService settingService) : IJwtService -{ - public string Issuer => Global.Config["JwtSetting:Issuer"]; - public string Audience => Global.Config["JwtSetting:Audience"]; - public int ExpireSeconds => int.Parse(Global.Config["JwtSetting:ExpireSeconds"]); - - private string? _secretKey; - - public string GetSecurityKey() - { - if (!string.IsNullOrEmpty(_secretKey)) - { - return _secretKey; - } - - _secretKey = Global.Config["JwtSetting:SecurityKey"]; - if (!string.IsNullOrEmpty(_secretKey)) - { - return _secretKey; - } - - _secretKey = settingService.GetJwtTokenSecret(); - - if (string.IsNullOrEmpty(_secretKey)) - { - throw new ArgumentNullException($"No JwtSetting SecurityKey"); - } - - return _secretKey; - } - - public string GetToken(string userId, string userName, bool isAdmin) - { - //创建用户身份标识,可按需要添加更多信息 - var claims = new Claim[] - { - new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), - new Claim("id", userId, ClaimValueTypes.String), // 用户id - new Claim("username", userName, ClaimValueTypes.String), // 用户名 - new Claim("admin", isAdmin.ToString(), ClaimValueTypes.Boolean) // 是否是管理员 - }; - var key = Encoding.UTF8.GetBytes(GetSecurityKey()); - //创建令牌 - var token = new JwtSecurityToken( - issuer: Issuer, - audience: Audience, - signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), - SecurityAlgorithms.HmacSha256Signature), - claims: claims, - notBefore: DateTime.Now, - expires: DateTime.Now.AddSeconds(ExpireSeconds) - ); - - string jwtToken = new JwtSecurityTokenHandler().WriteToken(token); - - return jwtToken; - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs b/src/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs deleted file mode 100644 index b85a1ace..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/MongodbServiceExtensions.cs +++ /dev/null @@ -1,49 +0,0 @@ -using AgileConfig.Server.Data.Mongodb; -using AgileConfig.Server.IService; -using AgileConfig.Server.Mongodb.Service.EventRegisterService; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; - -namespace AgileConfig.Server.Mongodb.Service; - -public delegate IEventRegister? EventRegisterResolver(string key); - -public static class MongodbServiceExtensions -{ - public static void AddBusinessForMongoServices(this IServiceCollection services) - { - services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); - services.AddSingleton(); - - services.AddScoped(); - - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(x => key => - { - return key switch - { - nameof(ConfigStatusUpdateRegister) => x.GetService(), - nameof(ServiceInfoStatusUpdateRegister) => x.GetService(), - nameof(SysLogRegister) => x.GetService(), - _ => x.GetService() - }; - }); - - services.AddScoped(); - services.AddScoped(); - - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - services.AddScoped(); - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/PermissionService.cs b/src/AgileConfig.Server.Mongodb.Service/PermissionService.cs deleted file mode 100644 index 2a715d2c..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/PermissionService.cs +++ /dev/null @@ -1,230 +0,0 @@ -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Mongodb; -using AgileConfig.Server.IService; -using MongoDB.Driver; - -namespace AgileConfig.Server.Mongodb.Service; - -public class PermissionService( - IRepository userRoleRepository, - IRepository userAppAuthRepository, - IRepository appRepository) : IPremissionService -{ - private static readonly List Template_SuperAdminPermissions = new List - { - "GLOBAL_" + Functions.App_Add, - "GLOBAL_" + Functions.App_Delete, - "GLOBAL_" + Functions.App_Edit, - "GLOBAL_" + Functions.App_Auth, - - "GLOBAL_" + Functions.Config_Add, - "GLOBAL_" + Functions.Config_Delete, - "GLOBAL_" + Functions.Config_Edit, - "GLOBAL_" + Functions.Config_Offline, - "GLOBAL_" + Functions.Config_Publish, - - "GLOBAL_" + Functions.Node_Add, - "GLOBAL_" + Functions.Node_Delete, - - "GLOBAL_" + Functions.Client_Disconnect, - - "GLOBAL_" + Functions.User_Add, - "GLOBAL_" + Functions.User_Edit, - "GLOBAL_" + Functions.User_Delete, - }; - - private static readonly List Template_NormalAdminPermissions = new List - { - "GLOBAL_" + Functions.App_Add, - "GLOBAL_" + Functions.Node_Add, - "GLOBAL_" + Functions.Node_Delete, - "GLOBAL_" + Functions.Client_Disconnect, - - "GLOBAL_" + Functions.User_Add, - "GLOBAL_" + Functions.User_Edit, - "GLOBAL_" + Functions.User_Delete, - - "APP_{0}_" + Functions.App_Delete, - "APP_{0}_" + Functions.App_Edit, - "APP_{0}_" + Functions.App_Auth, - - "APP_{0}_" + Functions.Config_Add, - "APP_{0}_" + Functions.Config_Delete, - "APP_{0}_" + Functions.Config_Edit, - "APP_{0}_" + Functions.Config_Offline, - "APP_{0}_" + Functions.Config_Publish, - }; - - private static readonly List Template_NormalUserPermissions_Edit = new List - { - "APP_{0}_" + Functions.Config_Add, - "APP_{0}_" + Functions.Config_Delete, - "APP_{0}_" + Functions.Config_Edit, - }; - - private static readonly List Template_NormalUserPermissions_Publish = new List - { - "APP_{0}_" + Functions.Config_Offline, - "APP_{0}_" + Functions.Config_Publish - }; - - private async Task> GetAdminUserFunctions(string userId) - { - var userFunctions = new List(); - //获取当前用户为管理员的app - var adminApps = await GetUserAdminApps(userId); - Template_NormalAdminPermissions.Where(x => x.StartsWith("GLOBAL_")).ToList().ForEach( - key => { userFunctions.Add(key); } - ); - Template_NormalUserPermissions_Edit.Where(x => x.StartsWith("GLOBAL_")).ToList().ForEach( - key => { userFunctions.Add(key); } - ); - Template_NormalUserPermissions_Publish.Where(x => x.StartsWith("GLOBAL_")).ToList().ForEach( - key => { userFunctions.Add(key); } - ); - foreach (var app in adminApps) - { - foreach (var temp in Template_NormalAdminPermissions) - { - if (temp.StartsWith("APP_{0}_")) - { - userFunctions.Add(string.Format(temp, app.Id)); - } - } - } - - //EditConfigPermissionKey - var editPermissionApps = await GetUserAuthApp(userId, EditConfigPermissionKey); - foreach (var app in editPermissionApps) - { - foreach (var temp in Template_NormalUserPermissions_Edit) - { - if (temp.StartsWith("APP_{0}_")) - { - userFunctions.Add(string.Format(temp, app.Id)); - } - } - } - - //PublishConfigPermissionKey - var publishPermissionApps = await GetUserAuthApp(userId, PublishConfigPermissionKey); - foreach (var app in publishPermissionApps) - { - foreach (var temp in Template_NormalUserPermissions_Publish) - { - if (temp.StartsWith("APP_{0}_")) - { - userFunctions.Add(string.Format(temp, app.Id)); - } - } - } - - return userFunctions; - } - - private async Task> GetNormalUserFunctions(string userId) - { - var userFunctions = new List(); - //EditConfigPermissionKey - var editPermissionApps = await GetUserAuthApp(userId, EditConfigPermissionKey); - foreach (var app in editPermissionApps) - { - foreach (var temp in Template_NormalUserPermissions_Edit) - { - if (temp.StartsWith("GLOBAL_")) - { - userFunctions.Add(temp); - } - - if (temp.StartsWith("APP_{0}_")) - { - userFunctions.Add(string.Format(temp, app.Id)); - } - } - } - - //PublishConfigPermissionKey - var publishPermissionApps = await GetUserAuthApp(userId, PublishConfigPermissionKey); - foreach (var app in publishPermissionApps) - { - foreach (var temp in Template_NormalUserPermissions_Publish) - { - if (temp.StartsWith("GLOBAL_")) - { - userFunctions.Add(temp); - } - - if (temp.StartsWith("APP_{0}_")) - { - userFunctions.Add(string.Format(temp, app.Id)); - } - } - } - - return userFunctions; - } - - /// - /// 获取角色权限的模板 - /// - /// - /// - public async Task> GetUserPermission(string userId) - { - var userRoles = await userRoleRepository.SearchFor(x => x.UserId == userId).ToListAsync(); - if (userRoles.Any(x => x.Role == Role.SuperAdmin)) - { - return Template_SuperAdminPermissions; - } - - var userFunctions = new List(); - //计算普通管理员的权限 - if (userRoles.Any(x => x.Role == Role.Admin)) - { - userFunctions.AddRange(await GetAdminUserFunctions(userId)); - } - - //计算普通用户的权限 - if (userRoles.Any(x => x.Role == Role.NormalUser)) - { - userFunctions.AddRange(await GetNormalUserFunctions(userId)); - } - - return userFunctions.Distinct().ToList(); - } - - /// - /// 获取被授权给用户的app - /// - /// - /// - private async Task> GetUserAuthApp(string userId, string authPermissionKey) - { - var apps = new List(); - var userAuths = await userAppAuthRepository.SearchFor(x => x.UserId == userId && x.Permission == authPermissionKey).ToListAsync(); - foreach (var appAuth in userAuths) - { - var app = await appRepository.SearchFor(x => x.Id == appAuth.AppId).FirstAsync(); - if (app != null) - { - apps.Add(app); - } - } - - return apps; - } - - /// - /// 获取是管理员的app - /// - /// - /// - private async Task> GetUserAdminApps(string userId) - { - return await appRepository.SearchFor(x => x.AppAdmin == userId).ToListAsync(); - } - - public string EditConfigPermissionKey => "EDIT_CONFIG"; - - public string PublishConfigPermissionKey => "PUBLISH_CONFIG"; -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/RegisterCenterService.cs b/src/AgileConfig.Server.Mongodb.Service/RegisterCenterService.cs deleted file mode 100644 index 02167097..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/RegisterCenterService.cs +++ /dev/null @@ -1,153 +0,0 @@ -using System.Dynamic; -using AgileConfig.Server.Common; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Mongodb; -using AgileConfig.Server.IService; -using Microsoft.Extensions.Logging; -using MongoDB.Driver.Linq; - -namespace AgileConfig.Server.Mongodb.Service; - -public class RegisterCenterService( - IRepository serviceInfoRepository, - IServiceInfoService serviceInfoService, - ILogger logger) : IRegisterCenterService -{ - public async Task RegisterAsync(ServiceInfo serviceInfo) - { - if (serviceInfo == null) - { - throw new ArgumentNullException(nameof(serviceInfo)); - } - - - //if exist - var oldEntity = await serviceInfoRepository.SearchFor(x => x.ServiceId == serviceInfo.ServiceId) - .FirstOrDefaultAsync(); - if (oldEntity != null) - { - oldEntity.RegisterTime = DateTime.Now; - oldEntity.Status = ServiceStatus.Healthy; - oldEntity.LastHeartBeat = DateTime.Now; - oldEntity.ServiceName = serviceInfo.ServiceName; - oldEntity.Ip = serviceInfo.Ip; - oldEntity.Port = serviceInfo.Port; - oldEntity.MetaData = serviceInfo.MetaData; - oldEntity.HeartBeatMode = serviceInfo.HeartBeatMode; - oldEntity.CheckUrl = serviceInfo.CheckUrl; - oldEntity.AlarmUrl = serviceInfo.AlarmUrl; - oldEntity.RegisterWay = serviceInfo.RegisterWay; - await serviceInfoRepository.UpdateAsync(oldEntity); - - serviceInfoService.ClearCache(); - - logger.LogInformation("registered service {ServiceId} {ServiceName} successful", serviceInfo.ServiceId, - serviceInfo.ServiceName); - - return oldEntity.Id; - } - - serviceInfo.RegisterTime = DateTime.Now; - serviceInfo.LastHeartBeat = DateTime.Now; - serviceInfo.Status = ServiceStatus.Healthy; - serviceInfo.Id = Guid.NewGuid().ToString("n"); - - await serviceInfoRepository.InsertAsync(serviceInfo); - serviceInfoService.ClearCache(); - - logger.LogInformation("registered service {ServiceId} {ServiceName} successful", serviceInfo.ServiceId, - serviceInfo.ServiceName); - - return serviceInfo.Id; - } - - public async Task UnRegisterAsync(string serviceUniqueId) - { - logger.LogInformation("try to unregister service {ServiceUniqueId}", serviceUniqueId); - - if (string.IsNullOrEmpty(serviceUniqueId)) - { - throw new ArgumentNullException(nameof(serviceUniqueId)); - } - - var oldEntity = await serviceInfoRepository.SearchFor(x => x.Id == serviceUniqueId).FirstOrDefaultAsync(); - if (oldEntity == null) - { - //if not exist - logger.LogInformation("not find the service {ServiceUniqueId} ", serviceUniqueId); - return false; - } - - await serviceInfoRepository.DeleteAsync(oldEntity.Id.ToString()); - - serviceInfoService.ClearCache(); - - logger.LogInformation("unregister service {ServiceId} {ServiceName} successful", oldEntity.ServiceId, - oldEntity.ServiceName); - - return true; - } - - public async Task UnRegisterByServiceIdAsync(string serviceId) - { - logger.LogInformation("try to unregister service {ServiceId}", serviceId); - - if (string.IsNullOrEmpty(serviceId)) - { - throw new ArgumentNullException(nameof(serviceId)); - } - - var oldEntity = await serviceInfoRepository.SearchFor(x => x.ServiceId == serviceId).FirstOrDefaultAsync(); - if (oldEntity == null) - { - //if not exist - logger.LogInformation("not find the service {ServiceId}", serviceId); - return false; - } - - await serviceInfoRepository.DeleteAsync(oldEntity.Id.ToString()); - - serviceInfoService.ClearCache(); - - logger.LogInformation("unregister service {ServiceId} {ServiceName} successful", oldEntity.ServiceId, - oldEntity.ServiceName); - - return true; - } - - public async Task ReceiveHeartbeatAsync(string serviceUniqueId) - { - var entity = await serviceInfoRepository.FindAsync(serviceUniqueId); - if (entity == null) - { - return false; - } - - logger.LogInformation("receive service {ServiceId} {ServiceName} heartbeat", entity.ServiceId, entity.ServiceName); - - if (entity.HeartBeatMode == "server") - { - //如果是server模式,则不作为服务是否在线的判断依据 - } - else - { - var oldStatus = entity.Status; - entity.Status = ServiceStatus.Healthy; - entity.LastHeartBeat = DateTime.Now; - await serviceInfoRepository.UpdateAsync(entity); - - - if (oldStatus != ServiceStatus.Healthy) - { - serviceInfoService.ClearCache(); - dynamic param = new ExpandoObject(); - param.ServiceId = entity.ServiceId; - param.ServiceName = entity.ServiceName; - param.UniqueId = entity.Id; - TinyEventBus.Instance.Fire(EventKeys.UPDATE_SERVICE_STATUS, param); - } - } - - return true; - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/RemoteServerNodeProxy.cs b/src/AgileConfig.Server.Mongodb.Service/RemoteServerNodeProxy.cs deleted file mode 100644 index 868a09fb..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/RemoteServerNodeProxy.cs +++ /dev/null @@ -1,272 +0,0 @@ -using System.Collections.Concurrent; -using Agile.Config.Protocol; -using AgileConfig.Server.Common; -using AgileConfig.Server.Common.RestClient; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.IService; -using Microsoft.Extensions.Logging; - -namespace AgileConfig.Server.Mongodb.Service; - -public class RemoteServerNodeProxy( - IServerNodeService serverNodeService, - ISysLogService sysLogService, - ILoggerFactory loggerFactory, - IRestClient restClient) - : IRemoteServerNodeProxy -{ - - private readonly ILogger _logger = loggerFactory.CreateLogger(); - - - private static readonly ConcurrentDictionary _serverNodeClientReports = - new ConcurrentDictionary(); - - public async Task AllClientsDoActionAsync(string address, WebsocketAction action) - { - var result = await FunctionUtil.TRYAsync(async () => - { - dynamic result = await restClient.PostAsync(address + "/RemoteOP/AllClientsDoAction", action); - if ((bool)result.success) - { - return true; - } - - return false; - }, 5); - - var module = ""; - if (action.Module == "r") - { - module = "注册中心"; - } - - if (action.Module == "c") - { - module = "配置中心"; - } - - await sysLogService.AddSysLogAsync(new SysLog - { - LogTime = DateTime.Now, - LogType = result ? SysLogType.Normal : SysLogType.Warn, - LogText = $"通知节点【{address}】所有客户端:【{module}】【{action.Action}】 响应:{(result ? "成功" : "失败")}" - }); - - return result; - } - - public async Task AppClientsDoActionAsync(string address, string appId, string env, WebsocketAction action) - { - var result = await FunctionUtil.TRYAsync(async () => - { - var url = $"{address}/RemoteOP/AppClientsDoAction?appId={Uri.EscapeDataString(appId)}&env={env}"; - dynamic result = await restClient.PostAsync(url, action); - if ((bool)result.success) - { - return true; - } - - return false; - }, 5); - - - var module = ""; - if (action.Module == "r") - { - module = "注册中心"; - } - - if (action.Module == "c") - { - module = "配置中心"; - } - - await sysLogService.AddSysLogAsync(new SysLog - { - LogTime = DateTime.Now, - LogType = result ? SysLogType.Normal : SysLogType.Warn, - AppId = appId, - LogText = $"通知节点【{address}】应用【{appId}】的客户端:【{module}】【{action.Action}】 响应:{(result ? "成功" : "失败")}" - }); - - - return result; - } - - public async Task OneClientDoActionAsync(string address, string clientId, WebsocketAction action) - { - var result = await FunctionUtil.TRYAsync(async () => - { - var url = $"{address}/RemoteOP/OneClientDoAction?clientId={clientId}"; - dynamic result = await restClient.PostAsync(url, action); - - if ((bool)result.success) - { - if (action.Action == ActionConst.Offline) - { - if (_serverNodeClientReports.ContainsKey(address)) - { - if (_serverNodeClientReports[address].Infos != null) - { - var report = _serverNodeClientReports[address]; - report.Infos.RemoveAll(c => c.Id == clientId); - report.ClientCount = report.Infos.Count; - } - } - } - - return true; - } - - return false; - }, 5); - - - var module = ""; - if (action.Module == "r") - { - module = "注册中心"; - } - - if (action.Module == "c") - { - module = "配置中心"; - } - - await sysLogService.AddSysLogAsync(new SysLog - { - LogTime = DateTime.Now, - LogType = result ? SysLogType.Normal : SysLogType.Warn, - LogText = $"通知节点【{address}】的客户端【{clientId}】:【{module}】【{action.Action}】 响应:{(result ? "成功" : "失败")}" - }); - - - return result; - } - - public async Task GetClientsReportAsync(string address) - { - if (string.IsNullOrEmpty(address)) - { - return new ClientInfos() - { - ClientCount = 0, - Infos = new List() - }; - } - - try - { - var url = address + "/report/Clients"; - - var clients = await restClient.GetAsync(url); - if (clients != null) - { - clients.Infos?.ForEach(i => { i.Address = address; }); - return clients; - } - - return new ClientInfos() - { - ClientCount = 0, - Infos = new List() - }; - } - catch (Exception ex) - { - _logger?.LogError(ex,"Try to get client infos from node {Address} occur ERROR ",address); - } - - return new ClientInfos() - { - ClientCount = 0, - Infos = new List() - }; - } - - public async Task TestEchoAsync(string address) - { - var node = await serverNodeService.GetAsync(address); - try - { - var url = node.Id + "/home/echo"; - - using var resp = await restClient.GetAsync(url); - - if (resp.StatusCode == System.Net.HttpStatusCode.OK && (await resp.Content.ReadAsStringAsync()) == "ok") - { - node.LastEchoTime = DateTime.Now; - node.Status = NodeStatus.Online; - } - else - { - node.Status = NodeStatus.Offline; - } - } - catch (Exception e) - { - node.Status = NodeStatus.Offline; - _logger.LogInformation(e, "Try test node {Address} echo , but fail", node.Id); - } - - if (node.Status == NodeStatus.Offline) - { - var time = node.LastEchoTime ?? node.CreateTime; - - if ((DateTime.Now - time).TotalMinutes >= 30) - { - // 超过 30 分钟没有回应,则移除节点 - await serverNodeService.DeleteAsync(address); - return; - } - } - - await serverNodeService.UpdateAsync(node); - } - - public Task TestEchoAsync() - { - return Task.Run(async () => - { - while (true) - { - var nodes = await serverNodeService.GetAllNodesAsync(); - - foreach (var node in nodes) - { - await TestEchoAsync(node.Id as string); - } - - await Task.Delay(5000 * 1); - } - }); - } - - public async Task ClearConfigServiceCache(string address) - { - try - { - var url = (address + "/RemoteOP/ClearConfigServiceCache"); - using var resp = await restClient.PostAsync(url, null); - } - catch (Exception e) - { - _logger.LogError(e, "Try to clear node {Address}'s config cache , but fail", address); - } - } - - public async Task ClearServiceInfoCache(string address) - { - try - { - var url = (address + "/RemoteOP/ClearServiceInfoCache"); - - await restClient.PostAsync(url, null); - } - catch (Exception e) - { - _logger.LogError(e, "Try to clear node {Address}'s services info cache , but fail", address); - } - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/ServerNodeService.cs b/src/AgileConfig.Server.Mongodb.Service/ServerNodeService.cs deleted file mode 100644 index b94ce0c2..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/ServerNodeService.cs +++ /dev/null @@ -1,117 +0,0 @@ -using AgileConfig.Server.Common; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Mongodb; -using AgileConfig.Server.IService; -using MongoDB.Driver; -using MongoDB.Driver.Linq; - -namespace AgileConfig.Server.Mongodb.Service; - -public class ServerNodeService(IRepository repository) : IServerNodeService -{ - public async Task AddAsync(ServerNode node) - { - await repository.InsertAsync(node); - return true; - } - - public async Task DeleteAsync(ServerNode node) - { - var result = await repository.DeleteAsync(x => x.Id == node.Id); - return result.DeletedCount > 0; - } - - public async Task DeleteAsync(string address) - { - var result = await repository.DeleteAsync(x => x.Id == address); - return result.DeletedCount > 0; - } - - public void Dispose() - { - GC.SuppressFinalize(this); - } - - public Task> GetAllNodesAsync() - { - return repository.SearchFor(x => true).ToListAsync(); - } - - public Task GetAsync(string address) - { - return repository.SearchFor(n => n.Id == address).FirstOrDefaultAsync(); - } - - public async Task UpdateAsync(ServerNode node) - { - var result = await repository.UpdateAsync(node); - return result.ModifiedCount > 0; - } - - - public async Task InitWatchNodeAsync() - { - var count = await repository.SearchFor(x => true).CountAsync(); - if (count > 0) - { - return false; - } - - var nodes = Global.Config["nodes"]; - var addresses = new List(); - if (!string.IsNullOrEmpty(nodes)) - { - var arr = nodes.Split(','); - foreach (var item in arr) - { - var address = ""; - if (item.StartsWith("http", StringComparison.OrdinalIgnoreCase)) - { - address = item; - } - else - { - address = "http://" + item; - } - - addresses.Add(address); - } - } - - var existNodes = await repository.SearchFor(x => addresses.Contains(x.Id)).ToListAsync(); - var newNodes = addresses - .Where(x => existNodes.All(y => y.Id != x)) - .Select(x => new ServerNode { Id = x, CreateTime = DateTime.Now }) - .ToList(); - await repository.InsertAsync(newNodes); - - return true; - } - - public async Task JoinAsync(string ip, int port, string desc) - { - var address = $"http://{ip}:{port}"; - var nodes = await repository.SearchFor(x => x.Id == address).ToListAsync(); - if (nodes.Count > 0) - { - nodes.ForEach(n => - { - n.Id = address; - n.Remark = desc; - n.Status = NodeStatus.Online; - }); - } - else - { - await repository.InsertAsync(new ServerNode - { - Id = address, - CreateTime = DateTime.Now, - Remark = desc, - Status = NodeStatus.Online, - LastEchoTime = DateTime.Now - }); - } - return true; - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/ServiceHealthCheckService.cs b/src/AgileConfig.Server.Mongodb.Service/ServiceHealthCheckService.cs deleted file mode 100644 index f3be7b1c..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/ServiceHealthCheckService.cs +++ /dev/null @@ -1,204 +0,0 @@ -using AgileConfig.Server.Common; -using AgileConfig.Server.Common.RestClient; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Mongodb; -using AgileConfig.Server.IService; -using Microsoft.Extensions.Logging; -using MongoDB.Driver; - -namespace AgileConfig.Server.Mongodb.Service; - -public class ServiceHealthCheckService( - IRepository serviceInfoRepository, - IServiceInfoService serviceInfoService, - ILogger logger, - IRestClient restClient) - : IServiceHealthCheckService -{ - private readonly ILogger _logger = logger; - - private int _checkInterval; - private int _unhealthInterval; - private int _removeServiceInterval; - - /// - /// 健康检测的间隔 - /// - /// - private int CheckInterval - { - get - { - if (_checkInterval > 0) - { - return _checkInterval; - } - - var interval = Global.Config["serviceHealthCheckInterval"]; - if (int.TryParse(interval, out int i)) - { - if (i <= 0) - { - throw new ArgumentException("serviceHealthCheckInterval must be greater than 0"); - } - - _checkInterval = i; - } - - return _checkInterval; - } - } - - /// - /// 判断一个服务是否健康的标准时间,操作这个时间没有收到响应,则认为不健康 - /// - /// - private int UnhealthInterval - { - get - { - if (_unhealthInterval > 0) - { - return _unhealthInterval; - } - - var interval = Global.Config["serviceUnhealthInterval"]; - if (int.TryParse(interval, out int i)) - { - if (i <= 0) - { - throw new ArgumentException("serviceUnhealthInterval must be greater than 0"); - } - - _unhealthInterval = i; - } - - return _unhealthInterval; - } - } - - private int RemoveServiceInterval - { - get - { - if (_removeServiceInterval > 0) - { - return _removeServiceInterval; - } - - var interval = Global.Config["removeServiceInterval"]; - if (int.TryParse(interval, out int i)) - { - if (i <= 0) - { - _removeServiceInterval = 0; - } - else - { - _removeServiceInterval = i; - } - } - - return _removeServiceInterval; - } - } - - public Task StartCheckAsync() - { - _logger.LogInformation("start to service health check"); - - Task.Factory.StartNew(async () => - { - while (true) - { - //没有填写心跳模式,则不做检查 - var services = await serviceInfoRepository - .SearchFor(x => x.HeartBeatMode != null && x.HeartBeatMode != "").ToListAsync(); - foreach (var service in services) - { - if (service.HeartBeatMode == HeartBeatModes.none.ToString()) - { - continue; - } - - var lstHeartBeat = service.LastHeartBeat; - if (!lstHeartBeat.HasValue) - { - lstHeartBeat = service.RegisterTime ?? DateTime.MinValue; - } - - //service.HeartBeatMode 不为空 - if (!string.IsNullOrWhiteSpace(service.HeartBeatMode)) - { - if (RemoveServiceInterval > 0 && - (DateTime.Now - lstHeartBeat.Value).TotalSeconds > RemoveServiceInterval) - { - //超过设定时间,则直接删除服务 - await serviceInfoService.RemoveAsync(service.Id); - continue; - } - - //是客户端主动心跳,不做http健康检查 - if (service.HeartBeatMode == HeartBeatModes.client.ToString()) - { - if ((DateTime.Now - lstHeartBeat.Value).TotalSeconds > UnhealthInterval) - { - //客户端主动心跳模式:超过 UnhealthInterval 没有心跳,则认为服务不可用 - if (service.Status == ServiceStatus.Healthy) - { - await serviceInfoService.UpdateServiceStatus(service, ServiceStatus.Unhealthy); - } - } - - continue; - } - - //等于server 主动http健康检查 - if (service.HeartBeatMode == HeartBeatModes.server.ToString()) - { - if (string.IsNullOrWhiteSpace(service.CheckUrl)) - { - //CheckUrl不填,直接认为下线 - await serviceInfoService.UpdateServiceStatus(service, ServiceStatus.Unhealthy); - continue; - } - - _ = Task.Run(async () => - { - var result = await CheckAService(service); - await serviceInfoService.UpdateServiceStatus(service, - result ? ServiceStatus.Healthy : ServiceStatus.Unhealthy); - }); - } - } - } - - await Task.Delay(CheckInterval * 1000); - } - }, TaskCreationOptions.LongRunning); - - return Task.CompletedTask; - } - - private async Task CheckAService(ServiceInfo service) - { - try - { - using var resp = await restClient.GetAsync(service.CheckUrl); - - var result = false; - int istatus = ((int)resp.StatusCode - 200); - result = istatus >= 0 && istatus < 100; // 200 段都认为是正常的 - - _logger.LogInformation("check service health {0} {1} {2} result:{3}", service.CheckUrl, service.ServiceId, - service.ServiceName, result ? "up" : "down"); - return result; - } - catch (Exception e) - { - _logger.LogError(e, "check service health {0} {1} {2} error", service.CheckUrl, service.ServiceId, - service.ServiceName); - return false; - } - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/ServiceInfoService.cs b/src/AgileConfig.Server.Mongodb.Service/ServiceInfoService.cs deleted file mode 100644 index 4aa066d8..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/ServiceInfoService.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System.Dynamic; -using System.Text; -using AgileConfig.Server.Common; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Mongodb; -using AgileConfig.Server.IService; -using Microsoft.Extensions.Caching.Memory; -using MongoDB.Driver; -using MongoDB.Driver.Linq; -using Newtonsoft.Json; - -namespace AgileConfig.Server.Mongodb.Service; - -public class ServiceInfoService(IRepository repository, IMemoryCache? memoryCache) : IServiceInfoService -{ - public async Task GetByUniqueIdAsync(string id) - { - var entity = await repository.FindAsync(id); - return entity; - } - - public async Task GetByServiceIdAsync(string serviceId) - { - var entity = await repository.SearchFor(x => x.ServiceId == serviceId).FirstOrDefaultAsync(); - return entity; - } - - public async Task RemoveAsync(string id) - { - var result = await repository.DeleteAsync(id); - return result.DeletedCount > 0; - } - - public async Task> GetAllServiceInfoAsync() - { - var services = await repository.SearchFor(x => true).ToListAsync(); - - return services; - } - - public async Task> GetOnlineServiceInfoAsync() - { - var services = await repository.SearchFor(x => x.Status == ServiceStatus.Healthy) - .ToListAsync(); - - return services; - } - - public async Task> GetOfflineServiceInfoAsync() - { - var services = await repository.SearchFor(x => x.Status == ServiceStatus.Unhealthy) - .ToListAsync(); - - return services; - } - - public async Task ServicesMD5Cache() - { - var cacheKey = $"ServiceInfoService_ServicesMD5Cache"; - if (memoryCache != null && memoryCache.TryGetValue(cacheKey, out string? md5)) - { - return md5; - } - - md5 = await ServicesMD5(); - var cacheOp = new MemoryCacheEntryOptions() - .SetAbsoluteExpiration(TimeSpan.FromSeconds(60)); - memoryCache?.Set(cacheKey, md5, cacheOp); - - return md5; - } - - public async Task ServicesMD5() - { - var services = await GetAllServiceInfoAsync(); - var md5 = GenerateMD5(services); - - return md5; - } - - private string GenerateMD5(List services) - { - var sb = new StringBuilder(); - foreach (var serviceInfo in services.OrderBy(x => x.ServiceId, StringComparer.Ordinal)) - { - var metaDataStr = ""; - if (!string.IsNullOrEmpty(serviceInfo.MetaData)) - { - var metaData = JsonConvert.DeserializeObject>(serviceInfo.MetaData); - if (metaData != null) - { - metaDataStr = string.Join(",", metaData.OrderBy(x => x, StringComparer.Ordinal)); - } - } - - sb.Append( - $"{serviceInfo.ServiceId}&{serviceInfo.ServiceName}&{serviceInfo.Ip}&{serviceInfo.Port}&{(int)serviceInfo.Status}&{metaDataStr}&"); - } - - var txt = sb.ToString(); - return Encrypt.Md5(txt); - } - - public void ClearCache() - { - if (memoryCache is MemoryCache memCache) - { - memCache.Compact(1.0); - } - } - - public async Task UpdateServiceStatus(ServiceInfo service, ServiceStatus status) - { - var id = service.Id; - var oldStatus = service.Status; - - if (status == ServiceStatus.Unhealthy) - { - var update = Builders.Update.Set(x => x.Status, status); - await repository.UpdateAsync(x => x.Id == id, update); - } - else - { - var update = Builders.Update - .Set(x => x.Status, status) - .Set(x => x.LastHeartBeat,DateTime.Now); - await repository.UpdateAsync(x => x.Id == id, update); - } - - if (oldStatus != status) - { - ClearCache(); - dynamic param = new ExpandoObject(); - param.ServiceId = service.ServiceId; - param.ServiceName = service.ServiceName; - param.UniqueId = service.Id; - TinyEventBus.Instance.Fire(EventKeys.UPDATE_SERVICE_STATUS, param); - } - } - - public void Dispose() - { - GC.SuppressFinalize(this); - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/SettingService.cs b/src/AgileConfig.Server.Mongodb.Service/SettingService.cs deleted file mode 100644 index e9bf6bfe..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/SettingService.cs +++ /dev/null @@ -1,181 +0,0 @@ -using AgileConfig.Server.Common; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Mongodb; -using AgileConfig.Server.IService; -using MongoDB.Driver; -using MongoDB.Driver.Linq; - -namespace AgileConfig.Server.Mongodb.Service; - -public class SettingService( - IRepository repository, - IRepository userRepository, - IRepository userRoleRepository) : ISettingService -{ - public const string SuperAdminId = "super_admin"; - public const string SuperAdminUserName = "admin"; - - public const string DefaultEnvironment = "DEV,TEST,STAGING,PROD"; - public const string DefaultEnvironmentKey = "environment"; - public const string DefaultJwtSecretKey = "jwtsecret"; - - public async Task AddAsync(Setting setting) - { - await repository.InsertAsync(setting); - return true; - } - - public async Task DeleteAsync(Setting setting) - { - var result = await repository.DeleteAsync(setting.Id.ToString()); - return result.DeletedCount > 0; - } - - public async Task DeleteAsync(string settingId) - { - var result = await repository.DeleteAsync(settingId); - return result.DeletedCount > 0; - } - - public Task GetAsync(string id) - { - return repository.SearchFor(s => s.Id == id).FirstOrDefaultAsync(); - } - - public Task> GetAllSettingsAsync() - { - return repository.SearchFor(s => true).ToListAsync(); - } - - public async Task UpdateAsync(Setting setting) - { - var result = await repository.UpdateAsync(setting); - return result.ModifiedCount > 0; - } - - public async Task SetSuperAdminPassword(string password) - { - if (string.IsNullOrEmpty(password)) - { - throw new ArgumentNullException(nameof(password)); - } - - var newSalt = Guid.NewGuid().ToString("N"); - password = Encrypt.Md5((password + newSalt)); - - var su = new User(); - su.Id = SuperAdminId; - su.Password = password; - su.Salt = newSalt; - su.Status = UserStatus.Normal; - su.Team = ""; - su.CreateTime = DateTime.Now; - su.UserName = SuperAdminUserName; - await userRepository.InsertAsync(su); - - var ursa = new UserRole() - { - Id = Guid.NewGuid().ToString("N"), - Role = Role.SuperAdmin, - UserId = SuperAdminId - }; - - var ura = new UserRole() - { - Id = Guid.NewGuid().ToString("N"), - Role = Role.Admin, - UserId = SuperAdminId - }; - await userRoleRepository.InsertAsync(ursa, ura); - - return true; - } - - public async Task HasSuperAdmin() - { - var admin = await userRepository.SearchFor(x => x.Id == SuperAdminId).FirstOrDefaultAsync(); - - return admin != null; - } - - public async Task InitDefaultEnvironment() - { - var env = await repository.SearchFor(x => x.Id == DefaultEnvironmentKey).FirstOrDefaultAsync(); - if (env == null) - { - await repository.InsertAsync(new Setting - { - Id = DefaultEnvironmentKey, - Value = DefaultEnvironment, - CreateTime = DateTime.Now - }); - } - - return true; - } - - public void Dispose() - { - GC.SuppressFinalize(this); - } - - public async Task GetEnvironmentList() - { - var env = await repository.SearchFor(x => x.Id == DefaultEnvironmentKey).FirstAsync(); - - return env.Value.ToUpper().Split(','); - } - - /// - /// 如果 配置文件或者环境变量没配置 JwtSetting:SecurityKey 则生成一个存库 - /// - /// - public bool TryInitJwtSecret() - { - var jwtSecretFromConfig = Global.Config["JwtSetting:SecurityKey"]; - if (string.IsNullOrEmpty(jwtSecretFromConfig)) - { - var jwtSecretSetting = repository.Find(DefaultJwtSecretKey); - if (jwtSecretSetting == null) - { - try - { - repository.Insert(new Setting - { - Id = DefaultJwtSecretKey, - Value = GenreateJwtSecretKey(), - CreateTime = DateTime.Now - }); - return true; - } - catch (Exception e) - { - //处理异常,防止多个实例第一次启动的时候,并发生成key值,发生异常,导致服务起不来 - Console.WriteLine(e); - } - - return false; - } - } - - return true; - } - - public string? GetJwtTokenSecret() - { - var jwtSecretSetting = repository.Find(DefaultJwtSecretKey);; - return jwtSecretSetting?.Value; - } - - /// - /// 生成一个 jwt 加密的 key ,38位 - /// - /// - private string GenreateJwtSecretKey() - { - var guid1 = Guid.NewGuid().ToString("n"); - var guid2 = Guid.NewGuid().ToString("n"); - - return guid1.Substring(0, 19) + guid2.Substring(0, 19); - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/SysLogService.cs b/src/AgileConfig.Server.Mongodb.Service/SysLogService.cs deleted file mode 100644 index 3798930f..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/SysLogService.cs +++ /dev/null @@ -1,116 +0,0 @@ -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Mongodb; -using AgileConfig.Server.IService; -using MongoDB.Driver; -using MongoDB.Driver.Linq; - -namespace AgileConfig.Server.Mongodb.Service; - -public class SysLogService(IRepository repository) : ISysLogService -{ - public async Task AddRangeAsync(IEnumerable logs) - { - var insertLogs = logs.ToList(); - var newId = await GenerateIdAsync(); - foreach (var item in insertLogs) - { - item.Id = newId; - newId++; - } - await repository.InsertAsync(insertLogs); - return true; - } - - public async Task AddSysLogAsync(SysLog log) - { - if (log.Id <= 0) - { - log.Id = await GenerateIdAsync(); - } - await repository.InsertAsync(log); - return true; - } - - private async Task GenerateIdAsync() - { - var count = await repository.MongodbQueryable.CountAsync(); - if (count == 0) - { - return 1; - } - var log = await repository.MongodbQueryable.OrderByDescending(x => x.Id).FirstAsync(); - return log.Id + 1; - } - - public async Task Count(string appId, SysLogType? logType, DateTime? startTime, DateTime? endTime) - { - var query = repository.SearchFor(x => true); - if (!string.IsNullOrEmpty(appId)) - { - query = query.Where(x => x.AppId == appId); - } - - if (startTime.HasValue) - { - query = query.Where(x => x.LogTime >= startTime); - } - - if (endTime.HasValue) - { - query = query.Where(x => x.LogTime < endTime); - } - - if (logType.HasValue) - { - query = query.Where(x => x.LogType == logType); - } - - var count = await query.CountAsync(); - - return count; - } - - public void Dispose() - { - GC.SuppressFinalize(this); - } - - public Task> SearchPage(string appId, SysLogType? logType, DateTime? startTime, DateTime? endTime, - int pageSize, int pageIndex) - { - var query = repository.SearchFor(x => true); - if (!string.IsNullOrEmpty(appId)) - { - query = query.Where(x => x.AppId == appId); - } - - if (startTime.HasValue) - { - query = query.Where(x => x.LogTime >= startTime); - } - - if (endTime.HasValue) - { - query = query.Where(x => x.LogTime < endTime); - } - - if (logType.HasValue) - { - query = query.Where(x => x.LogType == logType); - } - - if (pageIndex <= 0) - { - pageIndex = 1; - } - - if (pageSize <= 0) - { - pageSize = 1; - } - - query = query.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize); - - return query.ToListAsync(); - } -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Mongodb.Service/UserService.cs b/src/AgileConfig.Server.Mongodb.Service/UserService.cs deleted file mode 100644 index eb2a5e18..00000000 --- a/src/AgileConfig.Server.Mongodb.Service/UserService.cs +++ /dev/null @@ -1,104 +0,0 @@ -using AgileConfig.Server.Common; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Mongodb; -using AgileConfig.Server.IService; -using MongoDB.Driver; -using MongoDB.Driver.Linq; - -namespace AgileConfig.Server.Mongodb.Service; - -public class UserService(IRepository repository, IRepository userRoleRepository) : IUserService -{ - public void Dispose() - { - GC.SuppressFinalize(this); - } - - public Task> GetAll() - { - return repository.SearchFor(x => true).ToListAsync(); - } - - public Task GetUserAsync(string userId) - { - return repository.FindAsync(userId); - } - - public User? GetUser(string userId) - { - return repository.Find(userId); - } - - public Task> GetUsersByNameAsync(string userName) - { - return repository.SearchFor(x => x.UserName == userName).ToListAsync(); - } - - public async Task> GetUserRolesAsync(string userId) - { - var userRoles = await userRoleRepository.SearchFor(x => x.UserId == userId).ToListAsync(); - return userRoles.Select(x => x.Role).ToList(); - } - - public async Task AddAsync(User user) - { - var old = repository.SearchFor(x => x.UserName == user.UserName && x.Status == UserStatus.Normal) - .FirstOrDefault(); - if (old != null) - return false; - - await repository.InsertAsync(user); - return true; - } - - public async Task DeleteAsync(User user) - { - var result = await repository.DeleteAsync(user.Id.ToString()); - return result.DeletedCount > 0; - } - - public async Task UpdateAsync(User user) - { - var result = await repository.UpdateAsync(user); - return result.ModifiedCount > 0; - } - - public async Task UpdateUserRolesAsync(string userId, List roles) - { - await userRoleRepository.DeleteAsync(x => x.UserId == userId); - var userRoles = roles.Select(x => new UserRole - { - Id = Guid.NewGuid().ToString("N"), - UserId = userId, - Role = x - }) - .ToList(); - - await userRoleRepository.InsertAsync(userRoles); - return true; - } - - public async Task ValidateUserPassword(string userName, string password) - { - var user = await repository.SearchFor(x => x.Status == UserStatus.Normal && x.UserName == userName) - .FirstOrDefaultAsync(); - if (user == null) - return false; - - if (user.Password == Encrypt.Md5(password + user.Salt)) - { - return true; - } - - return false; - } - - public Task> GetUsersByRoleAsync(Role role) - { - return (from user in repository.MongodbQueryable - join userRole in userRoleRepository.MongodbQueryable - on user.Id equals userRole.UserId - where userRole.Role == role - select user).ToListAsync(); - } -} \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/AgileConfig.Server.Mongodb.ServiceTest.csproj b/test/AgileConfig.Server.Mongodb.ServiceTest/AgileConfig.Server.Mongodb.ServiceTest.csproj deleted file mode 100644 index 357327f6..00000000 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/AgileConfig.Server.Mongodb.ServiceTest.csproj +++ /dev/null @@ -1,27 +0,0 @@ - - - - net8.0 - enable - enable - - false - true - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/AppServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/AppServiceTests.cs deleted file mode 100644 index 454370da..00000000 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/AppServiceTests.cs +++ /dev/null @@ -1,337 +0,0 @@ -namespace AgileConfig.Server.Mongodb.ServiceTest; - -[TestFixture] -public class AppServiceTests : DatabaseFixture -{ - private IAppService service; - - [SetUp] - public async Task TestInitialize() - { - service = new AppService(AppRepository, AppInheritancedRepository, ConfigRepository, ConfigPublishedRepository, - UserAppAuthRepository, UserRepository); - await AppRepository.DeleteAsync(x => true); - } - - [Test] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - var app = await AppRepository.FindAsync(id); - - Assert.IsTrue(result); - Assert.IsNotNull(app); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), app.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), app.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [Test] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var delResult = await service.DeleteAsync(source); - Assert.IsTrue(delResult); - - var app = await AppRepository.FindAsync(id); - Assert.IsNull(app); - } - - [Test] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var delResult = await service.DeleteAsync(id); - Assert.IsTrue(delResult); - - var app = await AppRepository.FindAsync(id); - Assert.IsNull(app); - } - - [Test] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var app = await service.GetAsync(id); - Assert.IsNotNull(app); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), app.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), app.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [Test] - public async Task GetAllAppsAsyncTest() - { - await AppRepository.DeleteAsync(x => true); - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Data.Entity.App - { - Id = id1, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var apps = await service.GetAllAppsAsync(); - Assert.IsNotNull(apps); - Assert.AreEqual(2, apps.Count); - } - - [Test] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.Name = "new name"; - source.Secret = "new sec"; - source.CreateTime = DateTime.Now.AddDays(1); - source.UpdateTime = DateTime.Now.AddDays(1); - source.Enabled = false; - - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result1); - - var app = await AppRepository.FindAsync(id); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), app.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), app.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [Test] - public async Task CountEnabledAppsAsyncTest() - { - await AppRepository.DeleteAsync(x => true); - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Data.Entity.App - { - Id = id1, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = false - }; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var count = await service.CountEnabledAppsAsync(); - Assert.AreEqual(1, count); - } - - [Test] - public async Task GetAllInheritancedAppsAsyncTest() - { - await AppRepository.DeleteAsync(x => true); - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source1 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source2 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - var source3 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = false, - Type = AppType.Inheritance - }; - var result = await service.AddAsync(source); - await service.AddAsync(source1); - await service.AddAsync(source2); - await service.AddAsync(source3); - - Assert.IsTrue(result); - - var apps = await service.GetAllInheritancedAppsAsync(); - - Assert.AreEqual(2, apps.Count); - } - - [Test] - public async Task GetInheritancedAppsAsyncTest() - { - await AppRepository.DeleteAsync(x => true); - await AppInheritancedRepository.DeleteAsync(x => true); - - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source1 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xx1", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - var source2 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xx2", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - // - var appInher = new AppInheritanced(); - appInher.Id = Guid.NewGuid().ToString(); - appInher.AppId = source.Id; - appInher.InheritancedAppId = source1.Id; - appInher.Sort = 1; - var appInher1 = new AppInheritanced(); - appInher1.Id = Guid.NewGuid().ToString(); - appInher1.AppId = source.Id; - appInher1.InheritancedAppId = source2.Id; - appInher1.Sort = 2; - - var result = await service.AddAsync(source); - await service.AddAsync(source1); - await service.AddAsync(source2); - - await AppInheritancedRepository.InsertAsync(appInher); - await AppInheritancedRepository.InsertAsync(appInher1); - - Assert.IsTrue(result); - - var apps = await service.GetInheritancedAppsAsync(source.Id); - - Assert.AreEqual(2, apps.Count); - } -} \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/ConfigServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/ConfigServiceTests.cs deleted file mode 100644 index 275d26af..00000000 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/ConfigServiceTests.cs +++ /dev/null @@ -1,835 +0,0 @@ -using Microsoft.Extensions.Caching.Memory; -using Microsoft.Extensions.Configuration; - -namespace AgileConfig.Server.Mongodb.ServiceTest; - -[TestFixture] -public class ConfigServiceTests : DatabaseFixture -{ - private IConfigService service; - - [SetUp] - public async Task TestInitialize() - { - var cache = new Mock(); - var configuration = new Mock(); - var appService = new AppService(AppRepository, AppInheritancedRepository, ConfigRepository, - ConfigPublishedRepository, - UserAppAuthRepository, UserRepository); - var settingService = new SettingService(SettingRepository, UserRepository, UserRoleRepository); - var userService = new UserService(UserRepository, UserRoleRepository); - service = new ConfigService(configuration.Object, cache.Object, appService, settingService, userService); - - await ConfigRepository.DeleteAsync(x => true); - } - - [Test] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var config = await ConfigRepository.FindAsync(id); - - Assert.IsTrue(result); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), config.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), config.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [Test] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - source.AppId = "1"; - source.Group = "1"; - source.Key = "1"; - source.Value = "1"; - source.Description = "1"; - source.CreateTime = DateTime.Now; - source.UpdateTime = DateTime.Now; - source.Status = ConfigStatus.Enabled; - source.OnlineStatus = OnlineStatus.WaitPublish; - - var result1 = await service.UpdateAsync(source, ""); - var config = await ConfigRepository.FindAsync(id); - - Assert.IsTrue(result1); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), config.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), config.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [Test] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source, ""); - Assert.IsTrue(result1); - - var config = await ConfigRepository.FindAsync(id); - - Assert.IsNull(config); - } - - [Test] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(id, ""); - Assert.IsTrue(result1); - - var config = await ConfigRepository.FindAsync(id); - - Assert.IsNull(config); - } - - [Test] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var config = await service.GetAsync(id, ""); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), config.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), config.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [Test] - public async Task GetAllConfigsAsyncTest() - { - await ConfigRepository.DeleteAsync(x => true); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - Env = "", - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - Env = "", - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - - var configs = await service.GetAllConfigsAsync(""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - } - - [Test] - public async Task GetByAppIdKeyTest() - { - await ConfigRepository.DeleteAsync(x => true); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - Env = "env", - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - Env = "env", - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - Env = "env", - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, "env"); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, "env"); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, "env"); - Assert.IsTrue(result2); - - var config = await service.GetByAppIdKeyEnv("001", "g", "k", "env"); - Assert.IsNotNull(config); - - var config1 = await service.GetByAppIdKeyEnv("002", "g", "k", "env"); - Assert.IsNull(config1); - } - - [Test] - public async Task GetByAppIdTest() - { - await ConfigRepository.DeleteAsync(x => true); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - Env = "", - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - Env = "", - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - Env = "", - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var configs = await service.GetByAppIdAsync("001", ""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - } - - [Test] - public async Task SearchTest() - { - await ConfigRepository.DeleteAsync(x => true); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var configs = await service.Search("001", "", "", ""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - var configs1 = await service.Search("", "o", "", ""); - Assert.IsNotNull(configs1); - Assert.AreEqual(1, configs1.Count); - var configs2 = await service.Search("", "", "e", ""); - Assert.IsNotNull(configs2); - Assert.AreEqual(1, configs2.Count); - } - - [Test] - public async Task CountEnabledConfigsAsyncTest() - { - await ConfigRepository.DeleteAsync(x => true); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var count = await service.CountEnabledConfigsAsync(); - Assert.AreEqual(1, count); - } - - [Test] - public async Task AppPublishedConfigsMd5Test() - { - await ConfigRepository.DeleteAsync(x => true); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var md5 = await service.AppPublishedConfigsMd5("001", ""); - Assert.IsNotNull(md5); - } - - [Test] - public void AppPublishedConfigsMd5CacheTest() - { - } - - [Test] - public async Task GetPublishedConfigsByAppIdTest() - { - await ConfigRepository.DeleteAsync(x => true); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - //var configs = await service.GetPublishedConfigsByAppId("001"); - //Assert.IsNotNull(configs); - //Assert.AreEqual(1, configs.Count); - } - - [Test] - public async Task AddRangeAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddRangeAsync(new List - { - source, - source1 - }, ""); - Assert.IsTrue(result); - - var config = await ConfigRepository.FindAsync(id); - Assert.IsNotNull(config); - var config1 = await ConfigRepository.FindAsync(id1); - Assert.IsNotNull(config1); - } - - [Test] - public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() - { - await AppRepository.DeleteAsync(x => true); - await ConfigRepository.DeleteAsync(x => true); - await AppInheritancedRepository.DeleteAsync(x => true); - - var app = new App(); - app.Id = "001"; - app.Name = "x"; - app.Enabled = true; - app.CreateTime = DateTime.Now; - app.UpdateTime = DateTime.Now; - app.Type = AppType.PRIVATE; - var app1 = new App(); - app1.Id = "002"; - app1.Name = "x"; - app1.Enabled = true; - app1.CreateTime = DateTime.Now; - app1.UpdateTime = DateTime.Now; - app.Type = AppType.Inheritance; - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Key = "k1", - Value = "v1", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source2 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k2", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source3 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k21", - Value = "v2", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var appref = new AppInheritanced(); - appref.AppId = app.Id; - appref.InheritancedAppId = app1.Id; - appref.Sort = 1; - appref.Id = Guid.NewGuid().ToString(); - - await AppRepository.InsertAsync(app, app1); - await ConfigRepository.InsertAsync(source, source1, source3); - await AppInheritancedRepository.InsertAsync(appref); - - var dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(4, dict.Keys.Count); - - Assert.IsTrue(dict.ContainsKey(source.Key)); - Assert.IsTrue(dict.ContainsKey(source1.Key)); - Assert.IsTrue(dict.ContainsKey(source2.Key)); - Assert.IsTrue(dict.ContainsKey(source3.Key)); - - Assert.IsTrue(dict[source.Key].Value == "v"); - Assert.IsTrue(dict[source1.Key].Value == "v1"); - Assert.IsTrue(dict[source2.Key].Value == "v"); - Assert.IsTrue(dict[source3.Key].Value == "v2"); - - var source4 = new Config - { - AppId = "001", - Id = Guid.NewGuid().ToString(), - Key = "k4", - Value = "v3", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source5 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k4", - Value = "v2", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - - await ConfigRepository.InsertAsync(source4, source5); - - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); - - var config1 = dict["k4"]; - Assert.AreEqual(source4.Value, config1.Value); - - var app2 = new App(); - app2.Id = "003"; - app2.Name = "x"; - app2.Enabled = true; - app2.CreateTime = DateTime.Now; - app2.UpdateTime = DateTime.Now; - app2.Type = AppType.Inheritance; - await AppRepository.InsertAsync(app2); - var source6 = new Config - { - AppId = "003", - Id = Guid.NewGuid().ToString(), - Key = "k2", - Value = "k4444", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - - await AppInheritancedRepository.DeleteAsync(x => true); - await ConfigRepository.InsertAsync(source6); - await AppInheritancedRepository.InsertAsync(appref); - - - var appref1 = new AppInheritanced(); - appref1.AppId = app.Id; - appref1.InheritancedAppId = app2.Id; - appref1.Sort = 2; - appref1.Id = Guid.NewGuid().ToString(); - await AppInheritancedRepository.InsertAsync(appref1); - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); - - config1 = dict["k2"]; - Assert.AreEqual(source6.Value, config1.Value); - } -} \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs deleted file mode 100644 index 5acd6ddd..00000000 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/DatabaseFixture.cs +++ /dev/null @@ -1,28 +0,0 @@ -namespace AgileConfig.Server.Mongodb.ServiceTest; - -public class DatabaseFixture -{ - private const string ConnectionString = "mongodb://localhost:27017,localhost:37017/AgileConfig"; - - protected IRepository AppRepository => new Repository(ConnectionString); - - protected IRepository AppInheritancedRepository => - new Repository(ConnectionString); - - protected IRepository ConfigRepository => new Repository(ConnectionString); - - protected IRepository ConfigPublishedRepository => - new Repository(ConnectionString); - - protected IRepository UserAppAuthRepository => new Repository(ConnectionString); - - protected IRepository UserRepository => new Repository(ConnectionString); - - protected IRepository SettingRepository => new Repository(ConnectionString); - - protected IRepository UserRoleRepository => new Repository(ConnectionString); - - protected IRepository ServerNodeRepository => new Repository(ConnectionString); - - protected IRepository SysLogRepository => new Repository(ConnectionString); -} \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/GlobalUsings.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/GlobalUsings.cs deleted file mode 100644 index 1bf22356..00000000 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/GlobalUsings.cs +++ /dev/null @@ -1,6 +0,0 @@ -global using Moq; -global using NUnit.Framework; -global using AgileConfig.Server.Data.Mongodb; -global using AgileConfig.Server.Data.Entity; -global using AgileConfig.Server.IService; -global using AgileConfig.Server.Mongodb.Service; \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/ServerNodeServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/ServerNodeServiceTests.cs deleted file mode 100644 index 25d05c00..00000000 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/ServerNodeServiceTests.cs +++ /dev/null @@ -1,163 +0,0 @@ -using MongoDB.Driver.Linq; - -namespace AgileConfig.Server.Mongodb.ServiceTest; - -public class ServerNodeServiceTests : DatabaseFixture -{ - private IServerNodeService service; - - [SetUp] - public async Task TestInitialize() - { - service = new ServerNodeService(ServerNodeRepository); - - await ServerNodeRepository.DeleteAsync(x => true); - - Console.WriteLine("TestInitialize"); - } - - [Test] - public async Task AddAsyncTest() - { - await ServerNodeRepository.DeleteAsync(x => true); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var node = await ServerNodeRepository.SearchFor(x => x.Id == "1").FirstOrDefaultAsync(); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } - - [Test] - public async Task DeleteAsyncTest() - { - await ServerNodeRepository.DeleteAsync(x => true); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source); - Assert.IsTrue(result1); - - var node = await ServerNodeRepository.SearchFor(x => x.Id == "1").FirstOrDefaultAsync(); - Assert.IsNull(node); - } - - [Test] - public async Task DeleteAsyncTest1() - { - await ServerNodeRepository.DeleteAsync(x => true); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source.Id); - Assert.IsTrue(result1); - - var node = await ServerNodeRepository.SearchFor(x => x.Id == "1").FirstOrDefaultAsync(); - Assert.IsNull(node); - } - - [Test] - public async Task GetAllNodesAsyncTest() - { - await ServerNodeRepository.DeleteAsync(x => true); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var nodes = await service.GetAllNodesAsync(); - Assert.IsNotNull(nodes); - - Assert.AreEqual(1, nodes.Count); - } - - [Test] - public async Task GetAsyncTest() - { - await ServerNodeRepository.DeleteAsync(x => true); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var node = await service.GetAsync(source.Id); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } - - [Test] - public async Task UpdateAsyncTest() - { - await ServerNodeRepository.DeleteAsync(x => true); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "3"; - source.Status = NodeStatus.Online; - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result); - - var node = await service.GetAsync(source.Id); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } -} \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/SettingServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/SettingServiceTests.cs deleted file mode 100644 index 1e54b755..00000000 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/SettingServiceTests.cs +++ /dev/null @@ -1,182 +0,0 @@ -namespace AgileConfig.Server.Mongodb.ServiceTest; - -public class SettingServiceTests : DatabaseFixture -{ - private ISettingService service; - - [SetUp] - public async Task TestInitialize() - { - service = new SettingService(SettingRepository, UserRepository, UserRoleRepository); - await SettingRepository.DeleteAsync(x => true); - Console.WriteLine("TestInitialize"); - } - - [Test] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var setting = await SettingRepository.FindAsync(id); - - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [Test] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - result = await service.DeleteAsync(source); - Assert.IsTrue(result); - - var setting = await SettingRepository.FindAsync(id); - - Assert.IsNull(setting); - } - - [Test] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - result = await service.DeleteAsync(id); - Assert.IsTrue(result); - - var setting = await SettingRepository.FindAsync(id); - - Assert.IsNull(setting); - } - - [Test] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var setting = await service.GetAsync(id); - - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [Test] - public async Task GetAllSettingsAsyncTest() - { - await SettingRepository.DeleteAsync(x => true); - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Setting(); - source1.Id = id1; - source1.Value = "123"; - source1.CreateTime = DateTime.Now; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var settings = await service.GetAllSettingsAsync(); - - Assert.IsNotNull(settings); - - Assert.AreEqual(2, settings.Count); - } - - [Test] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.CreateTime = DateTime.Now; - source.Value = "321"; - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result1); - - var setting = await service.GetAsync(id); - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [Test] - public async Task SetAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - //var list = fsq.Select().Where("1=1").ToList(); - //Assert.IsNotNull(list); - //Assert.AreEqual(2, list.Count); - - //var pass = list.FirstOrDefault(s => s.Id == service.SuperAdminPasswordSettingKey); - //Assert.IsNotNull(pass); - //var salt = list.FirstOrDefault(s => s.Id == service.AdminPasswordHashSaltKey); - //Assert.IsNotNull(salt); - } - - [Test] - public async Task HasAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - - //var has = await service.HasSuperAdminPassword(); - //Assert.IsTrue(has); - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //has = await service.HasSuperAdminPassword(); - //Assert.IsFalse(has); - } - - [Test] - public async Task ValidateAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - - //var v = await service.ValidateAdminPassword("123456"); - //Assert.IsTrue(v); - //v = await service.ValidateAdminPassword("1234561"); - //Assert.IsFalse(v); - } -} \ No newline at end of file diff --git a/test/AgileConfig.Server.Mongodb.ServiceTest/SysLogServiceTests.cs b/test/AgileConfig.Server.Mongodb.ServiceTest/SysLogServiceTests.cs deleted file mode 100644 index b9870878..00000000 --- a/test/AgileConfig.Server.Mongodb.ServiceTest/SysLogServiceTests.cs +++ /dev/null @@ -1,147 +0,0 @@ -namespace AgileConfig.Server.Mongodb.ServiceTest; - -public class SysLogServiceTests : DatabaseFixture -{ - private ISysLogService service; - - [SetUp] - public async Task TestInitialize() - { - service = new SysLogService(SysLogRepository); - await SysLogRepository.DeleteAsync(x => true); - Console.WriteLine("TestInitialize"); - } - - [Test] - public async Task AddSysLogAsyncTest() - { - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - - var result = await service.AddSysLogAsync(source); - Assert.IsTrue(result); - - var log = await SysLogRepository.FindAsync(source.Id); - - Assert.IsNotNull(log); - - Assert.AreEqual(source.Id, log.Id); - Assert.AreEqual(source.AppId, log.AppId); - Assert.AreEqual(source.LogType, log.LogType); - // Assert.AreEqual(source.LogTime, log.LogTime); - Assert.AreEqual(source.LogText, log.LogText); - } - - - [Test] - public async Task AddRangeAsyncTest() - { - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List - { - source, source1 - }); - Assert.IsTrue(result); - - var log = await SysLogRepository.FindAsync(source.Id); - Assert.IsNotNull(log); - Assert.AreEqual(source.Id, log.Id); - Assert.AreEqual(source.AppId, log.AppId); - Assert.AreEqual(source.LogType, log.LogType); - // Assert.AreEqual(source.LogTime, log.LogTime); - Assert.AreEqual(source.LogText, log.LogText); - - var log1 = await SysLogRepository.FindAsync(source1.Id); - Assert.IsNotNull(log1); - Assert.AreEqual(source1.Id, log1.Id); - Assert.AreEqual(source1.AppId, log1.AppId); - Assert.AreEqual(source1.LogType, log1.LogType); - // Assert.AreEqual(source1.LogTime, log1.LogTime); - Assert.AreEqual(source1.LogText, log1.LogText); - } - - - [Test] - public async Task CountTest() - { - await SysLogRepository.DeleteAsync(x => true); - - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List - { - source, source1 - }); - Assert.IsTrue(result); - - var count = await service.Count("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1)); - Assert.AreEqual(1, count); - - var count1 = await service.Count("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1)); - Assert.AreEqual(0, count1); - } - - [Test] - public async Task SearchPageTest() - { - await SysLogRepository.DeleteAsync(x => true); - - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List - { - source, source1 - }); - Assert.IsTrue(result); - - var page = await service.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1), - 1, 0); - Assert.AreEqual(1, page.Count); - - var page1 = await service.SearchPage("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), - 1, 0); - Assert.AreEqual(0, page1.Count); - } -} \ No newline at end of file From 5f193cebeb32ef082cf41cb0575189277adf7cf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Mon, 25 Dec 2023 15:33:02 +0800 Subject: [PATCH 15/45] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../MongodbRepositoryExt.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs index 8c4d37ea..9bf89958 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs @@ -16,6 +16,6 @@ public static void AddMongodbRepository(this IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddScoped(); - services.AddScoped(); + services.AddScoped(); } } \ No newline at end of file From cacf8f467e03fba9b0b5ff967ac30b3dae8eb8c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Mon, 25 Dec 2023 18:03:50 +0800 Subject: [PATCH 16/45] =?UTF-8?q?EventRegister=20=E6=B3=A8=E5=85=A5?= =?UTF-8?q?=E6=8A=BD=E8=B1=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../IRepository.cs | 2 +- .../ConfigStatusUpdateRegister.cs | 23 +++-- .../EventRegisterService/EventRegister.cs | 26 ++---- src/AgileConfig.Server.Service/JwtService.cs | 19 ++-- .../ServiceCollectionExt.cs | 22 ++++- .../SettingService.cs | 88 ++++++++++--------- .../PostgreSQL/SettingServiceTests.cs | 11 ++- .../mysql/SettingServiceTests.cs | 11 ++- .../oracle/SettingServiceTests.cs | 11 ++- .../sqlite/SettingServiceTests.cs | 11 ++- .../sqlserver/SettingServiceTests.cs | 13 ++- 11 files changed, 151 insertions(+), 86 deletions(-) diff --git a/src/AgileConfig.Server.Data.Abstraction/IRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IRepository.cs index a5fdf186..00ab8eac 100644 --- a/src/AgileConfig.Server.Data.Abstraction/IRepository.cs +++ b/src/AgileConfig.Server.Data.Abstraction/IRepository.cs @@ -6,7 +6,7 @@ namespace AgileConfig.Server.Data.Abstraction public interface IRepository : IDisposable where T : IEntity { Task> AllAsync(); - Task GetAsync(T1 id); + Task GetAsync(T1 id); Task UpdateAsync(T entity); Task UpdateAsync(IList entities); diff --git a/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs index a6ed8288..756767ff 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs @@ -12,16 +12,23 @@ namespace AgileConfig.Server.Service.EventRegisterService; internal class ConfigStatusUpdateRegister : IEventRegister { private readonly IRemoteServerNodeProxy _remoteServerNodeProxy; + private readonly EventRegisterTransient _serverNodeService; + private readonly EventRegisterTransient _appService; - public ConfigStatusUpdateRegister(IRemoteServerNodeProxy remoteServerNodeProxy) + public ConfigStatusUpdateRegister( + IRemoteServerNodeProxy remoteServerNodeProxy, + EventRegisterTransient serverNodeService, + EventRegisterTransient appService) { _remoteServerNodeProxy = remoteServerNodeProxy; + _serverNodeService = serverNodeService; + _appService = appService; } - private IServerNodeService NewServerNodeService() - { - return new ServerNodeService(new FreeSqlContext(FreeSQL.Instance)); - } + // private IServerNodeService NewServerNodeService() + // { + // return new ServerNodeService(new FreeSqlContext(FreeSQL.Instance)); + // } private IAppService NewAppService() { @@ -52,7 +59,7 @@ public void Register() { Task.Run(async () => { - using (var serverNodeService = NewServerNodeService()) + using (var serverNodeService = _serverNodeService()) { var nodes = await serverNodeService.GetAllNodesAsync(); var noticeApps = await GetNeedNoticeInheritancedFromAppsAction(timelineNode.AppId); @@ -99,7 +106,7 @@ await _remoteServerNodeProxy.AppClientsDoActionAsync( { Task.Run(async () => { - using (var serverNodeService = NewServerNodeService()) + using (var serverNodeService = _serverNodeService()) { var nodes = await serverNodeService.GetAllNodesAsync(); var noticeApps = await GetNeedNoticeInheritancedFromAppsAction(timelineNode.AppId); @@ -136,7 +143,7 @@ private async Task> GetNeedNoticeInheritance Dictionary needNoticeAppsActions = new Dictionary { }; - using (var appService = NewAppService()) + using (var appService = _appService()) { var currentApp = await appService.GetAsync(appId); if (currentApp.Type == AppType.Inheritance) diff --git a/src/AgileConfig.Server.Service/EventRegisterService/EventRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/EventRegister.cs index a99ed8be..77329ac7 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/EventRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/EventRegister.cs @@ -1,28 +1,18 @@ -using AgileConfig.Server.Common.RestClient; +#nullable enable using AgileConfig.Server.IService; -using Microsoft.Extensions.Logging; namespace AgileConfig.Server.Service.EventRegisterService; -public class EventRegister : IEventRegister +public class EventRegister(EventRegisterResolver eventRegisterResolver) : IEventRegister { - private readonly IRemoteServerNodeProxy _remoteServerNodeProxy; - private readonly ConfigStatusUpdateRegister _configStatusUpdateRegister; - private readonly SysLogRegister _sysLogRegister; - private readonly ServiceInfoStatusUpdateRegister _serviceInfoStatusUpdateRegister; - - public EventRegister(IRemoteServerNodeProxy remoteServerNodeProxy, ILoggerFactory loggerFactory, IRestClient restClient) - { - _remoteServerNodeProxy = remoteServerNodeProxy; - _configStatusUpdateRegister = new ConfigStatusUpdateRegister(_remoteServerNodeProxy); - _sysLogRegister = new SysLogRegister(); - _serviceInfoStatusUpdateRegister = new ServiceInfoStatusUpdateRegister(_remoteServerNodeProxy, loggerFactory, restClient); - } + private readonly IEventRegister? _configStatusUpdateRegister = eventRegisterResolver(nameof(ConfigStatusUpdateRegister)); + private readonly IEventRegister? _sysLogRegister = eventRegisterResolver(nameof(SysLogRegister)); + private readonly IEventRegister? _serviceInfoStatusUpdateRegister = eventRegisterResolver(nameof(ServiceInfoStatusUpdateRegister)); public void Register() { - _configStatusUpdateRegister.Register(); - _sysLogRegister.Register(); - _serviceInfoStatusUpdateRegister.Register(); + _configStatusUpdateRegister?.Register(); + _sysLogRegister?.Register(); + _serviceInfoStatusUpdateRegister?.Register(); } } \ No newline at end of file diff --git a/src/AgileConfig.Server.Service/JwtService.cs b/src/AgileConfig.Server.Service/JwtService.cs index 111307c9..b7ef38bb 100644 --- a/src/AgileConfig.Server.Service/JwtService.cs +++ b/src/AgileConfig.Server.Service/JwtService.cs @@ -14,12 +14,19 @@ namespace AgileConfig.Server.Service; /// public class JwtService : IJwtService { - static JwtService() + private readonly ISettingService _settingService; + // static JwtService() + // { + // // 则尝试生成一个key到数据库 + // using var settingService = new SettingService(new FreeSqlContext(FreeSQL.Instance)); + // settingService.TryInitJwtSecret(); + // } + + public JwtService(ISettingService settingService) { - // 则尝试生成一个key到数据库 - using var settingService = new SettingService(new FreeSqlContext(FreeSQL.Instance)); - settingService.TryInitJwtSecret(); + _settingService = settingService; } + public string Issuer => Global.Config["JwtSetting:Issuer"]; public string Audience => Global.Config["JwtSetting:Audience"]; public int ExpireSeconds => int.Parse(Global.Config["JwtSetting:ExpireSeconds"]); @@ -38,8 +45,8 @@ public string GetSecurityKey() return _secretKey; } - using var settingService = new SettingService(new FreeSqlContext(FreeSQL.Instance)); - _secretKey = settingService.GetJwtTokenSecret(); + //using var settingService = new SettingService(new FreeSqlContext(FreeSQL.Instance)); + _secretKey = _settingService.GetJwtTokenSecret(); if (string.IsNullOrEmpty(_secretKey)) { diff --git a/src/AgileConfig.Server.Service/ServiceCollectionExt.cs b/src/AgileConfig.Server.Service/ServiceCollectionExt.cs index 66490646..216c6ee4 100644 --- a/src/AgileConfig.Server.Service/ServiceCollectionExt.cs +++ b/src/AgileConfig.Server.Service/ServiceCollectionExt.cs @@ -1,10 +1,15 @@ -using AgileConfig.Server.Common.RestClient; +#nullable enable +using AgileConfig.Server.Common.RestClient; using AgileConfig.Server.IService; using AgileConfig.Server.Service.EventRegisterService; using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service { + public delegate T? EventRegisterTransient(); + + public delegate IEventRegister? EventRegisterResolver(string key); + public static class ServiceCollectionExt { public static void AddBusinessServices(this IServiceCollection sc) @@ -26,6 +31,21 @@ public static void AddBusinessServices(this IServiceCollection sc) sc.AddScoped(); sc.AddScoped(); sc.AddScoped(); + + sc.AddScoped(x => key => + { + return key switch + { + nameof(ConfigStatusUpdateRegister) => x.GetService(), + nameof(ServiceInfoStatusUpdateRegister) => x.GetService(), + nameof(SysLogRegister) => x.GetService(), + _ => null + }; + }); + + sc.AddTransient,EventRegisterTransient>(); + sc.AddTransient,EventRegisterTransient>(); + sc.AddTransient,EventRegisterTransient>(); } } } diff --git a/src/AgileConfig.Server.Service/SettingService.cs b/src/AgileConfig.Server.Service/SettingService.cs index 8a13cd85..89812a60 100644 --- a/src/AgileConfig.Server.Service/SettingService.cs +++ b/src/AgileConfig.Server.Service/SettingService.cs @@ -4,13 +4,16 @@ using System.Collections.Generic; using System.Threading.Tasks; using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Freesql; namespace AgileConfig.Server.Service { public class SettingService : ISettingService { - private FreeSqlContext _dbContext; + private readonly ISettingRepository _settingRepository; + private readonly IUserRepository _userRepository; + private readonly IUserRoleRepository _userRoleRepository; public const string SuperAdminId = "super_admin"; public const string SuperAdminUserName = "admin"; @@ -19,56 +22,56 @@ public class SettingService : ISettingService public const string DefaultEnvironmentKey = "environment"; public const string DefaultJwtSecretKey = "jwtsecret"; - public SettingService(FreeSqlContext context) + public SettingService( + ISettingRepository settingRepository, + IUserRepository userRepository, + IUserRoleRepository userRoleRepository) { - _dbContext = context; + _settingRepository = settingRepository; + _userRepository = userRepository; + _userRoleRepository = userRoleRepository; } public async Task AddAsync(Setting setting) { - await _dbContext.Settings.AddAsync(setting); - int x = await _dbContext.SaveChangesAsync(); - return x > 0; + await _settingRepository.InsertAsync(setting); + return true; } public async Task DeleteAsync(Setting setting) { - setting = await _dbContext.Settings.Where(s => s.Id == setting.Id).ToOneAsync(); - if (setting != null) + var setting2 = await _settingRepository.GetAsync(setting.Id); + if (setting2 != null) { - _dbContext.Settings.Remove(setting); + await _settingRepository.DeleteAsync(setting); } - int x = await _dbContext.SaveChangesAsync(); - return x > 0; + return true; } public async Task DeleteAsync(string settingId) { - var setting = await _dbContext.Settings.Where(s => s.Id == settingId).ToOneAsync(); + var setting = await _settingRepository.GetAsync(settingId); if (setting != null) { - _dbContext.Settings.Remove(setting); + await _settingRepository.DeleteAsync(setting); } - int x = await _dbContext.SaveChangesAsync(); - return x > 0; + return true; } public async Task GetAsync(string id) { - return await _dbContext.Settings.Where(s => s.Id == id).ToOneAsync(); + return await _settingRepository.GetAsync(id); } public async Task> GetAllSettingsAsync() { - return await _dbContext.Settings.Where(s => 1 == 1).ToListAsync(); + return await _settingRepository.AllAsync(); } public async Task UpdateAsync(Setting setting) { - _dbContext.Update(setting); - var x = await _dbContext.SaveChangesAsync(); - - return x > 0; + await _settingRepository.UpdateAsync(setting); + return true; } public async Task SetSuperAdminPassword(string password) @@ -89,49 +92,50 @@ public async Task SetSuperAdminPassword(string password) su.Team = ""; su.CreateTime = DateTime.Now; su.UserName = SuperAdminUserName; - _dbContext.Users.Add(su); + await _userRepository.InsertAsync(su); + var userRoles = new List(); var ursa = new UserRole() { Id = Guid.NewGuid().ToString("N"), Role = Role.SuperAdmin, UserId = SuperAdminId }; - _dbContext.UserRoles.Add(ursa); + userRoles.Add(ursa); var ura = new UserRole() { Id = Guid.NewGuid().ToString("N"), Role = Role.Admin, UserId = SuperAdminId }; - _dbContext.UserRoles.Add(ura); + userRoles.Add(ura); - var result = await _dbContext.SaveChangesAsync(); + await _userRoleRepository.InsertAsync(userRoles); - return result > 0; + return true; } public async Task HasSuperAdmin() { - var admin = await _dbContext.Users.Where(x => x.Id == SuperAdminId).FirstAsync(); + var admin = await _userRepository.GetAsync(SuperAdminId); return admin != null; } public async Task InitDefaultEnvironment() { - var env = await _dbContext.Settings.Where(x => x.Id == DefaultEnvironmentKey).FirstAsync(); + var env = await _settingRepository.GetAsync(DefaultEnvironmentKey); if (env == null) { - _dbContext.Settings.Add(new Setting + var setting = new Setting { Id = DefaultEnvironmentKey, Value = DefaultEnvironment, CreateTime = DateTime.Now - }); - var result = await _dbContext.SaveChangesAsync(); + }; + await _settingRepository.InsertAsync(setting); - return result > 0; + return true; } return true; @@ -139,14 +143,16 @@ public async Task InitDefaultEnvironment() public void Dispose() { - _dbContext.Dispose(); + _settingRepository.Dispose(); + _userRepository.Dispose(); + _userRoleRepository.Dispose(); } public async Task GetEnvironmentList() { - var env = await _dbContext.Settings.Where(x => x.Id == DefaultEnvironmentKey).FirstAsync(); + var env = await _settingRepository.GetAsync(DefaultEnvironmentKey); - return env.Value.ToUpper().Split(','); + return env?.Value?.ToUpper().Split(',') ?? []; } /// @@ -158,20 +164,20 @@ public bool TryInitJwtSecret() var jwtSecretFromConfig = Global.Config["JwtSetting:SecurityKey"]; if (string.IsNullOrEmpty(jwtSecretFromConfig)) { - var jwtSecretSetting = _dbContext.Settings.Where(x => x.Id == DefaultJwtSecretKey).First(); + var jwtSecretSetting = _settingRepository.GetAsync(DefaultEnvironmentKey).Result; if (jwtSecretSetting == null) { - _dbContext.Settings.Add(new Setting + var setting = new Setting { Id = DefaultJwtSecretKey, Value = GenreateJwtSecretKey(), CreateTime = DateTime.Now - }); + }; try { - var result = _dbContext.SaveChanges(); - return result > 0; + _ = _settingRepository.InsertAsync(setting).Result; + return true; } catch (Exception e) { @@ -187,7 +193,7 @@ public bool TryInitJwtSecret() public string GetJwtTokenSecret() { - var jwtSecretSetting = _dbContext.Settings.Where(x => x.Id == DefaultJwtSecretKey).First(); + var jwtSecretSetting = _settingRepository.GetAsync(DefaultEnvironmentKey).Result; return jwtSecretSetting?.Value; } diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/SettingServiceTests.cs index 6277b3de..f67f0390 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/SettingServiceTests.cs @@ -8,6 +8,8 @@ using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; using System.Linq; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.PostgreSQL { @@ -16,7 +18,7 @@ public class SettingServiceTests { IFreeSql fsq = null; FreeSqlContext freeSqlContext; - SettingService service = null; + ISettingService service = null; [TestInitialize] public void TestInitialize() @@ -29,7 +31,12 @@ public void TestInitialize() FluentApi.Config(fsq); freeSqlContext = new FreeSqlContext(fsq); - service = new SettingService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs index 4156bc65..1886f35f 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs @@ -8,6 +8,8 @@ using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; using System.Linq; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.mysql { @@ -16,7 +18,7 @@ public class SettingServiceTests { IFreeSql fsq = null; FreeSqlContext freeSqlContext; - SettingService service = null; + ISettingService service = null; [TestInitialize] public void TestInitialize() @@ -28,7 +30,12 @@ public void TestInitialize() .Build(); freeSqlContext = new FreeSqlContext(fsq); - service = new SettingService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/oracle/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/SettingServiceTests.cs index 011c5ef3..d2669e00 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/SettingServiceTests.cs @@ -8,6 +8,8 @@ using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; using System.Linq; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.oracle { @@ -16,7 +18,7 @@ public class SettingServiceTests { IFreeSql fsq = null; FreeSqlContext freeSqlContext; - SettingService service = null; + ISettingService service = null; [TestInitialize] public void TestInitialize() @@ -29,7 +31,12 @@ public void TestInitialize() FluentApi.Config(fsq); freeSqlContext = new FreeSqlContext(fsq); - service = new SettingService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/SettingServiceTests.cs index 27cf51c0..d96db45e 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/SettingServiceTests.cs @@ -8,6 +8,8 @@ using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; using System.Linq; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests { @@ -16,7 +18,7 @@ public class SettingServiceTests { IFreeSql fsq = null; FreeSqlContext freeSqlContext; - SettingService service = null; + ISettingService service = null; [TestInitialize] public void TestInitialize() @@ -28,7 +30,12 @@ public void TestInitialize() .Build(); freeSqlContext = new FreeSqlContext(fsq); - service = new SettingService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/SettingServiceTests.cs index ffe2cf19..06e727d1 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/SettingServiceTests.cs @@ -8,6 +8,8 @@ using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; using System.Linq; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.sqlserver { @@ -16,7 +18,7 @@ public class SettingServiceTests { IFreeSql fsq = null; FreeSqlContext freeSqlContext; - SettingService service = null; + ISettingService service = null; [TestInitialize] public void TestInitialize() @@ -28,8 +30,13 @@ public void TestInitialize() .Build(); FluentApi.Config(fsq); freeSqlContext = new FreeSqlContext(fsq); - - service = new SettingService(freeSqlContext); + + IServiceCollection services = new ServiceCollection(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); From b50d583325cfacacacc52d3f84071489624daeef Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Tue, 26 Dec 2023 00:37:51 +0800 Subject: [PATCH 17/45] =?UTF-8?q?=E5=AF=B9=20IFreeSqlFactory=20=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E6=B7=BB=E5=8A=A0=20DeaultFreesqlFactory=20=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/AgileConfig.Server.Common/EnvAccessor.cs | 4 ---- .../DefaultFreeSqlFactory.cs | 10 ++++++++++ .../EnvFreeSqlFactory.cs | 2 +- src/AgileConfig.Server.Data.Freesql/FreeSQL.cs | 2 +- .../FreeSqlDbContextFactory.cs | 2 +- .../ServiceCollectionExt.cs | 3 ++- .../AppInheritancedRepository.cs | 3 ++- .../AppRepository.cs | 3 ++- .../ConfigPublishedRepository.cs | 3 ++- .../ConfigRepository.cs | 3 ++- .../PublishDetailRepository.cs | 3 ++- .../PublishTimelineRepository.cs | 3 ++- .../ServerNodeRepository.cs | 3 ++- .../ServiceInfoRepository.cs | 3 ++- .../SettingRepository.cs | 3 ++- .../SysLogRepository.cs | 3 ++- .../UserAppAuthRepository.cs | 3 ++- .../UserRepository.cs | 3 ++- .../UserRoleRepository.cs | 3 ++- 19 files changed, 41 insertions(+), 21 deletions(-) create mode 100644 src/AgileConfig.Server.Data.Freesql/DefaultFreeSqlFactory.cs diff --git a/src/AgileConfig.Server.Common/EnvAccessor.cs b/src/AgileConfig.Server.Common/EnvAccessor.cs index 99d4bfb6..68da74bb 100644 --- a/src/AgileConfig.Server.Common/EnvAccessor.cs +++ b/src/AgileConfig.Server.Common/EnvAccessor.cs @@ -21,10 +21,6 @@ public string Env get { var env = _httpContextAccessor.HttpContext.Request.Query["env"].FirstOrDefault(); - if (string.IsNullOrEmpty(env)) - { - env = "DEV"; - } return env; } } diff --git a/src/AgileConfig.Server.Data.Freesql/DefaultFreeSqlFactory.cs b/src/AgileConfig.Server.Data.Freesql/DefaultFreeSqlFactory.cs new file mode 100644 index 00000000..56450f79 --- /dev/null +++ b/src/AgileConfig.Server.Data.Freesql/DefaultFreeSqlFactory.cs @@ -0,0 +1,10 @@ +namespace AgileConfig.Server.Data.Freesql +{ + public class DefaultFreeSqlFactory : IFreeSqlFactory + { + public IFreeSql Create() + { + return FreeSQL.Instance; + } + } +} diff --git a/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs b/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs index da07a6cb..78c5f80d 100644 --- a/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs +++ b/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs @@ -11,7 +11,7 @@ public EnvFreeSqlFactory(IEnvAccessor envAccessor) } public IFreeSql Create() { - return FreeSQL.GetInstance(_envAccessor.Env); + return FreeSQL.GetInstanceByEnv(_envAccessor.Env); } } } diff --git a/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs b/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs index aa4d8d27..c7f42a07 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs @@ -27,7 +27,7 @@ static FreeSQL() /// /// /// - public static IFreeSql GetInstance(string env) + public static IFreeSql GetInstanceByEnv(string env) { if (string.IsNullOrEmpty(env)) { diff --git a/src/AgileConfig.Server.Data.Freesql/FreeSqlDbContextFactory.cs b/src/AgileConfig.Server.Data.Freesql/FreeSqlDbContextFactory.cs index 88ea5638..5f65f488 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreeSqlDbContextFactory.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreeSqlDbContextFactory.cs @@ -29,7 +29,7 @@ public static FreeSqlContext Create(string env) } Console.WriteLine("create env:{env} freesql dbcontext instance ."); - return new FreeSqlContext(FreeSQL.GetInstance(env)); + return new FreeSqlContext(FreeSQL.GetInstanceByEnv(env)); } } } diff --git a/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs b/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs index c56e0461..fe2e4171 100644 --- a/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs +++ b/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs @@ -9,7 +9,8 @@ public static class ServiceCollectionExt { public static void AddFreeSqlFactory(this IServiceCollection sc) { - sc.AddSingleton(); + sc.AddKeyedSingleton(""); + sc.AddKeyedSingleton("Env"); } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs index ddc43eb9..069ab2f2 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class AppInheritancedRepository : FreesqlRepository, IAppInheritancedRepository { - public AppInheritancedRepository(IFreeSqlFactory freeSql) : base(freeSql) + public AppInheritancedRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs index b25ae228..5ffe46ed 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class AppRepository : FreesqlRepository, IAppRepository { - public AppRepository(IFreeSqlFactory freeSql) : base(freeSql) + public AppRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs index a24f19a2..d2c00f49 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class ConfigPublishedRepository : FreesqlRepository, IConfigPublishedRepository { - public ConfigPublishedRepository(IFreeSqlFactory freeSql) : base(freeSql) + public ConfigPublishedRepository([FromKeyedServices("Env")] IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs index 876a2410..267c2d9d 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class ConfigRepository : FreesqlRepository, IConfigRepository { - public ConfigRepository(IFreeSqlFactory freeSql) : base(freeSql) + public ConfigRepository([FromKeyedServices("Env")]IFreeSqlFactory freeSqlFactory) : base(freeSqlFactory) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs index bace3a36..57e3b442 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class PublishDetailRepository : FreesqlRepository, IPublishDetailRepository { - public PublishDetailRepository(IFreeSqlFactory freeSql) : base(freeSql) + public PublishDetailRepository([FromKeyedServices("Env")] IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs index 55660104..b0a2bc2d 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class PublishTimelineRepository : FreesqlRepository, IPublishTimelineRepository { - public PublishTimelineRepository(IFreeSqlFactory freeSql) : base(freeSql) + public PublishTimelineRepository([FromKeyedServices("Env")] IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs index c7c0892a..f07940d9 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class ServerNodeRepository : FreesqlRepository, IServerNodeRepository { - public ServerNodeRepository(IFreeSqlFactory freeSql) : base(freeSql) + public ServerNodeRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs index 57175349..9a09b1b9 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class ServiceInfoRepository : FreesqlRepository, IServiceInfoRepository { - public ServiceInfoRepository(IFreeSqlFactory freeSql) : base(freeSql) + public ServiceInfoRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs index 9d9b6732..b91258cc 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class SettingRepository : FreesqlRepository, ISettingRepository { - public SettingRepository(IFreeSqlFactory freeSql) : base(freeSql) + public SettingRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs index 0be250ec..6558e795 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class SysLogRepository : FreesqlRepository, ISysLogRepository { - public SysLogRepository(IFreeSqlFactory freeSql) : base(freeSql) + public SysLogRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs index 286f93eb..6cf743f9 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class UserAppAuthRepository : FreesqlRepository, IUserAppAuthRepository { - public UserAppAuthRepository(IFreeSqlFactory freeSql) : base(freeSql) + public UserAppAuthRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs index 466b1733..9f70b34f 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class UserRepository : FreesqlRepository, IUserRepository { - public UserRepository(IFreeSqlFactory freeSql) : base(freeSql) + public UserRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) { } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs index 8466ae44..447a11fa 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs @@ -1,12 +1,13 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class UserRoleRepository : FreesqlRepository, IUserRoleRepository { - public UserRoleRepository(IFreeSqlFactory freeSql) : base(freeSql) + public UserRoleRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) { } } From a016c48960de5fdcee139fbf28235fc9348d1a8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Tue, 26 Dec 2023 19:23:22 +0800 Subject: [PATCH 18/45] =?UTF-8?q?Service=20=E5=AE=9E=E7=8E=B0=E5=B1=82?= =?UTF-8?q?=E7=A7=BB=E9=99=A4=20FreeSql=20=E7=9A=84=E4=BE=9D=E8=B5=96?= =?UTF-8?q?=EF=BC=8C=E5=90=8C=E6=97=B6=E9=80=82=E9=85=8D=E6=96=B0=E7=9A=84?= =?UTF-8?q?=20Repository=20=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../IRepository.cs | 7 ++ .../FreesqlRepository.cs | 44 ++++++++++ .../MongodbRepository.cs | 45 ++++++++++ .../IUserService.cs | 1 - .../AgileConfig.Server.Service.csproj | 7 +- .../ConfigService.cs | 2 +- .../ConfigStatusUpdateRegister.cs | 25 ------ .../ServiceInfoStatusUpdateRegister.cs | 28 +++--- .../EventRegisterService/SysLogRegister.cs | 57 ++++++------ src/AgileConfig.Server.Service/JwtService.cs | 1 - .../PremissionService.cs | 25 ++++-- .../RegisterCenterService.cs | 31 +++---- .../RemoteServerNodeProxy.cs | 46 ++++++---- .../ServerNodeService.cs | 88 +++++++------------ .../ServiceCollectionExt.cs | 5 ++ .../ServiceHealthCheckService.cs | 11 ++- .../ServiceInfoService.cs | 45 ++++------ .../SettingService.cs | 1 - .../SysLogService.cs | 69 ++++++++++----- src/AgileConfig.Server.Service/UserService.cs | 66 ++++++-------- .../AgileConfig.Server.ServiceTests.csproj | 1 + .../PostgreSQL/ServerNodeServiceTests.cs | 14 ++- .../PostgreSQL/SysLogServiceTests.cs | 14 ++- .../mysql/ServerNodeServiceTests.cs | 14 ++- .../mysql/SysLogServiceTests.cs | 14 ++- .../oracle/ServerNodeServiceTests.cs | 14 ++- .../oracle/SysLogServiceTests.cs | 14 ++- .../sqlite/ServerNodeServiceTests.cs | 14 ++- .../sqlite/SysLogServiceTests.cs | 14 ++- .../sqlserver/ServerNodeServiceTests.cs | 16 +++- .../sqlserver/SysLogServiceTests.cs | 14 ++- 31 files changed, 461 insertions(+), 286 deletions(-) diff --git a/src/AgileConfig.Server.Data.Abstraction/IRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IRepository.cs index 00ab8eac..062393d4 100644 --- a/src/AgileConfig.Server.Data.Abstraction/IRepository.cs +++ b/src/AgileConfig.Server.Data.Abstraction/IRepository.cs @@ -11,6 +11,8 @@ public interface IRepository : IDisposable where T : IEntity Task UpdateAsync(T entity); Task UpdateAsync(IList entities); + Task DeleteAsync(T1 id); + Task DeleteAsync(T entity); Task DeleteAsync(IList entities); @@ -20,5 +22,10 @@ public interface IRepository : IDisposable where T : IEntity Task InsertAsync(IList entities); Task> QueryAsync(Expression> exp); + + Task> QueryPageAsync(Expression> exp, int pageIndex, int pageSize, + string defaultSortField = "Id", string defaultSortType = "ASC"); + + Task CountAsync(Expression>? exp = null); } } diff --git a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs index 5ddb651a..c6e93d84 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs @@ -22,6 +22,11 @@ public Task> AllAsync() return _repository.Select.ToListAsync(); } + public async Task DeleteAsync(T1 id) + { + await _repository.DeleteAsync(x => Equals(x.Id, id)); + } + public Task DeleteAsync(T entity) { return _repository.DeleteAsync(entity); @@ -52,6 +57,45 @@ public Task> QueryAsync(Expression> exp) return _repository.Where(exp).ToListAsync(); } + public async Task> QueryPageAsync(Expression> exp, int pageIndex, int pageSize, string defaultSortField = "Id", + string defaultSortType = "ASC") + { + var query = _repository.Where(exp); + var sort = Sort(defaultSortField); + if (string.Equals(defaultSortField, "DESC", StringComparison.OrdinalIgnoreCase)) + { + query.OrderByDescending(sort); + } + else + { + query.OrderBy(sort); + } + return await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); + } + + private Expression> Sort(string defaultSortField) + { + Expression> defaultSort = x => x.Id; + if (!string.IsNullOrEmpty(defaultSortField) && + !defaultSortField.Equals("Id", StringComparison.OrdinalIgnoreCase)) + { + var property = typeof(T).GetProperty(defaultSortField); + if (property == null) + { + return defaultSort; + } + var parameter = Expression.Parameter(typeof(T), "__q"); + var memberExpress = Expression.Property(parameter, property); + return Expression.Lambda>(memberExpress, parameter); + } + return defaultSort; + } + + public async Task CountAsync(Expression> exp = null) + { + return await (exp == null ? _repository.Select.CountAsync() : _repository.Select.Where(exp).CountAsync()); + } + public Task UpdateAsync(T entity) { return _repository.UpdateAsync(entity); diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs index d05a1be3..39a796a3 100644 --- a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs @@ -60,6 +60,12 @@ public async Task UpdateAsync(IList entities) await _access.Collection.BulkWriteAsync(writes); } + public async Task DeleteAsync(TId id) + { + var filter = Builders.Filter.Eq(x => x.Id, id); + await _access.Collection.DeleteOneAsync(filter); + } + public async Task DeleteAsync(TEntity entity) { var filter = GetIdPropertyFilter(entity.Id); @@ -88,4 +94,43 @@ public async Task> QueryAsync(Expression> exp) { return await _access.MongoQueryable.Where(exp).ToListAsync(); } + + public async Task> QueryPageAsync(Expression> exp, int pageIndex, int pageSize, string defaultSortField = "Id", + string defaultSortType = "ASC") + { + var query = _access.MongoQueryable.Where(exp); + var sort = Sort(defaultSortField); + if (string.Equals(defaultSortField, "DESC", StringComparison.OrdinalIgnoreCase)) + { + query.OrderByDescending(sort); + } + else + { + query.OrderBy(sort); + } + return await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); + } + + private Expression> Sort(string defaultSortField) + { + Expression> defaultSort = x => x.Id; + if (!string.IsNullOrEmpty(defaultSortField) && + !defaultSortField.Equals("Id", StringComparison.OrdinalIgnoreCase)) + { + var property = typeof(TEntity).GetProperty(defaultSortField); + if (property == null) + { + return defaultSort; + } + var parameter = Expression.Parameter(typeof(TEntity), "__q"); + var memberExpress = Expression.Property(parameter, property); + return Expression.Lambda>(memberExpress, parameter); + } + return defaultSort; + } + + public async Task CountAsync(Expression>? exp = null) + { + return await (exp == null ? _access.MongoQueryable.CountAsync() : _access.MongoQueryable.Where(exp).CountAsync()); + } } \ No newline at end of file diff --git a/src/AgileConfig.Server.IService/IUserService.cs b/src/AgileConfig.Server.IService/IUserService.cs index 50d84710..9bc566fb 100644 --- a/src/AgileConfig.Server.IService/IUserService.cs +++ b/src/AgileConfig.Server.IService/IUserService.cs @@ -10,7 +10,6 @@ public interface IUserService: IDisposable { Task> GetAll(); Task GetUserAsync(string userId); - User GetUser(string userId); Task> GetUsersByNameAsync(string userName); Task> GetUserRolesAsync(string userId); diff --git a/src/AgileConfig.Server.Service/AgileConfig.Server.Service.csproj b/src/AgileConfig.Server.Service/AgileConfig.Server.Service.csproj index ea67d43a..98b830c9 100644 --- a/src/AgileConfig.Server.Service/AgileConfig.Server.Service.csproj +++ b/src/AgileConfig.Server.Service/AgileConfig.Server.Service.csproj @@ -4,9 +4,14 @@ net8.0 + + + + + - + diff --git a/src/AgileConfig.Server.Service/ConfigService.cs b/src/AgileConfig.Server.Service/ConfigService.cs index ce0740b8..1f6db9ec 100644 --- a/src/AgileConfig.Server.Service/ConfigService.cs +++ b/src/AgileConfig.Server.Service/ConfigService.cs @@ -468,7 +468,7 @@ public void Dispose() //这里默认admin console 实例只部署一个,如果部署多个同步操作,高并发的时候这个version会有问题 var versionMax = (await _publishTimelineRepository.QueryAsync(x => x.AppId == appId)).Max(x => x.Version); - var user = _userService.GetUser(operatorr); + var user = await _userService.GetUserAsync(operatorr); var publishTimelineNode = new PublishTimeline(); publishTimelineNode.AppId = appId; diff --git a/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs index 756767ff..0efe9122 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs @@ -4,7 +4,6 @@ using Agile.Config.Protocol; using AgileConfig.Server.Common; using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.IService; namespace AgileConfig.Server.Service.EventRegisterService; @@ -25,30 +24,6 @@ public ConfigStatusUpdateRegister( _appService = appService; } - // private IServerNodeService NewServerNodeService() - // { - // return new ServerNodeService(new FreeSqlContext(FreeSQL.Instance)); - // } - - private IAppService NewAppService() - { - // todo - - throw new NotImplementedException(); - - //return new AppService(new FreeSqlContext(FreeSQL.Instance)); - } - - private IConfigService NewConfigService() - { - // todo - - throw new NotImplementedException(); - - //return new ConfigService(null, NewAppService(), new SettingService(new FreeSqlContext(FreeSQL.Instance)), - // new UserService(new FreeSqlContext(FreeSQL.Instance))); - } - public void Register() { TinyEventBus.Instance.Register(EventKeys.PUBLISH_CONFIG_SUCCESS, (param) => diff --git a/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs index 9c8b63f3..4acba8e6 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs @@ -7,7 +7,6 @@ using AgileConfig.Server.Common; using AgileConfig.Server.Common.RestClient; using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.IService; using Microsoft.Extensions.Logging; @@ -17,28 +16,25 @@ internal class ServiceInfoStatusUpdateRegister : IEventRegister { private readonly IRemoteServerNodeProxy _remoteServerNodeProxy; private readonly IRestClient _restClient; + private readonly EventRegisterTransient _serverNodeService; + private readonly EventRegisterTransient _serviceInfoService; private ILogger _logger; public ServiceInfoStatusUpdateRegister( IRemoteServerNodeProxy remoteServerNodeProxy, ILoggerFactory loggerFactory, - IRestClient restClient + IRestClient restClient, + EventRegisterTransient serverNodeService, + EventRegisterTransient serviceInfoService ) { _remoteServerNodeProxy = remoteServerNodeProxy; _restClient = restClient; + _serverNodeService = serverNodeService; + _serviceInfoService = serviceInfoService; _logger = loggerFactory.CreateLogger(); } - - private IServerNodeService NewServerNodeService() - { - return new ServerNodeService(new FreeSqlContext(FreeSQL.Instance)); - } - - private IServiceInfoService NewServiceInfoService() - { - return new ServiceInfoService(null); - } + public void Register() { @@ -46,7 +42,7 @@ public void Register() { Task.Run(async () => { - using var serverNodeService = NewServerNodeService(); + using var serverNodeService = _serverNodeService(); var serverNodes = await serverNodeService.GetAllNodesAsync(); foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) { @@ -66,7 +62,7 @@ public void Register() { Task.Run(async () => { - using var serverNodeService = NewServerNodeService(); + using var serverNodeService = _serverNodeService(); var serverNodes = await serverNodeService.GetAllNodesAsync(); foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) { @@ -86,7 +82,7 @@ public void Register() { Task.Run(async () => { - using var serverNodeService = NewServerNodeService(); + using var serverNodeService = _serverNodeService(); var serverNodes = await serverNodeService.GetAllNodesAsync(); foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) { @@ -108,7 +104,7 @@ public void Register() { dynamic paramObj = param; string id = paramObj.UniqueId; - using var serviceInfoService = NewServiceInfoService(); + using var serviceInfoService = _serviceInfoService(); var service = await serviceInfoService.GetByUniqueIdAsync(id); if (service != null && !string.IsNullOrWhiteSpace(service.AlarmUrl) && service.Status == ServiceStatus.Unhealthy) diff --git a/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs index 3372090f..8ded506b 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs @@ -1,19 +1,18 @@ using System; -using System.Collections.Generic; using System.Threading.Tasks; -using Agile.Config.Protocol; using AgileConfig.Server.Common; using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.IService; namespace AgileConfig.Server.Service.EventRegisterService; internal class SysLogRegister : IEventRegister { - private ISysLogService NewSysLogService() + private readonly EventRegisterTransient _sysLogService; + + public SysLogRegister(EventRegisterTransient sysLogService) { - return new SysLogService(new FreeSqlContext(FreeSQL.Instance)); + _sysLogService = sysLogService; } public void Register() @@ -30,7 +29,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -47,7 +46,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -68,7 +67,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -88,7 +87,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -110,7 +109,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -134,7 +133,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -157,7 +156,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -180,7 +179,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -207,7 +206,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -232,7 +231,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -258,7 +257,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -282,7 +281,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -306,7 +305,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -331,7 +330,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -356,7 +355,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -381,7 +380,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -402,7 +401,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -423,7 +422,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -444,7 +443,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -465,7 +464,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -486,7 +485,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -507,7 +506,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = NewSysLogService()) + using (var syslogService = _sysLogService()) { await syslogService.AddSysLogAsync(log); } @@ -528,7 +527,7 @@ public void Register() }; Task.Run(async () => { - using var syslogService = NewSysLogService(); + using var syslogService = _sysLogService(); await syslogService.AddSysLogAsync(log); }); }); @@ -545,7 +544,7 @@ public void Register() }; Task.Run(async () => { - using var syslogService = NewSysLogService(); + using var syslogService = _sysLogService(); await syslogService.AddSysLogAsync(log); }); }); diff --git a/src/AgileConfig.Server.Service/JwtService.cs b/src/AgileConfig.Server.Service/JwtService.cs index b7ef38bb..a1252529 100644 --- a/src/AgileConfig.Server.Service/JwtService.cs +++ b/src/AgileConfig.Server.Service/JwtService.cs @@ -3,7 +3,6 @@ using System.Security.Claims; using System.Text; using AgileConfig.Server.Common; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.IService; using Microsoft.IdentityModel.Tokens; diff --git a/src/AgileConfig.Server.Service/PremissionService.cs b/src/AgileConfig.Server.Service/PremissionService.cs index c51525d3..f2c28ac9 100644 --- a/src/AgileConfig.Server.Service/PremissionService.cs +++ b/src/AgileConfig.Server.Service/PremissionService.cs @@ -1,18 +1,26 @@ using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.IService; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; +using AgileConfig.Server.Data.Abstraction; namespace AgileConfig.Server.Service { public class PermissionService : IPremissionService { - private FreeSqlContext _dbContext; - public PermissionService(FreeSqlContext freeSql) + private readonly IUserRoleRepository _userRoleRepository; + private readonly IUserAppAuthRepository _userAppAuthRepository; + private readonly IAppRepository _appRepository; + + public PermissionService( + IUserRoleRepository userRoleRepository, + IUserAppAuthRepository userAppAuthRepository, + IAppRepository appRepository) { - _dbContext = freeSql; + _userRoleRepository = userRoleRepository; + _userAppAuthRepository = userAppAuthRepository; + _appRepository = appRepository; } private static readonly List Template_SuperAdminPermissions = new List @@ -177,7 +185,7 @@ private async Task> GetNormalUserFunctions(string userId) /// public async Task> GetUserPermission(string userId) { - var userRoles = await _dbContext.UserRoles.Where(x => x.UserId == userId).ToListAsync(); + var userRoles = await _userRoleRepository.QueryAsync(x => x.UserId == userId); if (userRoles.Any(x=>x.Role == Role.SuperAdmin)) { return Template_SuperAdminPermissions; @@ -206,10 +214,11 @@ public async Task> GetUserPermission(string userId) private async Task> GetUserAuthApp(string userId, string authPermissionKey) { var apps = new List(); - var userAuths = await _dbContext.UserAppAuths.Where(x => x.UserId == userId && x.Permission == authPermissionKey).ToListAsync(); + var userAuths = + await _userAppAuthRepository.QueryAsync(x => x.UserId == userId && x.Permission == authPermissionKey); foreach (var appAuth in userAuths) { - var app = await _dbContext.Apps.Where(x=>x.Id == appAuth.AppId).FirstAsync(); + var app = await _appRepository.GetAsync(appAuth.AppId); if (app!= null) { apps.Add(app); @@ -226,7 +235,7 @@ private async Task> GetUserAuthApp(string userId, string authPermissio /// private async Task> GetUserAdminApps(string userId) { - return await _dbContext.Apps.Where(x => x.AppAdmin == userId).ToListAsync(); + return await _appRepository.QueryAsync(x => x.AppAdmin == userId); } public string EditConfigPermissionKey => "EDIT_CONFIG"; diff --git a/src/AgileConfig.Server.Service/RegisterCenterService.cs b/src/AgileConfig.Server.Service/RegisterCenterService.cs index 4a05ba08..bfcc383a 100644 --- a/src/AgileConfig.Server.Service/RegisterCenterService.cs +++ b/src/AgileConfig.Server.Service/RegisterCenterService.cs @@ -1,5 +1,4 @@ using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.IService; using System; using System.Collections.Generic; @@ -8,22 +7,23 @@ using System.Text; using System.Threading.Tasks; using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction; using Microsoft.Extensions.Logging; namespace AgileConfig.Server.Service { public class RegisterCenterService : IRegisterCenterService { - private readonly FreeSqlContext _dbContext; + private readonly IServiceInfoRepository _serviceInfoRepository; private readonly ILogger _logger; private readonly IServiceInfoService _serviceInfoService; public RegisterCenterService( - FreeSqlContext freeSql, + IServiceInfoRepository serviceInfoRepository, IServiceInfoService serviceInfoService, ILogger logger) { - _dbContext = freeSql; + _serviceInfoRepository = serviceInfoRepository; _logger = logger; _serviceInfoService = serviceInfoService; } @@ -38,7 +38,7 @@ public async Task RegisterAsync(ServiceInfo serviceInfo) _logger.LogInformation("try to register service {0} {1}", serviceInfo.ServiceId, serviceInfo.ServiceName); //if exist - var oldEntity = await _dbContext.ServiceInfo.Where(x => x.ServiceId == serviceInfo.ServiceId).FirstAsync(); + var oldEntity = (await _serviceInfoRepository.QueryAsync(x => x.ServiceId == serviceInfo.ServiceId)).FirstOrDefault(); if (oldEntity != null) { oldEntity.RegisterTime = DateTime.Now; @@ -52,8 +52,7 @@ public async Task RegisterAsync(ServiceInfo serviceInfo) oldEntity.CheckUrl = serviceInfo.CheckUrl; oldEntity.AlarmUrl = serviceInfo.AlarmUrl; oldEntity.RegisterWay = serviceInfo.RegisterWay; - await _dbContext.ServiceInfo.UpdateAsync(oldEntity); - var rows = await _dbContext.SaveChangesAsync(); + await _serviceInfoRepository.UpdateAsync(oldEntity); _serviceInfoService.ClearCache(); @@ -68,8 +67,7 @@ public async Task RegisterAsync(ServiceInfo serviceInfo) serviceInfo.Status = ServiceStatus.Healthy; serviceInfo.Id = Guid.NewGuid().ToString("n"); - _dbContext.ServiceInfo.Add(serviceInfo); - await _dbContext.SaveChangesAsync(); + await _serviceInfoRepository.InsertAsync(serviceInfo); _serviceInfoService.ClearCache(); @@ -88,7 +86,7 @@ public async Task UnRegisterAsync(string serviceUniqueId) throw new ArgumentNullException(nameof(serviceUniqueId)); } - var oldEntity = await _dbContext.ServiceInfo.Where(x => x.Id == serviceUniqueId).FirstAsync(); + var oldEntity = await _serviceInfoRepository.GetAsync(serviceUniqueId); if (oldEntity == null) { //if not exist @@ -96,8 +94,7 @@ public async Task UnRegisterAsync(string serviceUniqueId) return false; } - _dbContext.ServiceInfo.Remove(oldEntity); - await _dbContext.SaveChangesAsync(); + await _serviceInfoRepository.DeleteAsync(oldEntity); _serviceInfoService.ClearCache(); @@ -116,7 +113,7 @@ public async Task UnRegisterByServiceIdAsync(string serviceId) throw new ArgumentNullException(nameof(serviceId)); } - var oldEntity = await _dbContext.ServiceInfo.Where(x => x.ServiceId == serviceId).FirstAsync(); + var oldEntity = (await _serviceInfoRepository.QueryAsync(x => x.ServiceId == serviceId)).FirstOrDefault(); if (oldEntity == null) { //if not exist @@ -124,8 +121,7 @@ public async Task UnRegisterByServiceIdAsync(string serviceId) return false; } - _dbContext.ServiceInfo.Remove(oldEntity); - await _dbContext.SaveChangesAsync(); + await _serviceInfoRepository.DeleteAsync(oldEntity); _serviceInfoService.ClearCache(); @@ -137,7 +133,7 @@ public async Task UnRegisterByServiceIdAsync(string serviceId) public async Task ReceiveHeartbeatAsync(string serviceUniqueId) { - var entity = await _dbContext.ServiceInfo.Where(x => x.Id == serviceUniqueId).FirstAsync(); + var entity = await _serviceInfoRepository.GetAsync(serviceUniqueId); if (entity == null) { return false; @@ -154,9 +150,8 @@ public async Task ReceiveHeartbeatAsync(string serviceUniqueId) var oldStatus = entity.Status; entity.Status = ServiceStatus.Healthy; entity.LastHeartBeat = DateTime.Now; - await _dbContext.UpdateAsync(entity); - await _dbContext.SaveChangesAsync(); + await _serviceInfoRepository.UpdateAsync(entity); if (oldStatus != ServiceStatus.Healthy) { diff --git a/src/AgileConfig.Server.Service/RemoteServerNodeProxy.cs b/src/AgileConfig.Server.Service/RemoteServerNodeProxy.cs index 2dea6f76..1d100119 100644 --- a/src/AgileConfig.Server.Service/RemoteServerNodeProxy.cs +++ b/src/AgileConfig.Server.Service/RemoteServerNodeProxy.cs @@ -2,7 +2,6 @@ using AgileConfig.Server.Common; using AgileConfig.Server.Common.RestClient; using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.IService; using Microsoft.Extensions.Logging; using System; @@ -15,26 +14,35 @@ namespace AgileConfig.Server.Service { public class RemoteServerNodeProxy : IRemoteServerNodeProxy { - private IServerNodeService GetServerNodeService() - { - return new ServerNodeService(new FreeSqlContext(FreeSQL.Instance)); - } - - private ILogger _logger; - - private ISysLogService GetSysLogService() - { - return new SysLogService(new FreeSqlContext(FreeSQL.Instance)); - } + // private IServerNodeService GetServerNodeService() + // { + // return new ServerNodeService(new FreeSqlContext(FreeSQL.Instance)); + // } + // + // private ISysLogService GetSysLogService() + // { + // return new SysLogService(new FreeSqlContext(FreeSQL.Instance)); + // } + + private readonly ILogger _logger; + private readonly IRestClient _restClient; + private readonly EventRegisterTransient _serverNodeService; + private readonly EventRegisterTransient _sysLogService; private static ConcurrentDictionary _serverNodeClientReports = new ConcurrentDictionary(); - private readonly IRestClient _restClient; + - public RemoteServerNodeProxy(ILoggerFactory loggerFactory, IRestClient restClient) + public RemoteServerNodeProxy( + ILoggerFactory loggerFactory, + IRestClient restClient, + EventRegisterTransient serverNodeService, + EventRegisterTransient sysLogService) { _logger = loggerFactory.CreateLogger(); _restClient = restClient; + _serverNodeService = serverNodeService; + _sysLogService = sysLogService; } public async Task AllClientsDoActionAsync(string address, WebsocketAction action) @@ -50,7 +58,7 @@ public async Task AllClientsDoActionAsync(string address, WebsocketAction return false; }, 5); - using (var service = GetSysLogService()) + using (var service = _sysLogService()) { var module = ""; if (action.Module == "r") @@ -86,7 +94,7 @@ public async Task AppClientsDoActionAsync(string address, string appId, st return false; }, 5); - using (var service = GetSysLogService()) + using (var service = _sysLogService()) { var module = ""; if (action.Module == "r") @@ -137,7 +145,7 @@ public async Task OneClientDoActionAsync(string address, string clientId, return false; }, 5); - using (var service = GetSysLogService()) + using (var service = _sysLogService()) { var module = ""; if (action.Module == "r") @@ -201,7 +209,7 @@ public async Task GetClientsReportAsync(string address) public async Task TestEchoAsync(string address) { - using var service = GetServerNodeService(); + using var service = _serverNodeService(); var node = await service.GetAsync(address); try { @@ -249,7 +257,7 @@ public Task TestEchoAsync() { while (true) { - using var service = GetServerNodeService(); + using var service = _serverNodeService(); var nodes = await service.GetAllNodesAsync(); foreach (var node in nodes) diff --git a/src/AgileConfig.Server.Service/ServerNodeService.cs b/src/AgileConfig.Server.Service/ServerNodeService.cs index 4f2084f7..db0a66a3 100644 --- a/src/AgileConfig.Server.Service/ServerNodeService.cs +++ b/src/AgileConfig.Server.Service/ServerNodeService.cs @@ -4,82 +4,73 @@ using System.Threading.Tasks; using AgileConfig.Server.Common; using System; -using AgileConfig.Server.Data.Freesql; +using System.Linq; +using AgileConfig.Server.Data.Abstraction; namespace AgileConfig.Server.Service { public class ServerNodeService : IServerNodeService { - private FreeSqlContext _dbContext; + private readonly IServerNodeRepository _serverNodeRepository; - public ServerNodeService(FreeSqlContext context) + + public ServerNodeService(IServerNodeRepository serverNodeRepository) { - _dbContext = context; + _serverNodeRepository = serverNodeRepository; } public async Task AddAsync(ServerNode node) { - await _dbContext.ServerNodes.AddAsync(node); - int x = await _dbContext.SaveChangesAsync(); - var result = x > 0; - - return result; + await _serverNodeRepository.InsertAsync(node); + return true; } public async Task DeleteAsync(ServerNode node) { - node = await _dbContext.ServerNodes.Where(n => n.Id == node.Id).ToOneAsync(); - if (node != null) + var node2 = await _serverNodeRepository.GetAsync(node.Id); + if (node2 != null) { - _dbContext.ServerNodes.Remove(node); + await _serverNodeRepository.DeleteAsync(node2); } - int x = await _dbContext.SaveChangesAsync(); - var result = x > 0; - - return result; + return true; } public async Task DeleteAsync(string address) { - var node = await _dbContext.ServerNodes.Where(n => n.Id == address).ToOneAsync(); - if (node != null) + var node2 = await _serverNodeRepository.GetAsync(address); + if (node2 != null) { - _dbContext.ServerNodes.Remove(node); + await _serverNodeRepository.DeleteAsync(node2); } - int x = await _dbContext.SaveChangesAsync(); - var result = x > 0; - return result; + return true; } public void Dispose() { - _dbContext.Dispose(); + _serverNodeRepository.Dispose(); } public async Task> GetAllNodesAsync() { - return await _dbContext.ServerNodes.Where(n => 1 == 1).ToListAsync(); + return await _serverNodeRepository.AllAsync(); } public async Task GetAsync(string address) { - return await _dbContext.ServerNodes.Where(n => n.Id == address).ToOneAsync(); + return await _serverNodeRepository.GetAsync(address); } public async Task UpdateAsync(ServerNode node) { - _dbContext.Update(node); - var x = await _dbContext.SaveChangesAsync(); - var result = x > 0; - - return result; + await _serverNodeRepository.UpdateAsync(node); + return true; } public async Task InitWatchNodeAsync() { - var count = await _dbContext.ServerNodes.Select.CountAsync(); + var count = await _serverNodeRepository.CountAsync(); if (count > 0) { return false; @@ -105,33 +96,23 @@ public async Task InitWatchNodeAsync() } } - foreach (var address in addresses) - { - var node = await _dbContext.ServerNodes.Where(n => n.Id == address).ToOneAsync(); - if (node == null) - { - node = new ServerNode() - { - Id = address, - CreateTime = DateTime.Now, - }; - await _dbContext.ServerNodes.AddAsync(node); - } - } + var existNodes = await _serverNodeRepository.QueryAsync(x => addresses.Contains(x.Id)); + var newNodes = addresses + .Where(x => existNodes.All(y => y.Id != x)) + .Select(x => new ServerNode { Id = x, CreateTime = DateTime.Now }) + .ToList(); - var result = 0; - if (addresses.Count > 0) - { - result = await _dbContext.SaveChangesAsync(); - } + if (newNodes.Count == 0) + return false; - return result > 0; + await _serverNodeRepository.InsertAsync(newNodes); + return true; } public async Task JoinAsync(string ip, int port, string desc) { var address = $"http://{ip}:{port}"; - var nodes = await _dbContext.ServerNodes.Where(x => x.Id == address).ToListAsync(); + var nodes = await _serverNodeRepository.QueryAsync(x => x.Id == address); if (nodes.Count > 0) { nodes.ForEach(n => { @@ -142,7 +123,7 @@ public async Task JoinAsync(string ip, int port, string desc) } else { - await _dbContext.ServerNodes.AddAsync(new ServerNode { + await _serverNodeRepository.InsertAsync(new ServerNode { Id = address, CreateTime = DateTime.Now, Remark = desc, @@ -151,8 +132,7 @@ await _dbContext.ServerNodes.AddAsync(new ServerNode { }); } - var effRows = await _dbContext.SaveChangesAsync(); - return effRows > 0; + return true; } } } diff --git a/src/AgileConfig.Server.Service/ServiceCollectionExt.cs b/src/AgileConfig.Server.Service/ServiceCollectionExt.cs index 216c6ee4..e3e5ee95 100644 --- a/src/AgileConfig.Server.Service/ServiceCollectionExt.cs +++ b/src/AgileConfig.Server.Service/ServiceCollectionExt.cs @@ -32,6 +32,9 @@ public static void AddBusinessServices(this IServiceCollection sc) sc.AddScoped(); sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); sc.AddScoped(x => key => { return key switch @@ -46,6 +49,8 @@ public static void AddBusinessServices(this IServiceCollection sc) sc.AddTransient,EventRegisterTransient>(); sc.AddTransient,EventRegisterTransient>(); sc.AddTransient,EventRegisterTransient>(); + sc.AddTransient,EventRegisterTransient>(); + sc.AddTransient,EventRegisterTransient>(); } } } diff --git a/src/AgileConfig.Server.Service/ServiceHealthCheckService.cs b/src/AgileConfig.Server.Service/ServiceHealthCheckService.cs index 0474d275..2c73b6f0 100644 --- a/src/AgileConfig.Server.Service/ServiceHealthCheckService.cs +++ b/src/AgileConfig.Server.Service/ServiceHealthCheckService.cs @@ -2,8 +2,8 @@ using System.Threading.Tasks; using AgileConfig.Server.Common; using AgileConfig.Server.Common.RestClient; +using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.IService; using Microsoft.Extensions.Logging; @@ -13,17 +13,20 @@ public class ServiceHealthCheckService : IServiceHealthCheckService { private readonly ILogger _logger; private readonly IRestClient _restClient; + private readonly IServiceInfoRepository _serviceInfoRepository; private readonly IServiceInfoService _serviceInfoService; public ServiceHealthCheckService( IServiceInfoService serviceInfoService, ILogger logger, - IRestClient restClient + IRestClient restClient, + IServiceInfoRepository serviceInfoRepository ) { _serviceInfoService = serviceInfoService; _logger = logger; _restClient = restClient; + _serviceInfoRepository = serviceInfoRepository; } private int _checkInterval; @@ -121,8 +124,8 @@ public Task StartCheckAsync() while (true) { //没有填写心跳模式,则不做检查 - var services = await FreeSQL.Instance.Select() - .Where(x => x.HeartBeatMode != null && x.HeartBeatMode != "").ToListAsync(); + var services = await _serviceInfoRepository + .QueryAsync(x => x.HeartBeatMode != null && x.HeartBeatMode != ""); foreach (var service in services) { if (service.HeartBeatMode == HeartBeatModes.none.ToString()) diff --git a/src/AgileConfig.Server.Service/ServiceInfoService.cs b/src/AgileConfig.Server.Service/ServiceInfoService.cs index e899223e..49fce178 100644 --- a/src/AgileConfig.Server.Service/ServiceInfoService.cs +++ b/src/AgileConfig.Server.Service/ServiceInfoService.cs @@ -1,5 +1,4 @@ using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.IService; using System; using System.Collections.Generic; @@ -8,6 +7,7 @@ using System.Text; using System.Threading.Tasks; using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction; using Microsoft.Extensions.Caching.Memory; using Newtonsoft.Json; @@ -16,53 +16,51 @@ namespace AgileConfig.Server.Service public class ServiceInfoService : IServiceInfoService { private readonly IMemoryCache _memoryCache; + private readonly IServiceInfoRepository _serviceInfoRepository; - public ServiceInfoService(IMemoryCache memoryCache) + public ServiceInfoService(IMemoryCache memoryCache,IServiceInfoRepository serviceInfoRepository) { _memoryCache = memoryCache; + _serviceInfoRepository = serviceInfoRepository; } public async Task GetByUniqueIdAsync(string id) { - var entity = await FreeSQL.Instance.Select().Where(x => x.Id == id).FirstAsync(); + var entity = await _serviceInfoRepository.GetAsync(id); return entity; } public async Task GetByServiceIdAsync(string serviceId) { - var entity = await FreeSQL.Instance.Select().Where(x => x.ServiceId == serviceId).FirstAsync(); + var entity = (await _serviceInfoRepository.QueryAsync(x => x.ServiceId == serviceId)).FirstOrDefault(); return entity; } public async Task RemoveAsync(string id) { - var aff = await FreeSQL.Instance.Delete().Where(x => x.Id == id) - .ExecuteAffrowsAsync(); - - return aff > 0; + await _serviceInfoRepository.DeleteAsync(id); + return true; } public async Task> GetAllServiceInfoAsync() { - var services = await FreeSQL.Instance.Select().Where(x => 1 == 1).ToListAsync(); + var services = await _serviceInfoRepository.AllAsync(); return services; } public async Task> GetOnlineServiceInfoAsync() { - var services = await FreeSQL.Instance.Select().Where(x => x.Status == ServiceStatus.Healthy) - .ToListAsync(); + var services = await _serviceInfoRepository.QueryAsync(x => x.Status == ServiceStatus.Healthy); return services; } public async Task> GetOfflineServiceInfoAsync() { - var services = await FreeSQL.Instance.Select().Where(x => x.Status == ServiceStatus.Unhealthy) - .ToListAsync(); + var services = await _serviceInfoRepository.QueryAsync(x => x.Status == ServiceStatus.Unhealthy); return services; } @@ -127,21 +125,15 @@ public async Task UpdateServiceStatus(ServiceInfo service, ServiceStatus status) var id = service.Id; var oldStatus = service.Status; - if (status == ServiceStatus.Unhealthy) - { - await FreeSQL.Instance.Update() - .Set(x => x.Status, status) - .Where(x => x.Id == id) - .ExecuteAffrowsAsync(); - } - else + var service2 = await _serviceInfoRepository.GetAsync(id); + if (service2 == null) return; + + service2.Status = status; + if (status != ServiceStatus.Unhealthy) { - await FreeSQL.Instance.Update() - .Set(x => x.Status, status) - .Set(x => x.LastHeartBeat, DateTime.Now) - .Where(x => x.Id == id) - .ExecuteAffrowsAsync(); + service2.LastHeartBeat = DateTime.Now; } + await _serviceInfoRepository.UpdateAsync(service2); if (oldStatus != status) { @@ -156,6 +148,7 @@ await FreeSQL.Instance.Update() public void Dispose() { + _serviceInfoRepository.Dispose(); } } } \ No newline at end of file diff --git a/src/AgileConfig.Server.Service/SettingService.cs b/src/AgileConfig.Server.Service/SettingService.cs index 89812a60..e0bb9fe0 100644 --- a/src/AgileConfig.Server.Service/SettingService.cs +++ b/src/AgileConfig.Server.Service/SettingService.cs @@ -5,7 +5,6 @@ using System.Threading.Tasks; using AgileConfig.Server.Common; using AgileConfig.Server.Data.Abstraction; -using AgileConfig.Server.Data.Freesql; namespace AgileConfig.Server.Service { diff --git a/src/AgileConfig.Server.Service/SysLogService.cs b/src/AgileConfig.Server.Service/SysLogService.cs index d98620c3..3a49c5e5 100644 --- a/src/AgileConfig.Server.Service/SysLogService.cs +++ b/src/AgileConfig.Server.Service/SysLogService.cs @@ -2,85 +2,108 @@ using AgileConfig.Server.IService; using System; using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; using System.Threading.Tasks; -using AgileConfig.Server.Data.Freesql; +using AgileConfig.Server.Data.Abstraction; namespace AgileConfig.Server.Service { public class SysLogService : ISysLogService { - private FreeSqlContext _dbContext; + private readonly ISysLogRepository _sysLogRepository; - public SysLogService(FreeSqlContext context) + public SysLogService(ISysLogRepository sysLogRepository) { - _dbContext = context; + _sysLogRepository = sysLogRepository; } public async Task AddRangeAsync(IEnumerable logs) { - int x = await _dbContext.Freesql.Insert(logs).ExecuteAffrowsAsync(); - return x > 0; + await _sysLogRepository.InsertAsync(logs.ToList()); + return true; } public async Task AddSysLogAsync(SysLog log) { - int x = await _dbContext.Freesql.Insert(log).ExecuteAffrowsAsync();; - return x > 0; + await _sysLogRepository.InsertAsync(log); + return true; } public async Task Count(string appId, SysLogType? logType, DateTime? startTime, DateTime? endTime) { - var query = _dbContext.SysLogs.Where(s => 1 == 1); + var query = (Expression)Expression + .Constant(true); + if (!string.IsNullOrEmpty(appId)) { - query = query.Where(x => x.AppId == appId); + Expression> expr = x => x.AppId == appId; + query = Expression.AndAlso(query, expr); } + if (startTime.HasValue) { - query = query.Where(x => x.LogTime >= startTime); + Expression> expr = (x => x.LogTime >= startTime); + query = Expression.AndAlso(query, expr); } + if (endTime.HasValue) { - query = query.Where(x => x.LogTime < endTime); + Expression> expr = (x => x.LogTime < endTime); + query = Expression.AndAlso(query, expr); } + if (logType.HasValue) { - query = query.Where(x => x.LogType == logType); + Expression> expr = (x => x.LogType == logType); + query = Expression.AndAlso(query, expr); } - var count = await query.CountAsync(); + var exp = Expression.Lambda>(query); + + var count = await _sysLogRepository.CountAsync(exp); return count; } public void Dispose() { - _dbContext.Dispose(); + _sysLogRepository.Dispose(); } - public Task> SearchPage(string appId, SysLogType? logType, DateTime? startTime, DateTime? endTime, int pageSize, int pageIndex) + public async Task> SearchPage(string appId, SysLogType? logType, DateTime? startTime, DateTime? endTime, int pageSize, int pageIndex) { - var query = _dbContext.SysLogs.Where(s => 1 == 1); + var query = (Expression)Expression + .Constant(true); + if (!string.IsNullOrEmpty(appId)) { - query = query.Where(x => x.AppId == appId); + Expression> expr = x => x.AppId == appId; + query = Expression.AndAlso(query, expr); } + if (startTime.HasValue) { - query = query.Where(x => x.LogTime >= startTime); + Expression> expr = (x => x.LogTime >= startTime); + query = Expression.AndAlso(query, expr); } + if (endTime.HasValue) { - query = query.Where(x => x.LogTime < endTime); + Expression> expr = (x => x.LogTime < endTime); + query = Expression.AndAlso(query, expr); } + if (logType.HasValue) { - query = query.Where(x => x.LogType == logType); + Expression> expr = (x => x.LogType == logType); + query = Expression.AndAlso(query, expr); } - query = query.OrderByDescending(x => x.Id).Skip((pageIndex - 1) * pageSize).Take(pageSize); + var exp = Expression.Lambda>(query); - return query.ToListAsync(); + var list = await _sysLogRepository.QueryPageAsync(exp, pageIndex, pageSize, defaultSortType: "DESC"); + return list; } } } diff --git a/src/AgileConfig.Server.Service/UserService.cs b/src/AgileConfig.Server.Service/UserService.cs index a709df93..7b87c74e 100644 --- a/src/AgileConfig.Server.Service/UserService.cs +++ b/src/AgileConfig.Server.Service/UserService.cs @@ -1,59 +1,59 @@ using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.IService; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction; namespace AgileConfig.Server.Service { public class UserService : IUserService { - private FreeSqlContext _dbContext; + private readonly IUserRepository _userRepository; + private readonly IUserRoleRepository _userRoleRepository; - public UserService(FreeSqlContext context) + + public UserService(IUserRepository userRepository,IUserRoleRepository userRoleRepository) { - _dbContext = context; + _userRepository = userRepository; + _userRoleRepository = userRoleRepository; } public async Task AddAsync(User user) { - var old = await _dbContext.Users.Where(u => u.UserName == user.UserName && u.Status == UserStatus.Normal).FirstAsync(); + var old = (await _userRepository.QueryAsync(u => u.UserName == user.UserName && u.Status == UserStatus.Normal)).FirstOrDefault(); if (old != null) { return false; } - await _dbContext.Users.AddAsync(user); - var result = await _dbContext.SaveChangesAsync(); + await _userRepository.InsertAsync(user); - return result > 0; + return true; } public async Task DeleteAsync(User user) { - _dbContext.Users.Remove(user); - var result = await _dbContext.SaveChangesAsync(); - - return result > 0; + await _userRepository.DeleteAsync(user); + return true; } public async Task> GetUsersByNameAsync(string userName) { - return await _dbContext.Users.Where(u => u.UserName == userName).ToListAsync(); + return await _userRepository.QueryAsync(u => u.UserName == userName); } public async Task GetUserAsync(string id) { - return await _dbContext.Users.Where(u => u.Id == id).ToOneAsync(); + return await _userRepository.GetAsync(id); } public async Task> GetUserRolesAsync(string userId) { - var userRoles = await _dbContext.UserRoles.Where(x => x.UserId == userId).ToListAsync(); + var userRoles = await _userRoleRepository.QueryAsync(x => x.UserId == userId); return userRoles.Select(x => x.Role).ToList(); } @@ -61,15 +61,14 @@ public async Task> GetUserRolesAsync(string userId) public async Task UpdateAsync(User user) { - await _dbContext.Users.UpdateAsync(user); - var result = await _dbContext.SaveChangesAsync(); - - return result > 0; + await _userRepository.UpdateAsync(user); + return true; } public async Task UpdateUserRolesAsync(string userId, List roles) { - await _dbContext.UserRoles.RemoveAsync(x => x.UserId == userId); + var dbUserRoles = await _userRoleRepository.QueryAsync(x => x.UserId == userId); + await _userRoleRepository.DeleteAsync(dbUserRoles); var userRoles = new List(); roles.ForEach(x => { userRoles.Add(new UserRole @@ -80,25 +79,24 @@ public async Task UpdateUserRolesAsync(string userId, List roles) }); }); - await _dbContext.UserRoles.AddRangeAsync(userRoles); - var result = await _dbContext.SaveChangesAsync(); - - return result > 0; + await _userRoleRepository.InsertAsync(userRoles); + return true; } public void Dispose() { - _dbContext?.Dispose(); + _userRepository.Dispose(); + _userRoleRepository.Dispose(); } public async Task> GetAll() { - return await _dbContext.Users.Where(x => 1 == 1).ToListAsync(); + return await _userRepository.AllAsync(); } public async Task ValidateUserPassword(string userName, string password) { - var user = await _dbContext.Users.Where(u => u.Status == UserStatus.Normal && u.UserName == userName).FirstAsync(); + var user = (await _userRepository.QueryAsync(u => u.Status == UserStatus.Normal && u.UserName == userName)).FirstOrDefault(); if (user == null) { return false; @@ -114,17 +112,9 @@ public async Task ValidateUserPassword(string userName, string password) public async Task> GetUsersByRoleAsync(Role role) { - var users = await FreeSQL.Instance.Select() - .InnerJoin((a, b) => a.Id == b.UserId) - .Where((a, b) => b.Role == role) - .ToListAsync((a, b) => a); - - return users; - } - - public User GetUser(string userId) - { - return _dbContext.Users.Where(u => u.Id == userId).ToOne(); + var userRoles = await _userRoleRepository.QueryAsync(x => x.Role == role); + var userIds = userRoles.Select(x => x.UserId).Distinct().ToList(); + return await _userRepository.QueryAsync(x => userIds.Contains(x.Id)); } } } diff --git a/test/AgileConfig.Server.ServiceTests/AgileConfig.Server.ServiceTests.csproj b/test/AgileConfig.Server.ServiceTests/AgileConfig.Server.ServiceTests.csproj index 581ad7c0..4de281c3 100644 --- a/test/AgileConfig.Server.ServiceTests/AgileConfig.Server.ServiceTests.csproj +++ b/test/AgileConfig.Server.ServiceTests/AgileConfig.Server.ServiceTests.csproj @@ -18,6 +18,7 @@ + diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs index 429523c9..2afdf5e1 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs @@ -7,6 +7,9 @@ using FreeSql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; +using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.PostgreSQL { @@ -15,7 +18,7 @@ public class ServerNodeServiceTests { IFreeSql fsq = null; FreeSqlContext freeSqlContext; - ServerNodeService service = null; + IServerNodeService service = null; [TestInitialize] public void TestInitialize() @@ -28,7 +31,14 @@ public void TestInitialize() FluentApi.Config(fsq); freeSqlContext = new FreeSqlContext(fsq); - service = new ServerNodeService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/SysLogServiceTests.cs index 11a65701..097f199f 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/SysLogServiceTests.cs @@ -7,6 +7,9 @@ using FreeSql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; +using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.PostgreSQL { @@ -16,7 +19,7 @@ public class SysLogServiceTests IFreeSql fsq = null; FreeSqlContext freeSqlContext; - SysLogService service = null; + ISysLogService service = null; [TestInitialize] public void TestInitialize() @@ -29,7 +32,14 @@ public void TestInitialize() FluentApi.Config(fsq); freeSqlContext = new FreeSqlContext(fsq); - service = new SysLogService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs index e4ce7725..daa7565e 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs @@ -7,6 +7,9 @@ using FreeSql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; +using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.mysql { @@ -15,7 +18,7 @@ public class ServerNodeServiceTests { IFreeSql fsq = null; FreeSqlContext freeSqlContext; - ServerNodeService service = null; + IServerNodeService service = null; [TestInitialize] public void TestInitialize() @@ -27,7 +30,14 @@ public void TestInitialize() .Build(); freeSqlContext = new FreeSqlContext(fsq); - service = new ServerNodeService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/mysql/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/SysLogServiceTests.cs index 6500da51..b4021f00 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/SysLogServiceTests.cs @@ -7,6 +7,9 @@ using FreeSql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; +using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.mysql { @@ -16,7 +19,7 @@ public class SysLogServiceTests IFreeSql fsq = null; FreeSqlContext freeSqlContext; - SysLogService service = null; + ISysLogService service = null; [TestInitialize] public void TestInitialize() @@ -28,7 +31,14 @@ public void TestInitialize() .Build(); freeSqlContext = new FreeSqlContext(fsq); - service = new SysLogService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs index 93ea8ec8..59206aef 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs @@ -7,6 +7,9 @@ using FreeSql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; +using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.oracle { @@ -15,7 +18,7 @@ public class ServerNodeServiceTests { IFreeSql fsq = null; FreeSqlContext freeSqlContext; - ServerNodeService service = null; + IServerNodeService service = null; [TestInitialize] public void TestInitialize() @@ -28,7 +31,14 @@ public void TestInitialize() FluentApi.Config(fsq); freeSqlContext = new FreeSqlContext(fsq); - service = new ServerNodeService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/oracle/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/SysLogServiceTests.cs index 9d71a71d..b0a18c1e 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/SysLogServiceTests.cs @@ -7,6 +7,9 @@ using FreeSql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; +using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.oracle { @@ -16,7 +19,7 @@ public class SysLogServiceTests IFreeSql fsq = null; FreeSqlContext freeSqlContext; - SysLogService service = null; + ISysLogService service = null; [TestInitialize] public void TestInitialize() @@ -29,7 +32,14 @@ public void TestInitialize() FluentApi.Config(fsq); freeSqlContext = new FreeSqlContext(fsq); - service = new SysLogService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs index b7365651..3a7fb9f0 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs @@ -7,6 +7,9 @@ using FreeSql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; +using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests { @@ -15,7 +18,7 @@ public class ServerNodeServiceTests { IFreeSql fsq = null; FreeSqlContext freeSqlContext; - ServerNodeService service = null; + IServerNodeService service = null; [TestInitialize] public void TestInitialize() @@ -27,7 +30,14 @@ public void TestInitialize() .Build(); freeSqlContext = new FreeSqlContext(fsq); - service = new ServerNodeService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs index 7ce386a5..f84493f9 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs @@ -7,6 +7,9 @@ using FreeSql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; +using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests { @@ -16,7 +19,7 @@ public class SysLogServiceTests IFreeSql fsq = null; FreeSqlContext freeSqlContext; - SysLogService service = null; + ISysLogService service = null; [TestInitialize] public void TestInitialize() @@ -28,7 +31,14 @@ public void TestInitialize() .Build(); freeSqlContext = new FreeSqlContext(fsq); - service = new SysLogService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs index bf18df40..7b13b63f 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs @@ -7,6 +7,9 @@ using FreeSql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; +using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.sqlserver { @@ -15,7 +18,7 @@ public class ServerNodeServiceTests { IFreeSql fsq = null; FreeSqlContext freeSqlContext; - ServerNodeService service = null; + IServerNodeService service = null; [TestInitialize] public void TestInitialize() @@ -27,8 +30,15 @@ public void TestInitialize() .Build(); FluentApi.Config(fsq); freeSqlContext = new FreeSqlContext(fsq); - - service = new ServerNodeService(freeSqlContext); + + IServiceCollection services = new ServiceCollection(); + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/SysLogServiceTests.cs index 94325df4..88eea163 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/SysLogServiceTests.cs @@ -7,6 +7,9 @@ using FreeSql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; +using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.IService; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.sqlserver { @@ -16,7 +19,7 @@ public class SysLogServiceTests IFreeSql fsq = null; FreeSqlContext freeSqlContext; - SysLogService service = null; + ISysLogService service = null; [TestInitialize] public void TestInitialize() @@ -29,7 +32,14 @@ public void TestInitialize() FluentApi.Config(fsq); freeSqlContext = new FreeSqlContext(fsq); - service = new SysLogService(freeSqlContext); + IServiceCollection services = new ServiceCollection(); + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + services.AddBusinessServices(); + + + var serviceProvider = services.BuildServiceProvider(); + service = serviceProvider.GetService(); fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); From 85884cf1b1ccbd4c4c617e8317b11c6554011dc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Wed, 27 Dec 2023 10:54:30 +0800 Subject: [PATCH 19/45] =?UTF-8?q?=E7=B3=BB=E7=BB=9F=E5=88=9D=E5=A7=8B?= =?UTF-8?q?=E5=8C=96=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ConfigureJwtBearerOptions.cs | 4 +- .../Controllers/UserController.cs | 4 +- .../SystemSettings.cs | 11 +++ .../ISysInitRepository.cs | 18 +++++ .../MongodbRepository.cs | 6 +- .../ServiceCollectionExt.cs | 2 + .../SysInitRepository.cs | 21 +++++ .../MongodbRepositoryExt.cs | 2 + .../SysInitRepository.cs | 19 +++++ .../ISettingService.cs | 12 --- .../ISystemInitializationService.cs | 6 ++ src/AgileConfig.Server.Service/JwtService.cs | 11 +-- .../ServiceCollectionExt.cs | 11 +-- .../SettingService.cs | 79 +++---------------- .../SystemInitializationService.cs | 59 ++++++++++++++ .../mysql/SettingServiceTests.cs | 5 +- 16 files changed, 166 insertions(+), 104 deletions(-) create mode 100644 src/AgileConfig.Server.Common/SystemSettings.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/ISysInitRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs create mode 100644 src/AgileConfig.Server.Data.Repository.Mongodb/SysInitRepository.cs create mode 100644 src/AgileConfig.Server.IService/ISystemInitializationService.cs create mode 100644 src/AgileConfig.Server.Service/SystemInitializationService.cs diff --git a/src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs b/src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs index d28859b9..ad25cf0e 100644 --- a/src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs +++ b/src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs @@ -8,11 +8,11 @@ namespace AgileConfig.Server.Apisite; public class ConfigureJwtBearerOptions( IJwtService jwtService, - ISettingService settingService) : IConfigureNamedOptions + ISystemInitializationService systemInitializationService) : IConfigureNamedOptions { public void Configure(JwtBearerOptions options) { - settingService.TryInitJwtSecret(); + systemInitializationService.TryInitJwtSecret(); options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = jwtService.Issuer, diff --git a/src/AgileConfig.Server.Apisite/Controllers/UserController.cs b/src/AgileConfig.Server.Apisite/Controllers/UserController.cs index 39a5129a..1d02d908 100644 --- a/src/AgileConfig.Server.Apisite/Controllers/UserController.cs +++ b/src/AgileConfig.Server.Apisite/Controllers/UserController.cs @@ -38,7 +38,7 @@ public async Task Search(string userName, string team, int curren } var users = await _userService.GetAll(); - users = users.Where(x => x.Status == UserStatus.Normal && x.Id != SettingService.SuperAdminId).ToList(); + users = users.Where(x => x.Status == UserStatus.Normal && x.Id != SystemSettings.SuperAdminId).ToList(); if (!string.IsNullOrEmpty(userName)) { users = users.Where(x => x.UserName != null && x.UserName.Contains(userName)).ToList(); @@ -264,7 +264,7 @@ public async Task adminUsers() public async Task AllUsers() { var users = await _userService.GetAll(); - users = users.Where(x => x.Status == UserStatus.Normal && x.Id != SettingService.SuperAdminId).ToList(); + users = users.Where(x => x.Status == UserStatus.Normal && x.Id != SystemSettings.SuperAdminId).ToList(); return Json(new { diff --git a/src/AgileConfig.Server.Common/SystemSettings.cs b/src/AgileConfig.Server.Common/SystemSettings.cs new file mode 100644 index 00000000..06e957c3 --- /dev/null +++ b/src/AgileConfig.Server.Common/SystemSettings.cs @@ -0,0 +1,11 @@ +namespace AgileConfig.Server.Common; + +public static class SystemSettings +{ + public const string SuperAdminId = "super_admin"; + public const string SuperAdminUserName = "admin"; + + public const string DefaultEnvironment = "DEV,TEST,STAGING,PROD"; + public const string DefaultEnvironmentKey = "environment"; + public const string DefaultJwtSecretKey = "jwtsecret"; +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Abstraction/ISysInitRepository.cs b/src/AgileConfig.Server.Data.Abstraction/ISysInitRepository.cs new file mode 100644 index 00000000..063e2b27 --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/ISysInitRepository.cs @@ -0,0 +1,18 @@ +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Abstraction; + +public interface ISysInitRepository +{ + /// + /// get jwt token secret from db + /// + /// + string? GetJwtTokenSecret(); + + /// + /// save initialization setting + /// + /// + void SaveInitSetting(Setting setting); +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs index 39a796a3..6dea867a 100644 --- a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs @@ -36,11 +36,11 @@ public async Task> AllAsync() private Expression> GetIdPropertyFilter(TId id) { - var expression = _access.MongoQueryable.Where(x => Equals(x.Id, id)).Expression; - return Expression.Lambda>(expression); + Expression> expression = x => Equals(x.Id, id); + return expression; } - public async Task GetAsync(TId id) + public async Task GetAsync(TId id) { var filter = GetIdPropertyFilter(id); return await (await _access.Collection.FindAsync(filter)).SingleOrDefaultAsync(); diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceCollectionExt.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceCollectionExt.cs index fa82ccd9..281ddbbe 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceCollectionExt.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceCollectionExt.cs @@ -23,6 +23,8 @@ public static void AddFreeSqlRepository(this IServiceCollection sc) sc.AddScoped(); sc.AddScoped(); sc.AddScoped(); + + sc.AddSingleton(); } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs new file mode 100644 index 00000000..3f8996f0 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs @@ -0,0 +1,21 @@ +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; + +namespace AgileConfig.Server.Data.Repository.Freesql; + +public class SysInitRepository : ISysInitRepository +{ + public string? GetJwtTokenSecret() + { + var setting = FreeSQL.Instance.Select().Where(x => x.Id == SystemSettings.DefaultJwtSecretKey) + .ToOne(); + return setting?.Value; + } + + public void SaveInitSetting(Setting setting) + { + FreeSQL.Instance.Insert(setting); + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs index 9bf89958..e9f341d7 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs @@ -17,5 +17,7 @@ public static void AddMongodbRepository(this IServiceCollection services) services.AddScoped(); services.AddScoped(); services.AddScoped(); + + services.AddSingleton(); } } \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/SysInitRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/SysInitRepository.cs new file mode 100644 index 00000000..05f676f2 --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/SysInitRepository.cs @@ -0,0 +1,19 @@ +using AgileConfig.Server.Common; + +namespace AgileConfig.Server.Data.Repository.Mongodb; + +public class SysInitRepository : ISysInitRepository +{ + private readonly MongodbAccess _access = new(Global.Config["db:conn"]); + + public string? GetJwtTokenSecret() + { + var setting = _access.MongoQueryable.FirstOrDefault(x => x.Id == SystemSettings.DefaultJwtSecretKey); + return setting?.Value; + } + + public void SaveInitSetting(Setting setting) + { + _access.Collection.InsertOne(setting); + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.IService/ISettingService.cs b/src/AgileConfig.Server.IService/ISettingService.cs index c81bc7e3..a0ed09b6 100644 --- a/src/AgileConfig.Server.IService/ISettingService.cs +++ b/src/AgileConfig.Server.IService/ISettingService.cs @@ -46,17 +46,5 @@ public interface ISettingService: IDisposable /// /// Task GetEnvironmentList(); - - /// - /// 如果环境变量没有 JwtSetting:SecurityKey 则尝试生成一个key到数据库 - /// - /// - bool TryInitJwtSecret(); - - /// - /// 从配置表获取 jwt secret key - /// - /// - string GetJwtTokenSecret(); } } diff --git a/src/AgileConfig.Server.IService/ISystemInitializationService.cs b/src/AgileConfig.Server.IService/ISystemInitializationService.cs new file mode 100644 index 00000000..c76b240a --- /dev/null +++ b/src/AgileConfig.Server.IService/ISystemInitializationService.cs @@ -0,0 +1,6 @@ +namespace AgileConfig.Server.IService; + +public interface ISystemInitializationService +{ + bool TryInitJwtSecret(); +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Service/JwtService.cs b/src/AgileConfig.Server.Service/JwtService.cs index a1252529..f903356e 100644 --- a/src/AgileConfig.Server.Service/JwtService.cs +++ b/src/AgileConfig.Server.Service/JwtService.cs @@ -3,6 +3,7 @@ using System.Security.Claims; using System.Text; using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.IService; using Microsoft.IdentityModel.Tokens; @@ -11,9 +12,8 @@ namespace AgileConfig.Server.Service; /// /// jwt 相关业务 /// -public class JwtService : IJwtService +public class JwtService(ISysInitRepository sysInitRepository) : IJwtService { - private readonly ISettingService _settingService; // static JwtService() // { // // 则尝试生成一个key到数据库 @@ -21,11 +21,6 @@ public class JwtService : IJwtService // settingService.TryInitJwtSecret(); // } - public JwtService(ISettingService settingService) - { - _settingService = settingService; - } - public string Issuer => Global.Config["JwtSetting:Issuer"]; public string Audience => Global.Config["JwtSetting:Audience"]; public int ExpireSeconds => int.Parse(Global.Config["JwtSetting:ExpireSeconds"]); @@ -45,7 +40,7 @@ public string GetSecurityKey() } //using var settingService = new SettingService(new FreeSqlContext(FreeSQL.Instance)); - _secretKey = _settingService.GetJwtTokenSecret(); + _secretKey = sysInitRepository.GetJwtTokenSecret(); if (string.IsNullOrEmpty(_secretKey)) { diff --git a/src/AgileConfig.Server.Service/ServiceCollectionExt.cs b/src/AgileConfig.Server.Service/ServiceCollectionExt.cs index e3e5ee95..258497b0 100644 --- a/src/AgileConfig.Server.Service/ServiceCollectionExt.cs +++ b/src/AgileConfig.Server.Service/ServiceCollectionExt.cs @@ -14,6 +14,7 @@ public static class ServiceCollectionExt { public static void AddBusinessServices(this IServiceCollection sc) { + sc.AddSingleton(); sc.AddSingleton(); sc.AddScoped(); @@ -46,11 +47,11 @@ public static void AddBusinessServices(this IServiceCollection sc) }; }); - sc.AddTransient,EventRegisterTransient>(); - sc.AddTransient,EventRegisterTransient>(); - sc.AddTransient,EventRegisterTransient>(); - sc.AddTransient,EventRegisterTransient>(); - sc.AddTransient,EventRegisterTransient>(); + sc.AddTransient>(x => x.GetService); + sc.AddTransient>(x => x.GetService); + sc.AddTransient>(x => x.GetService); + sc.AddTransient>(x => x.GetService); + sc.AddTransient>(x => x.GetService); } } } diff --git a/src/AgileConfig.Server.Service/SettingService.cs b/src/AgileConfig.Server.Service/SettingService.cs index e0bb9fe0..f616aae2 100644 --- a/src/AgileConfig.Server.Service/SettingService.cs +++ b/src/AgileConfig.Server.Service/SettingService.cs @@ -14,13 +14,6 @@ public class SettingService : ISettingService private readonly IUserRepository _userRepository; private readonly IUserRoleRepository _userRoleRepository; - public const string SuperAdminId = "super_admin"; - public const string SuperAdminUserName = "admin"; - - public const string DefaultEnvironment = "DEV,TEST,STAGING,PROD"; - public const string DefaultEnvironmentKey = "environment"; - public const string DefaultJwtSecretKey = "jwtsecret"; - public SettingService( ISettingRepository settingRepository, IUserRepository userRepository, @@ -84,13 +77,13 @@ public async Task SetSuperAdminPassword(string password) password = Encrypt.Md5((password + newSalt)); var su = new User(); - su.Id = SuperAdminId; + su.Id = SystemSettings.SuperAdminId; su.Password = password; su.Salt = newSalt; su.Status = UserStatus.Normal; su.Team = ""; su.CreateTime = DateTime.Now; - su.UserName = SuperAdminUserName; + su.UserName = SystemSettings.SuperAdminUserName; await _userRepository.InsertAsync(su); var userRoles = new List(); @@ -98,14 +91,14 @@ public async Task SetSuperAdminPassword(string password) { Id = Guid.NewGuid().ToString("N"), Role = Role.SuperAdmin, - UserId = SuperAdminId + UserId = SystemSettings.SuperAdminId }; userRoles.Add(ursa); var ura = new UserRole() { Id = Guid.NewGuid().ToString("N"), Role = Role.Admin, - UserId = SuperAdminId + UserId = SystemSettings.SuperAdminId }; userRoles.Add(ura); @@ -116,20 +109,20 @@ public async Task SetSuperAdminPassword(string password) public async Task HasSuperAdmin() { - var admin = await _userRepository.GetAsync(SuperAdminId); + var admin = await _userRepository.GetAsync(SystemSettings.SuperAdminId); return admin != null; } public async Task InitDefaultEnvironment() { - var env = await _settingRepository.GetAsync(DefaultEnvironmentKey); + var env = await _settingRepository.GetAsync(SystemSettings.DefaultEnvironmentKey); if (env == null) { var setting = new Setting { - Id = DefaultEnvironmentKey, - Value = DefaultEnvironment, + Id = SystemSettings.DefaultEnvironmentKey, + Value = SystemSettings.DefaultEnvironment, CreateTime = DateTime.Now }; await _settingRepository.InsertAsync(setting); @@ -149,63 +142,9 @@ public void Dispose() public async Task GetEnvironmentList() { - var env = await _settingRepository.GetAsync(DefaultEnvironmentKey); + var env = await _settingRepository.GetAsync(SystemSettings.DefaultEnvironmentKey); return env?.Value?.ToUpper().Split(',') ?? []; } - - /// - /// 如果 配置文件或者环境变量没配置 JwtSetting:SecurityKey 则生成一个存库 - /// - /// - public bool TryInitJwtSecret() - { - var jwtSecretFromConfig = Global.Config["JwtSetting:SecurityKey"]; - if (string.IsNullOrEmpty(jwtSecretFromConfig)) - { - var jwtSecretSetting = _settingRepository.GetAsync(DefaultEnvironmentKey).Result; - if (jwtSecretSetting == null) - { - var setting = new Setting - { - Id = DefaultJwtSecretKey, - Value = GenreateJwtSecretKey(), - CreateTime = DateTime.Now - }; - - try - { - _ = _settingRepository.InsertAsync(setting).Result; - return true; - } - catch (Exception e) - { - //处理异常,防止多个实例第一次启动的时候,并发生成key值,发生异常,导致服务起不来 - Console.WriteLine(e); - } - - return false; - } - } - return true; - } - - public string GetJwtTokenSecret() - { - var jwtSecretSetting = _settingRepository.GetAsync(DefaultEnvironmentKey).Result; - return jwtSecretSetting?.Value; - } - - /// - /// 生成一个 jwt 加密的 key ,38位 - /// - /// - private string GenreateJwtSecretKey() - { - var guid1 = Guid.NewGuid().ToString("n"); - var guid2 = Guid.NewGuid().ToString("n"); - - return guid1.Substring(0, 19) + guid2.Substring(0, 19); - } } } diff --git a/src/AgileConfig.Server.Service/SystemInitializationService.cs b/src/AgileConfig.Server.Service/SystemInitializationService.cs new file mode 100644 index 00000000..78c8646a --- /dev/null +++ b/src/AgileConfig.Server.Service/SystemInitializationService.cs @@ -0,0 +1,59 @@ +using System; +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.IService; + +namespace AgileConfig.Server.Service; + +public class SystemInitializationService(ISysInitRepository sysInitRepository):ISystemInitializationService +{ + /// + /// 如果 配置文件或者环境变量没配置 JwtSetting:SecurityKey 则生成一个存库 + /// + /// + public bool TryInitJwtSecret() + { + var jwtSecretFromConfig = Global.Config["JwtSetting:SecurityKey"]; + if (string.IsNullOrEmpty(jwtSecretFromConfig)) + { + var jwtSecretSetting = sysInitRepository.GetJwtTokenSecret(); + if (jwtSecretSetting == null) + { + var setting = new Setting + { + Id = SystemSettings.DefaultJwtSecretKey, + Value = GenerateJwtSecretKey(), + CreateTime = DateTime.Now + }; + + try + { + sysInitRepository.SaveInitSetting(setting); + return true; + } + catch (Exception e) + { + //处理异常,防止多个实例第一次启动的时候,并发生成key值,发生异常,导致服务起不来 + Console.WriteLine(e); + } + + return false; + } + } + + return true; + } + + /// + /// 生成一个 jwt 加密的 key ,38位 + /// + /// + private static string GenerateJwtSecretKey() + { + var guid1 = Guid.NewGuid().ToString("n"); + var guid2 = Guid.NewGuid().ToString("n"); + + return guid1[..19] + guid2[..19]; + } +} \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs index 1886f35f..a73453f9 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs @@ -8,6 +8,7 @@ using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; using System.Linq; +using AgileConfig.Server.Common; using AgileConfig.Server.IService; using Microsoft.Extensions.DependencyInjection; @@ -193,9 +194,9 @@ public async Task SetAdminPasswordTest() Assert.IsNotNull(list); Assert.AreEqual(2, list.Count); - var pass = list.FirstOrDefault(s => s.Id == SettingService.SuperAdminUserName); + var pass = list.FirstOrDefault(s => s.Id == SystemSettings.SuperAdminUserName); Assert.IsNotNull(pass); - var salt = list.FirstOrDefault(s => s.Id == SettingService.SuperAdminId); + var salt = list.FirstOrDefault(s => s.Id == SystemSettings.SuperAdminId); Assert.IsNotNull(salt); } From e37858c01c3eb90499703e413c786c35f2ec9f21 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Wed, 3 Jan 2024 02:54:46 +0800 Subject: [PATCH 20/45] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=9C=A8=20freesql=20?= =?UTF-8?q?=E4=B8=8B=E7=9A=84=E4=B8=80=E4=BA=9B=E9=97=AE=E9=A2=98=E3=80=82?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E7=9A=84=E8=AF=A5=E5=88=A0=E9=99=A4=E5=9F=BA?= =?UTF-8?q?=E6=9C=AC=E8=83=BD=E7=94=A8=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AgileConfig.sln | 15 +- .../Controllers/ServerNodeController.cs | 19 ++- .../appsettings.Development.json | 8 +- .../appsettings.json | 3 - .../IRepository.cs | 2 +- .../AgileConfig.Server.Data.Freesql.csproj | 3 +- .../EnvFreeSqlFactory.cs | 7 +- .../FreeSQL.cs | 5 + .../FreesqlRepository.cs | 4 +- .../ServiceCollectionExt.cs | 2 +- .../SysInitRepository.cs | 2 +- ...fig.Server.Data.Repository.Selector.csproj | 15 ++ .../RepositoryExtension.cs | 151 ++++++++++++++++++ .../ConfigService.cs | 5 +- 14 files changed, 216 insertions(+), 25 deletions(-) create mode 100644 src/AgileConfig.Server.Data.Repository.Selector/AgileConfig.Server.Data.Repository.Selector.csproj create mode 100644 src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs diff --git a/AgileConfig.sln b/AgileConfig.sln index 9c9334c3..cc090078 100644 --- a/AgileConfig.sln +++ b/AgileConfig.sln @@ -38,13 +38,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.CommonTe EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.OIDC", "src\AgileConfig.Server.OIDC\AgileConfig.Server.OIDC.csproj", "{E49A2006-6D07-4434-AEC1-27E356A767AE}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Mongodb", "src\AgileConfig.Server.Data.Mongodb\AgileConfig.Server.Data.Mongodb.csproj", "{4803646E-8327-4F69-8BA5-2244CB58BBA2}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.Data.Mongodb", "src\AgileConfig.Server.Data.Mongodb\AgileConfig.Server.Data.Mongodb.csproj", "{4803646E-8327-4F69-8BA5-2244CB58BBA2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Abstraction", "src\AgileConfig.Server.Data.Abstraction\AgileConfig.Server.Data.Abstraction.csproj", "{E8101403-72C9-40FB-BCEE-16ED5C23A495}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.Data.Abstraction", "src\AgileConfig.Server.Data.Abstraction\AgileConfig.Server.Data.Abstraction.csproj", "{E8101403-72C9-40FB-BCEE-16ED5C23A495}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Repository.Freesql", "src\AgileConfig.Server.Data.Repository.Freesql\AgileConfig.Server.Data.Repository.Freesql.csproj", "{955F64CC-9EAC-4563-804D-6E2CF9547357}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.Data.Repository.Freesql", "src\AgileConfig.Server.Data.Repository.Freesql\AgileConfig.Server.Data.Repository.Freesql.csproj", "{955F64CC-9EAC-4563-804D-6E2CF9547357}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Repository.Mongodb", "src\AgileConfig.Server.Data.Repository.Mongodb\AgileConfig.Server.Data.Repository.Mongodb.csproj", "{C6B7A5A6-7287-4A20-9336-EBE82A5256F1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.Data.Repository.Mongodb", "src\AgileConfig.Server.Data.Repository.Mongodb\AgileConfig.Server.Data.Repository.Mongodb.csproj", "{C6B7A5A6-7287-4A20-9336-EBE82A5256F1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Repository.Selector", "src\AgileConfig.Server.Data.Repository.Selector\AgileConfig.Server.Data.Repository.Selector.csproj", "{15089E5A-12E4-4953-BA35-0CBB2B1189C0}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -112,6 +114,10 @@ Global {C6B7A5A6-7287-4A20-9336-EBE82A5256F1}.Debug|Any CPU.Build.0 = Debug|Any CPU {C6B7A5A6-7287-4A20-9336-EBE82A5256F1}.Release|Any CPU.ActiveCfg = Release|Any CPU {C6B7A5A6-7287-4A20-9336-EBE82A5256F1}.Release|Any CPU.Build.0 = Release|Any CPU + {15089E5A-12E4-4953-BA35-0CBB2B1189C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {15089E5A-12E4-4953-BA35-0CBB2B1189C0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {15089E5A-12E4-4953-BA35-0CBB2B1189C0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {15089E5A-12E4-4953-BA35-0CBB2B1189C0}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -132,6 +138,7 @@ Global {E8101403-72C9-40FB-BCEE-16ED5C23A495} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {955F64CC-9EAC-4563-804D-6E2CF9547357} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {C6B7A5A6-7287-4A20-9336-EBE82A5256F1} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} + {15089E5A-12E4-4953-BA35-0CBB2B1189C0} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {7F10DB58-5B6F-4EAC-994F-14E8046B306F} diff --git a/src/AgileConfig.Server.Apisite/Controllers/ServerNodeController.cs b/src/AgileConfig.Server.Apisite/Controllers/ServerNodeController.cs index 53c2eb70..23058edf 100644 --- a/src/AgileConfig.Server.Apisite/Controllers/ServerNodeController.cs +++ b/src/AgileConfig.Server.Apisite/Controllers/ServerNodeController.cs @@ -32,7 +32,7 @@ public ServerNodeController(IServerNodeService serverNodeService, [TypeFilter(typeof(PremissionCheckAttribute), Arguments = new object[] { "Node.Add", Functions.Node_Add })] [HttpPost] - public async Task Add([FromBody]ServerNodeVM model) + public async Task Add([FromBody] ServerNodeVM model) { if (model == null) { @@ -64,7 +64,7 @@ public async Task Add([FromBody]ServerNodeVM model) TinyEventBus.Instance.Fire(EventKeys.ADD_NODE_SUCCESS, param); await _remoteServerNodeProxy.TestEchoAsync(node.Id); } - + return Json(new { data = node, @@ -75,7 +75,7 @@ public async Task Add([FromBody]ServerNodeVM model) [TypeFilter(typeof(PremissionCheckAttribute), Arguments = new object[] { "Node.Delete", Functions.Node_Delete })] [HttpPost] - public async Task Delete([FromBody]ServerNodeVM model) + public async Task Delete([FromBody] ServerNodeVM model) { if (Appsettings.IsPreviewMode) { @@ -120,10 +120,21 @@ public async Task All() { var nodes = await _serverNodeService.GetAllNodesAsync(); + var vms = nodes.OrderBy(x => x.CreateTime).Select(x => + { + return new ServerNodeVM + { + Address = x.Id, + Remark = x.Remark, + LastEchoTime = x.LastEchoTime, + Status = x.Status + }; + }); + return Json(new { success = true, - data = nodes.OrderBy(n => n.CreateTime) + data = vms }); } } diff --git a/src/AgileConfig.Server.Apisite/appsettings.Development.json b/src/AgileConfig.Server.Apisite/appsettings.Development.json index 8855c93a..7a6779ab 100644 --- a/src/AgileConfig.Server.Apisite/appsettings.Development.json +++ b/src/AgileConfig.Server.Apisite/appsettings.Development.json @@ -14,10 +14,10 @@ "pathBase": "", //使用反向代理的时候,或许需要修改这个值 /xxx 必须/开头 "adminConsole": true, "cluster": false, // 集群模式:服务启动后自动加入节点列表,服务启动的时候会获取容器的ip,端口默认5000,适合 docker compose 环境使用 - "preview_mode": true, + "preview_mode": false, "db": { - "provider": "mongodb", //sqlite,mysql,sqlserver,npgsql,oracle,mongodb - "conn": "mongodb://localhost:27017,localhost:37017/AgileConfig", + "provider": "sqlite", //sqlite,mysql,sqlserver,npgsql,oracle,mongodb + "conn": "Data Source=agile_config.db", //"provider": "sqlserver", //"conn": "Encrypt=True;TrustServerCertificate=True;Persist Security Info = False; User ID =dev; Password =dev@123; Initial Catalog =agile_config; Server =192.168.18.82" //"provider": "npgsql", @@ -26,6 +26,8 @@ //"conn": "user id=CLINIC;password=CLINIC;data source=192.168.0.91/orcl" //"provider": "mysql", //"conn": "Database=agile_config;Data Source=192.168.0.125;User Id=root;Password=x;port=13306;Allow User Variables=true;", + //"provider": "mongodb", + //"conn": "mongodb://localhost:27017,localhost:37017/AgileConfig", "env": { "TEST": { "provider": "sqlite", //sqlite,mysql,sqlserver,npgsql,oracle diff --git a/src/AgileConfig.Server.Apisite/appsettings.json b/src/AgileConfig.Server.Apisite/appsettings.json index 9940e82b..8227ccb6 100644 --- a/src/AgileConfig.Server.Apisite/appsettings.json +++ b/src/AgileConfig.Server.Apisite/appsettings.json @@ -18,9 +18,6 @@ "db": { "provider": "", //sqlite,mysql,sqlserver,npgsql,oracle,mongodb "conn": "", - //"conn": "Data Source=agile_config.db" - //"conn": "Persist Security Info = False; User ID =dev; Password =dev@123; Initial Catalog =agile_config; Server =." - //"conn": "mongodb://user:password@localhost:27017,localhost:37017/database-name?authSource=admin" "env": { "TEST": { "provider": "", //sqlite,mysql,sqlserver,npgsql,oracle diff --git a/src/AgileConfig.Server.Data.Abstraction/IRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IRepository.cs index 062393d4..584dc22a 100644 --- a/src/AgileConfig.Server.Data.Abstraction/IRepository.cs +++ b/src/AgileConfig.Server.Data.Abstraction/IRepository.cs @@ -12,7 +12,7 @@ public interface IRepository : IDisposable where T : IEntity Task UpdateAsync(IList entities); Task DeleteAsync(T1 id); - + Task DeleteAsync(T entity); Task DeleteAsync(IList entities); diff --git a/src/AgileConfig.Server.Data.Freesql/AgileConfig.Server.Data.Freesql.csproj b/src/AgileConfig.Server.Data.Freesql/AgileConfig.Server.Data.Freesql.csproj index f4a5e629..d6fec744 100644 --- a/src/AgileConfig.Server.Data.Freesql/AgileConfig.Server.Data.Freesql.csproj +++ b/src/AgileConfig.Server.Data.Freesql/AgileConfig.Server.Data.Freesql.csproj @@ -1,7 +1,8 @@  - net8.0 + enable + net8.0 diff --git a/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs b/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs index 78c5f80d..44cff2c5 100644 --- a/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs +++ b/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs @@ -4,14 +4,15 @@ namespace AgileConfig.Server.Data.Freesql { public class EnvFreeSqlFactory : IFreeSqlFactory { - private readonly IEnvAccessor _envAccessor; + private readonly string _env; public EnvFreeSqlFactory(IEnvAccessor envAccessor) { - _envAccessor = envAccessor; + _env = envAccessor.Env; } + public IFreeSql Create() { - return FreeSQL.GetInstanceByEnv(_envAccessor.Env); + return FreeSQL.GetInstanceByEnv(_env); } } } diff --git a/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs b/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs index c7f42a07..ade93a16 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs @@ -37,6 +37,11 @@ public static IFreeSql GetInstanceByEnv(string env) var provider = Global.Config[$"db:env:{env}:provider"]; var conn = Global.Config[$"db:env:{env}:conn"]; + if (string.IsNullOrEmpty(provider)) + { + return Instance; + } + var key = provider; if (_envFreesqls.ContainsKey(key)) diff --git a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs index c6e93d84..9a8fed47 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs @@ -37,7 +37,7 @@ public Task DeleteAsync(IList entities) return _repository.DeleteAsync(entities); } - public Task GetAsync(T1 id) + public Task GetAsync(T1 id) { return _repository.Where(x => x.Id.Equals(id)).ToOneAsync(); } @@ -91,7 +91,7 @@ private Expression> Sort(string defaultSortField) return defaultSort; } - public async Task CountAsync(Expression> exp = null) + public async Task CountAsync(Expression>? exp = null) { return await (exp == null ? _repository.Select.CountAsync() : _repository.Select.Where(exp).CountAsync()); } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceCollectionExt.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceCollectionExt.cs index 281ddbbe..9a6c4e79 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceCollectionExt.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceCollectionExt.cs @@ -22,7 +22,7 @@ public static void AddFreeSqlRepository(this IServiceCollection sc) sc.AddScoped(); sc.AddScoped(); sc.AddScoped(); - sc.AddScoped(); + sc.AddScoped(); sc.AddSingleton(); } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs index 3f8996f0..f5b2f8e4 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs @@ -16,6 +16,6 @@ public class SysInitRepository : ISysInitRepository public void SaveInitSetting(Setting setting) { - FreeSQL.Instance.Insert(setting); + FreeSQL.Instance.Insert(setting).ExecuteAffrows(); } } \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Selector/AgileConfig.Server.Data.Repository.Selector.csproj b/src/AgileConfig.Server.Data.Repository.Selector/AgileConfig.Server.Data.Repository.Selector.csproj new file mode 100644 index 00000000..9aad88be --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Selector/AgileConfig.Server.Data.Repository.Selector.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + enable + enable + + + + + + + + + diff --git a/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs b/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs new file mode 100644 index 00000000..5f88048a --- /dev/null +++ b/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs @@ -0,0 +1,151 @@ +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Freesql; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using System.Security.Cryptography; + +namespace AgileConfig.Server.Data.Repository.Selector +{ + public static class RepositoryExtension + { + public static IServiceCollection AddRepositories(this IServiceCollection sc) + { + sc.AddFreeRepository(); + + var config = Global.Config; + var defaultProvider = config["db:provider"]; + + if (string.IsNullOrEmpty(defaultProvider)) + { + throw new ArgumentNullException(nameof(defaultProvider)); + } + + if (defaultProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) + { + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddSingleton(); + } + else + { + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddSingleton(); + } + + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + sc.AddScoped(); + + sc.AddScoped>(sp => env => + { + string envProvider = GetEnvProvider(env, config, defaultProvider); + + if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) + { + return sp.GetService(); + } + else + { + var envAccssor = new ManualEnvAccessor(env); + var factory = new EnvFreeSqlFactory(envAccssor); + return new Freesql.ConfigPublishedRepository(factory); + } + }); + + sc.AddScoped>(sp => env => + { + string envProvider = GetEnvProvider(env, config, defaultProvider); + + if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) + { + return sp.GetService(); + } + else + { + var envAccssor = new ManualEnvAccessor(env); + var factory = new EnvFreeSqlFactory(envAccssor); + return new Freesql.ConfigRepository(factory); + } + }); + + sc.AddScoped>(sp => env => + { + string envProvider = GetEnvProvider(env, config, defaultProvider); + + if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) + { + return sp.GetService(); + } + else + { + var envAccssor = new ManualEnvAccessor(env); + var factory = new EnvFreeSqlFactory(envAccssor); + return new Freesql.PublishDetailRepository(factory); + } + }); + + sc.AddScoped((Func>)(sp => env => + { + string envProvider = GetEnvProvider(env, config, defaultProvider); + + if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) + { + return sp.GetService(); + } + else + { + var envAccssor = new ManualEnvAccessor(env); + var factory = new EnvFreeSqlFactory(envAccssor); + return new Freesql.PublishTimelineRepository(factory); + } + })); + + return sc; + } + + private static string GetEnvProvider(string env, IConfiguration config, string defaultProvider) + { + var envProviderKey = $"db:env:{env}:provider"; + var envProvider = config[envProviderKey]; + if (string.IsNullOrEmpty(envProvider)) + { + // use default provider + envProvider = defaultProvider; + } + + return envProvider; + } + + class ManualEnvAccessor : IEnvAccessor + { + string _env; + public ManualEnvAccessor(string env) + { + _env = env; + } + public string Env => _env; + } + } +} diff --git a/src/AgileConfig.Server.Service/ConfigService.cs b/src/AgileConfig.Server.Service/ConfigService.cs index 1f6db9ec..c93f70a9 100644 --- a/src/AgileConfig.Server.Service/ConfigService.cs +++ b/src/AgileConfig.Server.Service/ConfigService.cs @@ -466,7 +466,8 @@ public void Dispose() waitPublishConfigs = waitPublishConfigs.Where(x => ids.Contains(x.Id)).ToList(); } //这里默认admin console 实例只部署一个,如果部署多个同步操作,高并发的时候这个version会有问题 - var versionMax = (await _publishTimelineRepository.QueryAsync(x => x.AppId == appId)).Max(x => x.Version); + var publishList = await _publishTimelineRepository.QueryAsync(x => x.AppId == appId); + var versionMax = publishList.Any() ? publishList.Max(x => x.Version) : 0; var user = await _userService.GetUserAsync(operatorr); @@ -732,7 +733,7 @@ public async Task RollbackAsync(string publishTimelineId, string env) //删除发布时间轴version之后的版本 var deletePublishTimeLineItems = await _publishTimelineRepository.QueryAsync(x => x.AppId == appId && x.Env == env && x.Version > version); await _publishTimelineRepository.DeleteAsync(deletePublishTimeLineItems); - var deletePublishDetailItems = await _publishDetailRepository.QueryAsync(x => x.PublishTimelineId == publishTimelineId && x.Env == env); + var deletePublishDetailItems = await _publishDetailRepository.QueryAsync(x => x.AppId == appId && x.Env == env && x.Version > version); await _publishDetailRepository.DeleteAsync(deletePublishDetailItems); ClearAppPublishedConfigsMd5Cache(appId, env); From 4a6d8eee69fe0fa27ec2c5572c37ad0675d15a58 Mon Sep 17 00:00:00 2001 From: Minjie ZHOU Date: Wed, 3 Jan 2024 18:13:15 +0800 Subject: [PATCH 21/45] Refactor ConfigService; --- .../FreesqlRepository.cs | 9 +- .../IServiceInfoService.cs | 3 + .../ConfigService.cs | 144 ++++++++++-------- .../ServiceHealthCheckService.cs | 8 +- .../ServiceInfoService.cs | 10 +- 5 files changed, 100 insertions(+), 74 deletions(-) diff --git a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs index 9a8fed47..628cf8c9 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs @@ -3,7 +3,6 @@ using FreeSql; using System; using System.Collections.Generic; -using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; @@ -12,8 +11,14 @@ namespace AgileConfig.Server.Data.Freesql public class FreesqlRepository : IRepository where T : class, IEntity { private readonly IBaseRepository _repository; + + private readonly IFreeSqlFactory _freeSqlFactory; + + protected IFreeSqlFactory FreeSqlFactory => _freeSqlFactory; + public FreesqlRepository(IFreeSqlFactory freeFactory) { + _freeSqlFactory = freeFactory; _repository = freeFactory.Create().GetRepository(); } @@ -86,7 +91,7 @@ private Expression> Sort(string defaultSortField) } var parameter = Expression.Parameter(typeof(T), "__q"); var memberExpress = Expression.Property(parameter, property); - return Expression.Lambda>(memberExpress, parameter); + return Expression.Lambda>(memberExpress, parameter); } return defaultSort; } diff --git a/src/AgileConfig.Server.IService/IServiceInfoService.cs b/src/AgileConfig.Server.IService/IServiceInfoService.cs index 55108406..5712b4f8 100644 --- a/src/AgileConfig.Server.IService/IServiceInfoService.cs +++ b/src/AgileConfig.Server.IService/IServiceInfoService.cs @@ -1,6 +1,7 @@ using AgileConfig.Server.Data.Entity; using System; using System.Collections.Generic; +using System.Linq.Expressions; using System.Threading.Tasks; namespace AgileConfig.Server.IService @@ -23,6 +24,8 @@ public interface IServiceInfoService: IDisposable Task ServicesMD5Cache(); + Task> QueryAsync(Expression> exp); + void ClearCache(); } } diff --git a/src/AgileConfig.Server.Service/ConfigService.cs b/src/AgileConfig.Server.Service/ConfigService.cs index c93f70a9..2dca61bf 100644 --- a/src/AgileConfig.Server.Service/ConfigService.cs +++ b/src/AgileConfig.Server.Service/ConfigService.cs @@ -20,28 +20,28 @@ public class ConfigService : IConfigService private readonly IAppService _appService; private readonly ISettingService _settingService; private readonly IUserService _userService; - private readonly IConfigRepository _configRepository; - private readonly IConfigPublishedRepository _configPublishedRepository; - private readonly IPublishDetailRepository _publishDetailRepository; - private readonly IPublishTimelineRepository _publishTimelineRepository; + private readonly Func _configRepositoryAccessor; + private readonly Func _configPublishedRepositoryAccessor; + private readonly Func _publishDetailRepositoryAccessor; + private readonly Func _publishTimelineRepositoryAccsssor; public ConfigService(IMemoryCache memoryCache, IAppService appService, ISettingService settingService, IUserService userService, - IConfigRepository configRepository, - IConfigPublishedRepository configPublishedRepository, - IPublishDetailRepository publishDetailRepository, - IPublishTimelineRepository publishTimelineRepository) + Func configRepository, + Func configPublishedRepository, + Func publishDetailRepository, + Func publishTimelineRepository) { _memoryCache = memoryCache; _appService = appService; _settingService = settingService; _userService = userService; - _configRepository = configRepository; - _configPublishedRepository = configPublishedRepository; - _publishDetailRepository = publishDetailRepository; - _publishTimelineRepository = publishTimelineRepository; + _configRepositoryAccessor = configRepository; + _configPublishedRepositoryAccessor = configPublishedRepository; + _publishDetailRepositoryAccessor = publishDetailRepository; + _publishTimelineRepositoryAccsssor = publishTimelineRepository; } public async Task IfEnvEmptySetDefaultAsync(string env) @@ -67,14 +67,14 @@ public async Task AddAsync(Config config, string env) config.Value = ""; } - await _configRepository.InsertAsync(config); + await _configRepositoryAccessor(env).InsertAsync(config); return true; } public async Task UpdateAsync(Config config, string env) { - await _configRepository.UpdateAsync(config); + await _configRepositoryAccessor(env).UpdateAsync(config); return true; } @@ -83,7 +83,7 @@ public async Task UpdateAsync(List configs, string env) { foreach (var item in configs) { - await _configRepository.UpdateAsync(item); + await _configRepositoryAccessor(env).UpdateAsync(item); } return true; @@ -91,9 +91,10 @@ public async Task UpdateAsync(List configs, string env) public async Task CancelEdit(List ids, string env) { + var configRepository = _configRepositoryAccessor(env); foreach (var configId in ids) { - var config = await _configRepository.GetAsync(configId); + var config = await configRepository.GetAsync(configId); ; if (config == null) { @@ -107,7 +108,7 @@ public async Task CancelEdit(List ids, string env) if (config.EditStatus == EditStatus.Add) { - await _configRepository.DeleteAsync(config); + await configRepository.DeleteAsync(config); } if (config.EditStatus == EditStatus.Deleted || config.EditStatus == EditStatus.Edit) @@ -129,7 +130,7 @@ public async Task CancelEdit(List ids, string env) config.OnlineStatus = OnlineStatus.Online; } - await _configRepository.UpdateAsync(config); + await configRepository.UpdateAsync(config); } } @@ -138,10 +139,11 @@ public async Task CancelEdit(List ids, string env) public async Task DeleteAsync(Config config, string env) { - config = await _configRepository.GetAsync(config.Id); + var configRepository = _configRepositoryAccessor(env); + config = await configRepository.GetAsync(config.Id); if (config != null) { - await _configRepository.DeleteAsync(config); + await configRepository.DeleteAsync(config); } return true; @@ -149,10 +151,11 @@ public async Task DeleteAsync(Config config, string env) public async Task DeleteAsync(string configId, string env) { - var config = await _configRepository.GetAsync(configId); + var configRepository = _configRepositoryAccessor(env); + var config = await configRepository.GetAsync(configId); if (config != null) { - await _configRepository.DeleteAsync(config); + await configRepository.DeleteAsync(config); } return true; @@ -160,14 +163,14 @@ public async Task DeleteAsync(string configId, string env) public async Task GetAsync(string id, string env) { - var config = await _configRepository.GetAsync(id); + var config = await _configRepositoryAccessor(env).GetAsync(id); return config; } public async Task> GetAllConfigsAsync(string env) { - return await _configRepository.QueryAsync(c => c.Status == ConfigStatus.Enabled && c.Env == env); + return await _configRepositoryAccessor(env).QueryAsync(c => c.Status == ConfigStatus.Enabled && c.Env == env); } public async Task GetByAppIdKeyEnv(string appId, string group, string key, string env) @@ -188,14 +191,14 @@ public async Task GetByAppIdKeyEnv(string appId, string group, string ke exp.And(exp1); } - var configs = await _configRepository.QueryAsync(exp); + var configs = await _configRepositoryAccessor(env).QueryAsync(exp); return configs.FirstOrDefault(); } public async Task> GetByAppIdAsync(string appId, string env) { - return await _configRepository.QueryAsync(c => + return await _configRepositoryAccessor(env).QueryAsync(c => c.AppId == appId && c.Status == ConfigStatus.Enabled && c.Env == env ); } @@ -218,7 +221,7 @@ public async Task> Search(string appId, string group, string key, s exp = exp.And(c => c.Key.Contains(key)); } - return await _configRepository.QueryAsync(exp); + return await _configRepositoryAccessor(env).QueryAsync(exp); } public async Task CountEnabledConfigsAsync() @@ -236,7 +239,7 @@ public async Task CountEnabledConfigsAsync() public async Task CountEnabledConfigsAsync(string env) { //这里计算所有的配置 - var q = await _configRepository.QueryAsync(c => c.Status == ConfigStatus.Enabled && c.Env == env); + var q = await _configRepositoryAccessor(env).QueryAsync(c => c.Status == ConfigStatus.Enabled && c.Env == env); return q.Count; } @@ -268,7 +271,7 @@ public string GenerateKey(ConfigPublished config) /// public async Task AppPublishedConfigsMd5(string appId, string env) { - var configs = await _configPublishedRepository.QueryAsync(c => + var configs = await _configPublishedRepositoryAccessor(env).QueryAsync(c => c.AppId == appId && c.Status == ConfigStatus.Enabled && c.Env == env ); @@ -334,7 +337,7 @@ public async Task AddRangeAsync(List configs, string env) } }); - await _configRepository.InsertAsync(configs); + await _configRepositoryAccessor(env).InsertAsync(configs); ClearAppPublishedConfigsMd5Cache(configs.First().AppId, env); ClearAppPublishedConfigsMd5CacheWithInheritanced(configs.First().AppId, env); @@ -454,7 +457,12 @@ public void Dispose() await _lock.WaitAsync(); try { - var waitPublishConfigs = await _configRepository.QueryAsync(x => + var configRepository = _configRepositoryAccessor(env); + var publishTimelineRepository = _publishTimelineRepositoryAccsssor(env); + var configPublishedRepository = _configPublishedRepositoryAccessor(env); + var publishDetailRepository = _publishDetailRepositoryAccessor(env); + + var waitPublishConfigs = await configRepository.QueryAsync(x => x.AppId == appId && x.Env == env && x.Status == ConfigStatus.Enabled && @@ -466,7 +474,7 @@ public void Dispose() waitPublishConfigs = waitPublishConfigs.Where(x => ids.Contains(x.Id)).ToList(); } //这里默认admin console 实例只部署一个,如果部署多个同步操作,高并发的时候这个version会有问题 - var publishList = await _publishTimelineRepository.QueryAsync(x => x.AppId == appId); + var publishList = await publishTimelineRepository.QueryAsync(x => x.AppId == appId); var versionMax = publishList.Any() ? publishList.Max(x => x.Version) : 0; var user = await _userService.GetUserAsync(operatorr); @@ -515,7 +523,7 @@ public void Dispose() }); //当前发布的配置 - var publishedConfigs = await _configPublishedRepository + var publishedConfigs = await configPublishedRepository .QueryAsync(x => x.Status == ConfigStatus.Enabled && x.AppId == appId && x.Env == env); //复制一份新版本,最后插入发布表 var publishedConfigsCopy = new List(); @@ -591,11 +599,11 @@ public void Dispose() } }); - await _configRepository.UpdateAsync(waitPublishConfigs); - await _publishTimelineRepository.InsertAsync(publishTimelineNode); - await _publishDetailRepository.InsertAsync(publishDetails); - await _configPublishedRepository.UpdateAsync(publishedConfigs); - await _configPublishedRepository.InsertAsync(publishedConfigsCopy); + await configRepository.UpdateAsync(waitPublishConfigs); + await publishTimelineRepository.InsertAsync(publishTimelineNode); + await publishDetailRepository.InsertAsync(publishDetails); + await configPublishedRepository.UpdateAsync(publishedConfigs); + await configPublishedRepository.InsertAsync(publishedConfigsCopy); ClearAppPublishedConfigsMd5Cache(appId, env); ClearAppPublishedConfigsMd5CacheWithInheritanced(appId, env); @@ -614,7 +622,7 @@ public void Dispose() public async Task IsPublishedAsync(string configId, string env) { - var any = await _configPublishedRepository.QueryAsync( + var any = await _configPublishedRepositoryAccessor(env).QueryAsync( x => x.ConfigId == configId && x.Env == env && x.Status == ConfigStatus.Enabled); @@ -625,7 +633,7 @@ public async Task IsPublishedAsync(string configId, string env) public async Task> GetPublishDetailByPublishTimelineIdAsync(string publishTimelineId, string env) { - var list = await _publishDetailRepository + var list = await _publishDetailRepositoryAccessor(env) .QueryAsync(x => x.PublishTimelineId == publishTimelineId && x.Env == env); return list; @@ -633,7 +641,7 @@ public async Task> GetPublishDetailByPublishTimelineIdAsync( public async Task GetPublishTimeLineNodeAsync(string publishTimelineId, string env) { - var one = (await _publishTimelineRepository.QueryAsync(x => x.Id == publishTimelineId && x.Env == env)) + var one = (await _publishTimelineRepositoryAccsssor(env).QueryAsync(x => x.Id == publishTimelineId && x.Env == env)) .FirstOrDefault(); return one; @@ -641,28 +649,28 @@ public async Task GetPublishTimeLineNodeAsync(string publishTim public async Task> GetPublishTimelineHistoryAsync(string appId, string env) { - var list = await _publishTimelineRepository.QueryAsync(x => x.AppId == appId && x.Env == env); + var list = await _publishTimelineRepositoryAccsssor(env).QueryAsync(x => x.AppId == appId && x.Env == env); return list; } public async Task> GetPublishDetailListAsync(string appId, string env) { - var list = await _publishDetailRepository.QueryAsync(x => x.AppId == appId && x.Env == env); + var list = await _publishDetailRepositoryAccessor(env).QueryAsync(x => x.AppId == appId && x.Env == env); return list; } public async Task> GetConfigPublishedHistory(string configId, string env) { - var list = await _publishDetailRepository.QueryAsync(x => x.ConfigId == configId && x.Env == env); + var list = await _publishDetailRepositoryAccessor(env).QueryAsync(x => x.ConfigId == configId && x.Env == env); return list; } public async Task> GetPublishedConfigsAsync(string appId, string env) { - var list = await _configPublishedRepository + var list = await _configPublishedRepositoryAccessor(env) .QueryAsync(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env); return list; @@ -670,7 +678,7 @@ public async Task> GetPublishedConfigsAsync(string appId, public async Task GetPublishedConfigAsync(string configId, string env) { - var one = (await _configPublishedRepository.QueryAsync(x => x.ConfigId == configId + var one = (await _configPublishedRepositoryAccessor(env).QueryAsync(x => x.ConfigId == configId && x.Status == ConfigStatus.Enabled && x.Env == env )).FirstOrDefault(); @@ -680,12 +688,18 @@ public async Task GetPublishedConfigAsync(string configId, stri public async Task RollbackAsync(string publishTimelineId, string env) { - var publishNode = (await _publishTimelineRepository.QueryAsync(x => x.Id == publishTimelineId && x.Env == env)).FirstOrDefault(); + var configRepository = _configRepositoryAccessor(env); + var publishTimelineRepository = _publishTimelineRepositoryAccsssor(env); + var configPublishedRepository = _configPublishedRepositoryAccessor(env); + var publishDetailRepository = _publishDetailRepositoryAccessor(env); + + + var publishNode = (await publishTimelineRepository.QueryAsync(x => x.Id == publishTimelineId && x.Env == env)).FirstOrDefault(); var version = publishNode.Version; var appId = publishNode.AppId; - var latest = (await _publishTimelineRepository.QueryAsync(x => x.AppId == appId && x.Env == env)) + var latest = (await publishTimelineRepository.QueryAsync(x => x.AppId == appId && x.Env == env)) .OrderByDescending(x => x.Version).FirstOrDefault(); if (latest.Id == publishTimelineId) @@ -694,9 +708,9 @@ public async Task RollbackAsync(string publishTimelineId, string env) return true; } - var publishedConfigs = await _configPublishedRepository + var publishedConfigs = await configPublishedRepository .QueryAsync(x => x.AppId == appId && x.Version == version && x.Env == env); - var currentConfigs = await _configRepository + var currentConfigs = await _configRepositoryAccessor(env) .QueryAsync(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env); //把当前的全部软删除 @@ -705,36 +719,36 @@ public async Task RollbackAsync(string publishTimelineId, string env) item.Status = ConfigStatus.Deleted; } - await _configRepository.UpdateAsync(currentConfigs); + await configRepository.UpdateAsync(currentConfigs); //根据id把所有发布项目设置为启用 var now = DateTime.Now; foreach (var item in publishedConfigs) { - var config = (await _configRepository.QueryAsync(x => x.AppId == appId && x.Id == item.ConfigId)).FirstOrDefault(); + var config = (await configRepository.QueryAsync(x => x.AppId == appId && x.Id == item.ConfigId)).FirstOrDefault(); config.Status = ConfigStatus.Enabled; config.Value = item.Value; config.UpdateTime = now; config.EditStatus = EditStatus.Commit; config.OnlineStatus = OnlineStatus.Online; - await _configRepository.UpdateAsync(config); + await configRepository.UpdateAsync(config); } //删除version之后的版本 - var configPublishedConfigs = await _configPublishedRepository.QueryAsync(x => x.AppId == appId && x.Env == env && x.Version > version); - await _configPublishedRepository.DeleteAsync(configPublishedConfigs); + var configPublishedConfigs = await configPublishedRepository.QueryAsync(x => x.AppId == appId && x.Env == env && x.Version > version); + await configPublishedRepository.DeleteAsync(configPublishedConfigs); //设置为发布状态 foreach (var item in publishedConfigs) { item.Status = ConfigStatus.Enabled; - await _configPublishedRepository.UpdateAsync(item); + await configPublishedRepository.UpdateAsync(item); } //删除发布时间轴version之后的版本 - var deletePublishTimeLineItems = await _publishTimelineRepository.QueryAsync(x => x.AppId == appId && x.Env == env && x.Version > version); - await _publishTimelineRepository.DeleteAsync(deletePublishTimeLineItems); - var deletePublishDetailItems = await _publishDetailRepository.QueryAsync(x => x.AppId == appId && x.Env == env && x.Version > version); - await _publishDetailRepository.DeleteAsync(deletePublishDetailItems); + var deletePublishTimeLineItems = await publishTimelineRepository.QueryAsync(x => x.AppId == appId && x.Env == env && x.Version > version); + await publishTimelineRepository.DeleteAsync(deletePublishTimeLineItems); + var deletePublishDetailItems = await publishDetailRepository.QueryAsync(x => x.AppId == appId && x.Env == env && x.Version > version); + await publishDetailRepository.DeleteAsync(deletePublishDetailItems); ClearAppPublishedConfigsMd5Cache(appId, env); ClearAppPublishedConfigsMd5CacheWithInheritanced(appId, env); @@ -819,7 +833,9 @@ public async Task>> GetKvListAsync(string appI private async Task SaveFromDictAsync(IDictionary dict, string appId, string env, bool isPatch) { - var currentConfigs = await _configRepository + var configRepository = _configRepositoryAccessor(env); + + var currentConfigs = await configRepository .QueryAsync(x => x.AppId == appId && x.Env == env && x.Status == ConfigStatus.Enabled); var addConfigs = new List(); var updateConfigs = new List(); @@ -898,17 +914,17 @@ private async Task SaveFromDictAsync(IDictionary dict, str if (addConfigs.Any()) { - await _configRepository.InsertAsync(addConfigs); + await configRepository.InsertAsync(addConfigs); } if (updateConfigs.Any()) { - await _configRepository.UpdateAsync(updateConfigs); + await configRepository.UpdateAsync(updateConfigs); } if (deleteConfigs.Any()) { - await _configRepository.UpdateAsync(deleteConfigs); + await configRepository.UpdateAsync(deleteConfigs); } return true; diff --git a/src/AgileConfig.Server.Service/ServiceHealthCheckService.cs b/src/AgileConfig.Server.Service/ServiceHealthCheckService.cs index 2c73b6f0..3b0f1df8 100644 --- a/src/AgileConfig.Server.Service/ServiceHealthCheckService.cs +++ b/src/AgileConfig.Server.Service/ServiceHealthCheckService.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using AgileConfig.Server.Common; using AgileConfig.Server.Common.RestClient; -using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.IService; using Microsoft.Extensions.Logging; @@ -13,20 +12,17 @@ public class ServiceHealthCheckService : IServiceHealthCheckService { private readonly ILogger _logger; private readonly IRestClient _restClient; - private readonly IServiceInfoRepository _serviceInfoRepository; private readonly IServiceInfoService _serviceInfoService; public ServiceHealthCheckService( IServiceInfoService serviceInfoService, ILogger logger, - IRestClient restClient, - IServiceInfoRepository serviceInfoRepository + IRestClient restClient ) { _serviceInfoService = serviceInfoService; _logger = logger; _restClient = restClient; - _serviceInfoRepository = serviceInfoRepository; } private int _checkInterval; @@ -124,7 +120,7 @@ public Task StartCheckAsync() while (true) { //没有填写心跳模式,则不做检查 - var services = await _serviceInfoRepository + var services = await _serviceInfoService .QueryAsync(x => x.HeartBeatMode != null && x.HeartBeatMode != ""); foreach (var service in services) { diff --git a/src/AgileConfig.Server.Service/ServiceInfoService.cs b/src/AgileConfig.Server.Service/ServiceInfoService.cs index 49fce178..915ea0dc 100644 --- a/src/AgileConfig.Server.Service/ServiceInfoService.cs +++ b/src/AgileConfig.Server.Service/ServiceInfoService.cs @@ -10,6 +10,7 @@ using AgileConfig.Server.Data.Abstraction; using Microsoft.Extensions.Caching.Memory; using Newtonsoft.Json; +using System.Linq.Expressions; namespace AgileConfig.Server.Service { @@ -18,7 +19,7 @@ public class ServiceInfoService : IServiceInfoService private readonly IMemoryCache _memoryCache; private readonly IServiceInfoRepository _serviceInfoRepository; - public ServiceInfoService(IMemoryCache memoryCache,IServiceInfoRepository serviceInfoRepository) + public ServiceInfoService(IMemoryCache memoryCache, IServiceInfoRepository serviceInfoRepository) { _memoryCache = memoryCache; _serviceInfoRepository = serviceInfoRepository; @@ -131,7 +132,7 @@ public async Task UpdateServiceStatus(ServiceInfo service, ServiceStatus status) service2.Status = status; if (status != ServiceStatus.Unhealthy) { - service2.LastHeartBeat = DateTime.Now; + service2.LastHeartBeat = DateTime.Now; } await _serviceInfoRepository.UpdateAsync(service2); @@ -150,5 +151,10 @@ public void Dispose() { _serviceInfoRepository.Dispose(); } + + public Task> QueryAsync(Expression> exp) + { + return _serviceInfoRepository.QueryAsync(exp); + } } } \ No newline at end of file From cb3529c80fba98d126c1f833d297c13db1549ca8 Mon Sep 17 00:00:00 2001 From: Minjie ZHOU Date: Wed, 3 Jan 2024 18:34:25 +0800 Subject: [PATCH 22/45] Refactor Freesql repositories; --- .../DefaultFreeSqlFactory.cs | 10 ------- .../EnvFreeSqlFactory.cs | 10 ++----- .../FreesqlRepository.cs | 11 ++----- .../IFreeSqlFactory.cs | 2 +- .../ServiceCollectionExt.cs | 7 ++--- .../AppInheritancedRepository.cs | 6 ++-- .../AppRepository.cs | 6 ++-- .../ConfigPublishedRepository.cs | 6 ++-- .../ConfigRepository.cs | 6 ++-- .../PublishDetailRepository.cs | 6 ++-- .../PublishTimelineRepository.cs | 6 ++-- .../ServerNodeRepository.cs | 6 ++-- .../ServiceInfoRepository.cs | 6 ++-- .../SettingRepository.cs | 6 ++-- .../SysLogRepository.cs | 7 +++-- .../UserAppAuthRepository.cs | 7 +++-- .../UserRepository.cs | 6 +++- .../UserRoleRepository.cs | 6 ++-- .../RepositoryExtension.cs | 30 +++++-------------- 19 files changed, 71 insertions(+), 79 deletions(-) delete mode 100644 src/AgileConfig.Server.Data.Freesql/DefaultFreeSqlFactory.cs diff --git a/src/AgileConfig.Server.Data.Freesql/DefaultFreeSqlFactory.cs b/src/AgileConfig.Server.Data.Freesql/DefaultFreeSqlFactory.cs deleted file mode 100644 index 56450f79..00000000 --- a/src/AgileConfig.Server.Data.Freesql/DefaultFreeSqlFactory.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace AgileConfig.Server.Data.Freesql -{ - public class DefaultFreeSqlFactory : IFreeSqlFactory - { - public IFreeSql Create() - { - return FreeSQL.Instance; - } - } -} diff --git a/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs b/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs index 44cff2c5..8007f65a 100644 --- a/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs +++ b/src/AgileConfig.Server.Data.Freesql/EnvFreeSqlFactory.cs @@ -4,15 +4,9 @@ namespace AgileConfig.Server.Data.Freesql { public class EnvFreeSqlFactory : IFreeSqlFactory { - private readonly string _env; - public EnvFreeSqlFactory(IEnvAccessor envAccessor) + public IFreeSql Create(string env) { - _env = envAccessor.Env; - } - - public IFreeSql Create() - { - return FreeSQL.GetInstanceByEnv(_env); + return FreeSQL.GetInstanceByEnv(env); } } } diff --git a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs index 628cf8c9..df3c30e5 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs @@ -8,18 +8,13 @@ namespace AgileConfig.Server.Data.Freesql { - public class FreesqlRepository : IRepository where T : class, IEntity + public abstract class FreesqlRepository : IRepository where T : class, IEntity { private readonly IBaseRepository _repository; - private readonly IFreeSqlFactory _freeSqlFactory; - - protected IFreeSqlFactory FreeSqlFactory => _freeSqlFactory; - - public FreesqlRepository(IFreeSqlFactory freeFactory) + public FreesqlRepository(IFreeSql freeSql) { - _freeSqlFactory = freeFactory; - _repository = freeFactory.Create().GetRepository(); + _repository = freeSql.GetRepository(); } public Task> AllAsync() diff --git a/src/AgileConfig.Server.Data.Freesql/IFreeSqlFactory.cs b/src/AgileConfig.Server.Data.Freesql/IFreeSqlFactory.cs index 8d1d2600..e7966ed1 100644 --- a/src/AgileConfig.Server.Data.Freesql/IFreeSqlFactory.cs +++ b/src/AgileConfig.Server.Data.Freesql/IFreeSqlFactory.cs @@ -2,6 +2,6 @@ { public interface IFreeSqlFactory { - IFreeSql Create(); + IFreeSql Create(string env); } } \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs b/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs index fe2e4171..94c79d98 100644 --- a/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs +++ b/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs @@ -1,7 +1,4 @@ using Microsoft.Extensions.DependencyInjection; -using System; -using System.Collections.Generic; -using System.Text; namespace AgileConfig.Server.Data.Freesql { @@ -9,8 +6,8 @@ public static class ServiceCollectionExt { public static void AddFreeSqlFactory(this IServiceCollection sc) { - sc.AddKeyedSingleton(""); - sc.AddKeyedSingleton("Env"); + sc.AddSingleton(FreeSQL.Instance); + sc.AddSingleton(); } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs index 069ab2f2..6fd9ece6 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs @@ -1,14 +1,16 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class AppInheritancedRepository : FreesqlRepository, IAppInheritancedRepository { - public AppInheritancedRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) + private readonly IFreeSql freeSql; + + public AppInheritancedRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs index 5ffe46ed..523d159e 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs @@ -1,14 +1,16 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class AppRepository : FreesqlRepository, IAppRepository { - public AppRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) + private readonly IFreeSql freeSql; + + public AppRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs index d2c00f49..5ee7c7c0 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigPublishedRepository.cs @@ -1,14 +1,16 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class ConfigPublishedRepository : FreesqlRepository, IConfigPublishedRepository { - public ConfigPublishedRepository([FromKeyedServices("Env")] IFreeSqlFactory freeSql) : base(freeSql) + private readonly IFreeSql freeSql; + + public ConfigPublishedRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs index 267c2d9d..9917b27a 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs @@ -1,14 +1,16 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class ConfigRepository : FreesqlRepository, IConfigRepository { - public ConfigRepository([FromKeyedServices("Env")]IFreeSqlFactory freeSqlFactory) : base(freeSqlFactory) + private readonly IFreeSql freeSql; + + public ConfigRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs index 57e3b442..8a1bb2eb 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/PublishDetailRepository.cs @@ -1,14 +1,16 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class PublishDetailRepository : FreesqlRepository, IPublishDetailRepository { - public PublishDetailRepository([FromKeyedServices("Env")] IFreeSqlFactory freeSql) : base(freeSql) + private readonly IFreeSql freeSql; + + public PublishDetailRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs index b0a2bc2d..d9ac0b93 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/PublishTimelineRepository.cs @@ -1,14 +1,16 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class PublishTimelineRepository : FreesqlRepository, IPublishTimelineRepository { - public PublishTimelineRepository([FromKeyedServices("Env")] IFreeSqlFactory freeSql) : base(freeSql) + private readonly IFreeSql freeSql; + + public PublishTimelineRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs index f07940d9..9a7b1644 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs @@ -1,14 +1,16 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class ServerNodeRepository : FreesqlRepository, IServerNodeRepository { - public ServerNodeRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) + private readonly IFreeSql freeSql; + + public ServerNodeRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs index 9a09b1b9..47c60d1e 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs @@ -1,14 +1,16 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class ServiceInfoRepository : FreesqlRepository, IServiceInfoRepository { - public ServiceInfoRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) + private readonly IFreeSql freeSql; + + public ServiceInfoRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs index b91258cc..e0ac6097 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs @@ -1,14 +1,16 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class SettingRepository : FreesqlRepository, ISettingRepository { - public SettingRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) + private readonly IFreeSql freeSql; + + public SettingRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs index 6558e795..37ae0da2 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs @@ -1,14 +1,17 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class SysLogRepository : FreesqlRepository, ISysLogRepository { - public SysLogRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) + + private readonly IFreeSql freeSql; + + public SysLogRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs index 6cf743f9..5333a5d8 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs @@ -1,14 +1,17 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class UserAppAuthRepository : FreesqlRepository, IUserAppAuthRepository { - public UserAppAuthRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) + + private readonly IFreeSql freeSql; + + public UserAppAuthRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs index 9f70b34f..a93e3324 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs @@ -7,8 +7,12 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class UserRepository : FreesqlRepository, IUserRepository { - public UserRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) + + private readonly IFreeSql freeSql; + + public UserRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs index 447a11fa..a85d12d0 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs @@ -1,14 +1,16 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class UserRoleRepository : FreesqlRepository, IUserRoleRepository { - public UserRoleRepository([FromKeyedServices("")] IFreeSqlFactory freeSql) : base(freeSql) + private readonly IFreeSql freeSql; + + public UserRoleRepository(IFreeSql freeSql) : base(freeSql) { + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs b/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs index 5f88048a..ef971589 100644 --- a/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs +++ b/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs @@ -68,9 +68,8 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) } else { - var envAccssor = new ManualEnvAccessor(env); - var factory = new EnvFreeSqlFactory(envAccssor); - return new Freesql.ConfigPublishedRepository(factory); + var factory = sp.GetService(); + return new Freesql.ConfigPublishedRepository(factory.Create(env)); } }); @@ -84,9 +83,8 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) } else { - var envAccssor = new ManualEnvAccessor(env); - var factory = new EnvFreeSqlFactory(envAccssor); - return new Freesql.ConfigRepository(factory); + var factory = sp.GetService(); + return new Freesql.ConfigRepository(factory.Create(env)); } }); @@ -100,9 +98,8 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) } else { - var envAccssor = new ManualEnvAccessor(env); - var factory = new EnvFreeSqlFactory(envAccssor); - return new Freesql.PublishDetailRepository(factory); + var factory = sp.GetService(); + return new Freesql.PublishDetailRepository(factory.Create(env)); } }); @@ -116,9 +113,8 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) } else { - var envAccssor = new ManualEnvAccessor(env); - var factory = new EnvFreeSqlFactory(envAccssor); - return new Freesql.PublishTimelineRepository(factory); + var factory = sp.GetService(); + return new Freesql.PublishTimelineRepository(factory.Create(env)); } })); @@ -137,15 +133,5 @@ private static string GetEnvProvider(string env, IConfiguration config, string d return envProvider; } - - class ManualEnvAccessor : IEnvAccessor - { - string _env; - public ManualEnvAccessor(string env) - { - _env = env; - } - public string Env => _env; - } } } From ecc0064c3b518453c5209cfd1a053e5f953f309c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BD=AD=E8=BF=81?= Date: Fri, 5 Jan 2024 14:58:54 +0800 Subject: [PATCH 23/45] adapt to different environment configurations of mongodb --- .../RepositoryExtension.cs | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs b/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs index ef971589..66b6b655 100644 --- a/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs +++ b/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs @@ -53,10 +53,10 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) sc.AddScoped(); sc.AddScoped(); - sc.AddScoped(); - sc.AddScoped(); - sc.AddScoped(); - sc.AddScoped(); + // sc.AddScoped(); + // sc.AddScoped(); + // sc.AddScoped(); + // sc.AddScoped(); sc.AddScoped>(sp => env => { @@ -64,7 +64,7 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) { - return sp.GetService(); + return new Mongodb.ConfigPublishedRepository(GetConnectionString(env, config)); } else { @@ -79,7 +79,7 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) { - return sp.GetService(); + return new Mongodb.ConfigRepository(GetConnectionString(env, config)); } else { @@ -94,7 +94,7 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) { - return sp.GetService(); + return new Mongodb.PublishDetailRepository(GetConnectionString(env, config)); } else { @@ -109,7 +109,7 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) { - return sp.GetService(); + return new Mongodb.PublishTimelineRepository(GetConnectionString(env,config)); } else { @@ -133,5 +133,10 @@ private static string GetEnvProvider(string env, IConfiguration config, string d return envProvider; } + + private static string? GetConnectionString(string env, IConfiguration config) + { + return string.IsNullOrEmpty(env) ? config["db:conn"] : config[$"db:env:{env}:conn"]; + } } -} +} \ No newline at end of file From 625b7d4a6523a614f23956dcacb9e0917fe6fe5b Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sat, 6 Jan 2024 15:59:24 +0800 Subject: [PATCH 24/45] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=9B=B8=E5=85=B3bug?= =?UTF-8?q?=EF=BC=8C=E9=87=8D=E6=9E=84=20EventRegister=20=E7=9B=B8?= =?UTF-8?q?=E5=85=B3=E5=86=85=E5=AE=B9=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../AgileConfig.Server.Apisite.csproj | 1 + src/AgileConfig.Server.Apisite/Startup.cs | 19 +-- .../FreesqlRepository.cs | 33 +---- .../RepositoryExtension.cs | 21 +-- src/AgileConfig.Server.Service/AppService.cs | 71 ++++++---- .../ConfigService.cs | 83 +++++++----- .../ConfigStatusUpdateRegister.cs | 23 ++-- .../ServiceInfoStatusUpdateRegister.cs | 24 ++-- .../EventRegisterService/SysLogRegister.cs | 122 ++++-------------- .../SysLogService.cs | 37 ++---- 10 files changed, 172 insertions(+), 262 deletions(-) diff --git a/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj b/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj index 27aebb1f..343482e3 100644 --- a/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj +++ b/src/AgileConfig.Server.Apisite/AgileConfig.Server.Apisite.csproj @@ -44,6 +44,7 @@ + diff --git a/src/AgileConfig.Server.Apisite/Startup.cs b/src/AgileConfig.Server.Apisite/Startup.cs index fa20b7c5..5a675870 100644 --- a/src/AgileConfig.Server.Apisite/Startup.cs +++ b/src/AgileConfig.Server.Apisite/Startup.cs @@ -18,6 +18,7 @@ using Microsoft.OpenApi.Models; using AgileConfig.Server.Data.Repository.Freesql; using AgileConfig.Server.Data.Repository.Mongodb; +using AgileConfig.Server.Data.Repository.Selector; namespace AgileConfig.Server.Apisite { @@ -72,9 +73,9 @@ public void ConfigureServices(IServiceCollection services) } services.AddEnvAccessor(); - + services.AddFreeSqlFactory(); // Add freesqlRepositories or other repositories - AddDataRepositories(services); + services.AddRepositories(); services.AddBusinessServices(); @@ -153,19 +154,5 @@ private void AddSwaggerMiddleWare(IApplicationBuilder app) }); } - - private void AddDataRepositories(IServiceCollection services) - { - if (string.Equals(Configuration["db:provider"], "mongodb", StringComparison.OrdinalIgnoreCase)) - { - services.AddMongodbRepository(); - } - else - { - services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); - } - } - } } diff --git a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs index df3c30e5..10c41034 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs @@ -60,37 +60,14 @@ public Task> QueryAsync(Expression> exp) public async Task> QueryPageAsync(Expression> exp, int pageIndex, int pageSize, string defaultSortField = "Id", string defaultSortType = "ASC") { - var query = _repository.Where(exp); - var sort = Sort(defaultSortField); - if (string.Equals(defaultSortField, "DESC", StringComparison.OrdinalIgnoreCase)) - { - query.OrderByDescending(sort); - } - else - { - query.OrderBy(sort); - } - return await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); - } + var list = await _repository.Where(exp) + .OrderByPropertyName(defaultSortField, defaultSortType.Equals("ASC", StringComparison.OrdinalIgnoreCase)) + .Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); - private Expression> Sort(string defaultSortField) - { - Expression> defaultSort = x => x.Id; - if (!string.IsNullOrEmpty(defaultSortField) && - !defaultSortField.Equals("Id", StringComparison.OrdinalIgnoreCase)) - { - var property = typeof(T).GetProperty(defaultSortField); - if (property == null) - { - return defaultSort; - } - var parameter = Expression.Parameter(typeof(T), "__q"); - var memberExpress = Expression.Property(parameter, property); - return Expression.Lambda>(memberExpress, parameter); - } - return defaultSort; + return list; } + public async Task CountAsync(Expression>? exp = null) { return await (exp == null ? _repository.Select.CountAsync() : _repository.Select.Where(exp).CountAsync()); diff --git a/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs b/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs index 66b6b655..12ba4760 100644 --- a/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs +++ b/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs @@ -3,7 +3,6 @@ using AgileConfig.Server.Data.Freesql; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using System.Security.Cryptography; namespace AgileConfig.Server.Data.Repository.Selector { @@ -21,6 +20,7 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) throw new ArgumentNullException(nameof(defaultProvider)); } + #region these repository will use default conn provider if (defaultProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) { sc.AddScoped(); @@ -47,17 +47,9 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) sc.AddScoped(); sc.AddSingleton(); } + #endregion - sc.AddScoped(); - sc.AddScoped(); - sc.AddScoped(); - sc.AddScoped(); - - // sc.AddScoped(); - // sc.AddScoped(); - // sc.AddScoped(); - // sc.AddScoped(); - + #region these repositories genereated dependency env provider, if no env provider use default provider sc.AddScoped>(sp => env => { string envProvider = GetEnvProvider(env, config, defaultProvider); @@ -103,20 +95,21 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) } }); - sc.AddScoped((Func>)(sp => env => + sc.AddScoped>(sp => env => { string envProvider = GetEnvProvider(env, config, defaultProvider); if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) { - return new Mongodb.PublishTimelineRepository(GetConnectionString(env,config)); + return new Mongodb.PublishTimelineRepository(GetConnectionString(env, config)); } else { var factory = sp.GetService(); return new Freesql.PublishTimelineRepository(factory.Create(env)); } - })); + }); + #endregion return sc; } diff --git a/src/AgileConfig.Server.Service/AppService.cs b/src/AgileConfig.Server.Service/AppService.cs index e8f38c2c..c500a01b 100644 --- a/src/AgileConfig.Server.Service/AppService.cs +++ b/src/AgileConfig.Server.Service/AppService.cs @@ -12,25 +12,29 @@ public class AppService : IAppService { private readonly IAppRepository _appRepository; private readonly IAppInheritancedRepository _appInheritancedRepository; - private readonly IConfigRepository _configRepository; - private readonly IConfigPublishedRepository _configPublishedRepository; + private readonly Func _configRepositoryAccessor; + private readonly Func _configPublishedRepositoryAccessor; private readonly IUserRepository _userRepository; private readonly IUserAppAuthRepository _userAppAuthRepository; + private readonly ISettingService _settingService; public AppService( IAppRepository repository, IAppInheritancedRepository appInheritancedRepository, - IConfigRepository configRepository, - IConfigPublishedRepository configPublishedRepository, + Func configRepository, + Func configPublishedRepository, IUserRepository userRepository, - IUserAppAuthRepository userAppAuthRepository) + IUserAppAuthRepository userAppAuthRepository, + ISettingService settingService + ) { _appRepository = repository; _appInheritancedRepository = appInheritancedRepository; - _configRepository = configRepository; - _configPublishedRepository = configPublishedRepository; + _configRepositoryAccessor = configRepository; + _configPublishedRepositoryAccessor = configPublishedRepository; _userRepository = userRepository; _userAppAuthRepository = userAppAuthRepository; + _settingService = settingService; } public async Task AddAsync(App app) @@ -54,22 +58,43 @@ public async Task DeleteAsync(App app) app = await _appRepository.GetAsync(app.Id); if (app != null) { - await _appRepository.DeleteAsync(app); - //怕有的同学误删app导致要恢复,所以保留配置项吧。 - var configs = await _configRepository.QueryAsync(x => x.AppId == app.Id); - foreach (var item in configs) - { - item.Status = ConfigStatus.Deleted; - await _configRepository.UpdateAsync(item); - } - //删除发布的配置项 - var publishedConfigs = await _configPublishedRepository - .QueryAsync(x => x.AppId == app.Id && x.Status == ConfigStatus.Enabled) - ; - foreach (var item in publishedConfigs) + var envs = await _settingService.GetEnvironmentList(); + var updatedConfigIds = new List(); + var updatedConfigPublishedIds = new List(); + + foreach (var env in envs) { - item.Status = ConfigStatus.Deleted; - await _configPublishedRepository.UpdateAsync(item); + using var configRepository = _configRepositoryAccessor(env); + using var configPublishedRepository = _configPublishedRepositoryAccessor(env); + await _appRepository.DeleteAsync(app); + //怕有的同学误删app导致要恢复,所以保留配置项吧。 + var configs = await configRepository.QueryAsync(x => x.AppId == app.Id); + foreach (var item in configs) + { + if (updatedConfigIds.Contains(item.Id)) + { + // 因为根据 env 构造的 provider 最终可能都定位到 default provider 上去,所以可能重复更新数据行,这里进行判断以下。 + continue; + } + item.Status = ConfigStatus.Deleted; + await configRepository.UpdateAsync(item); + updatedConfigIds.Add(item.Id); + } + //删除发布的配置项 + var publishedConfigs = await configPublishedRepository + .QueryAsync(x => x.AppId == app.Id && x.Status == ConfigStatus.Enabled) + ; + foreach (var item in publishedConfigs) + { + if (updatedConfigPublishedIds.Contains(item.Id)) + { + // 因为根据 env 构造的 provider 最终可能都定位到 default provider 上去,所以可能重复更新数据行,这里进行判断以下。 + continue; + } + item.Status = ConfigStatus.Deleted; + await configPublishedRepository.UpdateAsync(item); + updatedConfigPublishedIds.Add(item.Id); + } } } @@ -206,8 +231,6 @@ public void Dispose() { _appInheritancedRepository.Dispose(); _appRepository.Dispose(); - _configPublishedRepository.Dispose(); - _configRepository.Dispose(); _userAppAuthRepository.Dispose(); _userRepository.Dispose(); } diff --git a/src/AgileConfig.Server.Service/ConfigService.cs b/src/AgileConfig.Server.Service/ConfigService.cs index 2dca61bf..03e62444 100644 --- a/src/AgileConfig.Server.Service/ConfigService.cs +++ b/src/AgileConfig.Server.Service/ConfigService.cs @@ -67,23 +67,26 @@ public async Task AddAsync(Config config, string env) config.Value = ""; } - await _configRepositoryAccessor(env).InsertAsync(config); + using var repoistory = _configRepositoryAccessor(env); + await repoistory.InsertAsync(config); return true; } public async Task UpdateAsync(Config config, string env) { - await _configRepositoryAccessor(env).UpdateAsync(config); + using var repoistory = _configRepositoryAccessor(env); + await repoistory.UpdateAsync(config); return true; } public async Task UpdateAsync(List configs, string env) { + using var repoistory = _configRepositoryAccessor(env); foreach (var item in configs) { - await _configRepositoryAccessor(env).UpdateAsync(item); + await repoistory.UpdateAsync(item); } return true; @@ -91,7 +94,7 @@ public async Task UpdateAsync(List configs, string env) public async Task CancelEdit(List ids, string env) { - var configRepository = _configRepositoryAccessor(env); + using var configRepository = _configRepositoryAccessor(env); foreach (var configId in ids) { var config = await configRepository.GetAsync(configId); @@ -139,7 +142,7 @@ public async Task CancelEdit(List ids, string env) public async Task DeleteAsync(Config config, string env) { - var configRepository = _configRepositoryAccessor(env); + using var configRepository = _configRepositoryAccessor(env); config = await configRepository.GetAsync(config.Id); if (config != null) { @@ -151,7 +154,7 @@ public async Task DeleteAsync(Config config, string env) public async Task DeleteAsync(string configId, string env) { - var configRepository = _configRepositoryAccessor(env); + using var configRepository = _configRepositoryAccessor(env); var config = await configRepository.GetAsync(configId); if (config != null) { @@ -163,14 +166,16 @@ public async Task DeleteAsync(string configId, string env) public async Task GetAsync(string id, string env) { - var config = await _configRepositoryAccessor(env).GetAsync(id); + using var repository = _configRepositoryAccessor(env); + var config = await repository.GetAsync(id); return config; } public async Task> GetAllConfigsAsync(string env) { - return await _configRepositoryAccessor(env).QueryAsync(c => c.Status == ConfigStatus.Enabled && c.Env == env); + using var repository = _configRepositoryAccessor(env); + return await repository.QueryAsync(c => c.Status == ConfigStatus.Enabled && c.Env == env); } public async Task GetByAppIdKeyEnv(string appId, string group, string key, string env) @@ -191,20 +196,24 @@ public async Task GetByAppIdKeyEnv(string appId, string group, string ke exp.And(exp1); } - var configs = await _configRepositoryAccessor(env).QueryAsync(exp); + using var repository = _configRepositoryAccessor(env); + var configs = await repository.QueryAsync(exp); return configs.FirstOrDefault(); } public async Task> GetByAppIdAsync(string appId, string env) { - return await _configRepositoryAccessor(env).QueryAsync(c => + using var repository = _configRepositoryAccessor(env); + return await repository.QueryAsync(c => c.AppId == appId && c.Status == ConfigStatus.Enabled && c.Env == env ); } public async Task> Search(string appId, string group, string key, string env) { + using var repository = _configRepositoryAccessor(env); + Expression> exp = c => c.Status == ConfigStatus.Enabled && c.Env == env; if (!string.IsNullOrEmpty(appId)) { @@ -221,7 +230,7 @@ public async Task> Search(string appId, string group, string key, s exp = exp.And(c => c.Key.Contains(key)); } - return await _configRepositoryAccessor(env).QueryAsync(exp); + return await repository.QueryAsync(exp); } public async Task CountEnabledConfigsAsync() @@ -239,7 +248,8 @@ public async Task CountEnabledConfigsAsync() public async Task CountEnabledConfigsAsync(string env) { //这里计算所有的配置 - var q = await _configRepositoryAccessor(env).QueryAsync(c => c.Status == ConfigStatus.Enabled && c.Env == env); + using var repository = _configRepositoryAccessor(env); + var q = await repository.QueryAsync(c => c.Status == ConfigStatus.Enabled && c.Env == env); return q.Count; } @@ -271,7 +281,8 @@ public string GenerateKey(ConfigPublished config) /// public async Task AppPublishedConfigsMd5(string appId, string env) { - var configs = await _configPublishedRepositoryAccessor(env).QueryAsync(c => + using var repository = _configPublishedRepositoryAccessor(env); + var configs = await repository.QueryAsync(c => c.AppId == appId && c.Status == ConfigStatus.Enabled && c.Env == env ); @@ -337,6 +348,7 @@ public async Task AddRangeAsync(List configs, string env) } }); + using var repository = _configRepositoryAccessor(env); await _configRepositoryAccessor(env).InsertAsync(configs); ClearAppPublishedConfigsMd5Cache(configs.First().AppId, env); @@ -457,10 +469,10 @@ public void Dispose() await _lock.WaitAsync(); try { - var configRepository = _configRepositoryAccessor(env); - var publishTimelineRepository = _publishTimelineRepositoryAccsssor(env); - var configPublishedRepository = _configPublishedRepositoryAccessor(env); - var publishDetailRepository = _publishDetailRepositoryAccessor(env); + using var configRepository = _configRepositoryAccessor(env); + using var publishTimelineRepository = _publishTimelineRepositoryAccsssor(env); + using var configPublishedRepository = _configPublishedRepositoryAccessor(env); + using var publishDetailRepository = _publishDetailRepositoryAccessor(env); var waitPublishConfigs = await configRepository.QueryAsync(x => x.AppId == appId && @@ -622,7 +634,8 @@ public void Dispose() public async Task IsPublishedAsync(string configId, string env) { - var any = await _configPublishedRepositoryAccessor(env).QueryAsync( + using var repository = _configPublishedRepositoryAccessor(env); + var any = await repository.QueryAsync( x => x.ConfigId == configId && x.Env == env && x.Status == ConfigStatus.Enabled); @@ -633,7 +646,8 @@ public async Task IsPublishedAsync(string configId, string env) public async Task> GetPublishDetailByPublishTimelineIdAsync(string publishTimelineId, string env) { - var list = await _publishDetailRepositoryAccessor(env) + using var repository = _publishDetailRepositoryAccessor(env); + var list = await repository .QueryAsync(x => x.PublishTimelineId == publishTimelineId && x.Env == env); return list; @@ -641,7 +655,8 @@ public async Task> GetPublishDetailByPublishTimelineIdAsync( public async Task GetPublishTimeLineNodeAsync(string publishTimelineId, string env) { - var one = (await _publishTimelineRepositoryAccsssor(env).QueryAsync(x => x.Id == publishTimelineId && x.Env == env)) + using var repository = _publishTimelineRepositoryAccsssor(env); + var one = (await repository.QueryAsync(x => x.Id == publishTimelineId && x.Env == env)) .FirstOrDefault(); return one; @@ -649,36 +664,40 @@ public async Task GetPublishTimeLineNodeAsync(string publishTim public async Task> GetPublishTimelineHistoryAsync(string appId, string env) { - var list = await _publishTimelineRepositoryAccsssor(env).QueryAsync(x => x.AppId == appId && x.Env == env); + using var repository = _publishTimelineRepositoryAccsssor(env); + var list = await repository.QueryAsync(x => x.AppId == appId && x.Env == env); return list; } public async Task> GetPublishDetailListAsync(string appId, string env) { - var list = await _publishDetailRepositoryAccessor(env).QueryAsync(x => x.AppId == appId && x.Env == env); + using var repository = _publishDetailRepositoryAccessor(env); + var list = await repository.QueryAsync(x => x.AppId == appId && x.Env == env); return list; } public async Task> GetConfigPublishedHistory(string configId, string env) { - var list = await _publishDetailRepositoryAccessor(env).QueryAsync(x => x.ConfigId == configId && x.Env == env); + using var repository = _publishDetailRepositoryAccessor(env); + var list = await repository.QueryAsync(x => x.ConfigId == configId && x.Env == env); return list; } public async Task> GetPublishedConfigsAsync(string appId, string env) { - var list = await _configPublishedRepositoryAccessor(env) - .QueryAsync(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env); + using var repository = _configPublishedRepositoryAccessor(env); + var list = await repository.QueryAsync(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env); return list; } public async Task GetPublishedConfigAsync(string configId, string env) { - var one = (await _configPublishedRepositoryAccessor(env).QueryAsync(x => x.ConfigId == configId + using var repository = _configPublishedRepositoryAccessor(env); + var one = (await repository.QueryAsync(x => x.ConfigId == configId && x.Status == ConfigStatus.Enabled && x.Env == env )).FirstOrDefault(); @@ -688,10 +707,10 @@ public async Task GetPublishedConfigAsync(string configId, stri public async Task RollbackAsync(string publishTimelineId, string env) { - var configRepository = _configRepositoryAccessor(env); - var publishTimelineRepository = _publishTimelineRepositoryAccsssor(env); - var configPublishedRepository = _configPublishedRepositoryAccessor(env); - var publishDetailRepository = _publishDetailRepositoryAccessor(env); + using var configRepository = _configRepositoryAccessor(env); + using var publishTimelineRepository = _publishTimelineRepositoryAccsssor(env); + using var configPublishedRepository = _configPublishedRepositoryAccessor(env); + using var publishDetailRepository = _publishDetailRepositoryAccessor(env); var publishNode = (await publishTimelineRepository.QueryAsync(x => x.Id == publishTimelineId && x.Env == env)).FirstOrDefault(); @@ -710,7 +729,7 @@ public async Task RollbackAsync(string publishTimelineId, string env) var publishedConfigs = await configPublishedRepository .QueryAsync(x => x.AppId == appId && x.Version == version && x.Env == env); - var currentConfigs = await _configRepositoryAccessor(env) + var currentConfigs = await configRepository .QueryAsync(x => x.AppId == appId && x.Status == ConfigStatus.Enabled && x.Env == env); //把当前的全部软删除 @@ -833,7 +852,7 @@ public async Task>> GetKvListAsync(string appI private async Task SaveFromDictAsync(IDictionary dict, string appId, string env, bool isPatch) { - var configRepository = _configRepositoryAccessor(env); + using var configRepository = _configRepositoryAccessor(env); var currentConfigs = await configRepository .QueryAsync(x => x.AppId == appId && x.Env == env && x.Status == ConfigStatus.Enabled); diff --git a/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs index 0efe9122..c11c4788 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs @@ -11,17 +11,17 @@ namespace AgileConfig.Server.Service.EventRegisterService; internal class ConfigStatusUpdateRegister : IEventRegister { private readonly IRemoteServerNodeProxy _remoteServerNodeProxy; - private readonly EventRegisterTransient _serverNodeService; - private readonly EventRegisterTransient _appService; + private readonly IServerNodeService _serverNodeService; + private readonly IAppService _appService; public ConfigStatusUpdateRegister( IRemoteServerNodeProxy remoteServerNodeProxy, - EventRegisterTransient serverNodeService, - EventRegisterTransient appService) + EventRegisterTransient serverNodeServiceAccessor, + EventRegisterTransient appServiceAccessor) { _remoteServerNodeProxy = remoteServerNodeProxy; - _serverNodeService = serverNodeService; - _appService = appService; + _serverNodeService = serverNodeServiceAccessor(); + _appService = appServiceAccessor(); } public void Register() @@ -34,9 +34,8 @@ public void Register() { Task.Run(async () => { - using (var serverNodeService = _serverNodeService()) { - var nodes = await serverNodeService.GetAllNodesAsync(); + var nodes = await _serverNodeService.GetAllNodesAsync(); var noticeApps = await GetNeedNoticeInheritancedFromAppsAction(timelineNode.AppId); noticeApps.Add(timelineNode.AppId, new WebsocketAction { Action = ActionConst.Reload, Module = ActionModule.ConfigCenter }); @@ -81,9 +80,8 @@ await _remoteServerNodeProxy.AppClientsDoActionAsync( { Task.Run(async () => { - using (var serverNodeService = _serverNodeService()) { - var nodes = await serverNodeService.GetAllNodesAsync(); + var nodes = await _serverNodeService.GetAllNodesAsync(); var noticeApps = await GetNeedNoticeInheritancedFromAppsAction(timelineNode.AppId); noticeApps.Add(timelineNode.AppId, new WebsocketAction @@ -118,12 +116,11 @@ private async Task> GetNeedNoticeInheritance Dictionary needNoticeAppsActions = new Dictionary { }; - using (var appService = _appService()) { - var currentApp = await appService.GetAsync(appId); + var currentApp = await _appService.GetAsync(appId); if (currentApp.Type == AppType.Inheritance) { - var inheritancedFromApps = await appService.GetInheritancedFromAppsAsync(appId); + var inheritancedFromApps = await _appService.GetInheritancedFromAppsAsync(appId); inheritancedFromApps.ForEach(x => { needNoticeAppsActions.Add(x.Id, new WebsocketAction diff --git a/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs index 4acba8e6..f81e02e5 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs @@ -16,22 +16,22 @@ internal class ServiceInfoStatusUpdateRegister : IEventRegister { private readonly IRemoteServerNodeProxy _remoteServerNodeProxy; private readonly IRestClient _restClient; - private readonly EventRegisterTransient _serverNodeService; - private readonly EventRegisterTransient _serviceInfoService; private ILogger _logger; + private readonly IServerNodeService _serverNodeService; + private readonly IServiceInfoService _serviceInfoService; public ServiceInfoStatusUpdateRegister( IRemoteServerNodeProxy remoteServerNodeProxy, ILoggerFactory loggerFactory, IRestClient restClient, - EventRegisterTransient serverNodeService, - EventRegisterTransient serviceInfoService + EventRegisterTransient serverNodeServiceAccessor, + EventRegisterTransient serviceInfoServiceAccessor ) { _remoteServerNodeProxy = remoteServerNodeProxy; _restClient = restClient; - _serverNodeService = serverNodeService; - _serviceInfoService = serviceInfoService; + _serverNodeService = serverNodeServiceAccessor(); + _serviceInfoService = serviceInfoServiceAccessor(); _logger = loggerFactory.CreateLogger(); } @@ -42,8 +42,7 @@ public void Register() { Task.Run(async () => { - using var serverNodeService = _serverNodeService(); - var serverNodes = await serverNodeService.GetAllNodesAsync(); + var serverNodes = await _serverNodeService.GetAllNodesAsync(); foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) { //clear cache @@ -62,8 +61,7 @@ public void Register() { Task.Run(async () => { - using var serverNodeService = _serverNodeService(); - var serverNodes = await serverNodeService.GetAllNodesAsync(); + var serverNodes = await _serverNodeService.GetAllNodesAsync(); foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) { //clear cache @@ -82,8 +80,7 @@ public void Register() { Task.Run(async () => { - using var serverNodeService = _serverNodeService(); - var serverNodes = await serverNodeService.GetAllNodesAsync(); + var serverNodes = await _serverNodeService.GetAllNodesAsync(); foreach (var serverNode in serverNodes.Where(x => x.Status == NodeStatus.Online)) { //clear cache @@ -104,8 +101,7 @@ public void Register() { dynamic paramObj = param; string id = paramObj.UniqueId; - using var serviceInfoService = _serviceInfoService(); - var service = await serviceInfoService.GetByUniqueIdAsync(id); + var service = await _serviceInfoService.GetByUniqueIdAsync(id); if (service != null && !string.IsNullOrWhiteSpace(service.AlarmUrl) && service.Status == ServiceStatus.Unhealthy) { diff --git a/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs index 8ded506b..1ccaf3a9 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs @@ -8,11 +8,11 @@ namespace AgileConfig.Server.Service.EventRegisterService; internal class SysLogRegister : IEventRegister { - private readonly EventRegisterTransient _sysLogService; + private readonly ISysLogService _sysLogService; - public SysLogRegister(EventRegisterTransient sysLogService) + public SysLogRegister(EventRegisterTransient sysLogServiceAccessor) { - _sysLogService = sysLogService; + _sysLogService = sysLogServiceAccessor(); } public void Register() @@ -29,10 +29,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); }); @@ -46,10 +43,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); }); @@ -67,10 +61,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); }); @@ -87,10 +78,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); }); @@ -109,10 +97,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); } }); @@ -133,10 +118,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); } }); @@ -156,10 +138,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); } }); @@ -179,10 +158,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); } }); @@ -206,10 +182,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); } }); @@ -231,10 +204,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); } }); @@ -257,10 +227,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); } }); @@ -281,10 +248,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); } }); @@ -305,10 +269,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); }); TinyEventBus.Instance.Register(EventKeys.ROLLBACK_CONFIG_SUCCESS, (param) => @@ -330,10 +291,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); } }); @@ -355,10 +313,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); } }); @@ -380,10 +335,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); } }); @@ -401,10 +353,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); }); @@ -422,10 +371,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); }); @@ -443,10 +389,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); }); @@ -464,10 +407,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); }); @@ -485,10 +425,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); }); @@ -506,10 +443,7 @@ public void Register() }; Task.Run(async () => { - using (var syslogService = _sysLogService()) - { - await syslogService.AddSysLogAsync(log); - } + await _sysLogService.AddSysLogAsync(log); }); }); @@ -527,8 +461,7 @@ public void Register() }; Task.Run(async () => { - using var syslogService = _sysLogService(); - await syslogService.AddSysLogAsync(log); + await _sysLogService.AddSysLogAsync(log); }); }); TinyEventBus.Instance.Register(EventKeys.UNREGISTER_A_SERVICE, (param) => @@ -544,8 +477,7 @@ public void Register() }; Task.Run(async () => { - using var syslogService = _sysLogService(); - await syslogService.AddSysLogAsync(log); + await _sysLogService.AddSysLogAsync(log); }); }); } diff --git a/src/AgileConfig.Server.Service/SysLogService.cs b/src/AgileConfig.Server.Service/SysLogService.cs index 3a49c5e5..b7c570f4 100644 --- a/src/AgileConfig.Server.Service/SysLogService.cs +++ b/src/AgileConfig.Server.Service/SysLogService.cs @@ -6,6 +6,7 @@ using System.Linq.Expressions; using System.Threading.Tasks; using AgileConfig.Server.Data.Abstraction; +using Microsoft.AspNetCore.DataProtection.KeyManagement; namespace AgileConfig.Server.Service { @@ -32,35 +33,27 @@ public async Task AddSysLogAsync(SysLog log) public async Task Count(string appId, SysLogType? logType, DateTime? startTime, DateTime? endTime) { - var query = (Expression)Expression - .Constant(true); - + Expression> exp = x => true; if (!string.IsNullOrEmpty(appId)) { - Expression> expr = x => x.AppId == appId; - query = Expression.AndAlso(query, expr); + exp = exp.And(c => c.AppId == appId); } if (startTime.HasValue) { - Expression> expr = (x => x.LogTime >= startTime); - query = Expression.AndAlso(query, expr); + exp = exp.And(x => x.LogTime >= startTime); } if (endTime.HasValue) { - Expression> expr = (x => x.LogTime < endTime); - query = Expression.AndAlso(query, expr); + exp = exp.And(x => x.LogTime < endTime); } if (logType.HasValue) { - Expression> expr = (x => x.LogType == logType); - query = Expression.AndAlso(query, expr); + exp = exp.And(x => x.LogType == logType); } - var exp = Expression.Lambda>(query); - var count = await _sysLogRepository.CountAsync(exp); return count; @@ -73,35 +66,27 @@ public void Dispose() public async Task> SearchPage(string appId, SysLogType? logType, DateTime? startTime, DateTime? endTime, int pageSize, int pageIndex) { - var query = (Expression)Expression - .Constant(true); - + Expression> exp = x => true; if (!string.IsNullOrEmpty(appId)) { - Expression> expr = x => x.AppId == appId; - query = Expression.AndAlso(query, expr); + exp = exp.And(c => c.AppId == appId); } if (startTime.HasValue) { - Expression> expr = (x => x.LogTime >= startTime); - query = Expression.AndAlso(query, expr); + exp = exp.And(x => x.LogTime >= startTime); } if (endTime.HasValue) { - Expression> expr = (x => x.LogTime < endTime); - query = Expression.AndAlso(query, expr); + exp = exp.And(x => x.LogTime < endTime); } if (logType.HasValue) { - Expression> expr = (x => x.LogType == logType); - query = Expression.AndAlso(query, expr); + exp = exp.And(x => x.LogType == logType); } - var exp = Expression.Lambda>(query); - var list = await _sysLogRepository.QueryPageAsync(exp, pageIndex, pageSize, defaultSortType: "DESC"); return list; } From 7b453e57531237fd5533e1485c4f0460c1d1fb59 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sat, 6 Jan 2024 16:28:14 +0800 Subject: [PATCH 25/45] =?UTF-8?q?=E9=87=8D=E6=9E=84=20EventRegisterService?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/AgileConfig.Server.Service/AppService.cs | 9 +- .../ConfigStatusUpdateRegister.cs | 111 +++++++++--------- .../ServiceInfoStatusUpdateRegister.cs | 8 +- .../EventRegisterService/SysLogRegister.cs | 4 +- 4 files changed, 66 insertions(+), 66 deletions(-) diff --git a/src/AgileConfig.Server.Service/AppService.cs b/src/AgileConfig.Server.Service/AppService.cs index c500a01b..24fc2d54 100644 --- a/src/AgileConfig.Server.Service/AppService.cs +++ b/src/AgileConfig.Server.Service/AppService.cs @@ -5,6 +5,7 @@ using System.Threading.Tasks; using System.Linq; using AgileConfig.Server.Data.Abstraction; +using static FreeSql.Internal.GlobalFilter; namespace AgileConfig.Server.Service { @@ -69,6 +70,7 @@ public async Task DeleteAsync(App app) await _appRepository.DeleteAsync(app); //怕有的同学误删app导致要恢复,所以保留配置项吧。 var configs = await configRepository.QueryAsync(x => x.AppId == app.Id); + var waitDeleteConfigs = new List(); foreach (var item in configs) { if (updatedConfigIds.Contains(item.Id)) @@ -77,13 +79,15 @@ public async Task DeleteAsync(App app) continue; } item.Status = ConfigStatus.Deleted; - await configRepository.UpdateAsync(item); + waitDeleteConfigs.Add(item); updatedConfigIds.Add(item.Id); } + await configRepository.UpdateAsync(waitDeleteConfigs); //删除发布的配置项 var publishedConfigs = await configPublishedRepository .QueryAsync(x => x.AppId == app.Id && x.Status == ConfigStatus.Enabled) ; + var waitDeletePublishedConfigs = new List(); foreach (var item in publishedConfigs) { if (updatedConfigPublishedIds.Contains(item.Id)) @@ -92,9 +96,10 @@ public async Task DeleteAsync(App app) continue; } item.Status = ConfigStatus.Deleted; - await configPublishedRepository.UpdateAsync(item); + waitDeletePublishedConfigs.Add(item); updatedConfigPublishedIds.Add(item.Id); } + await configPublishedRepository.UpdateAsync(waitDeletePublishedConfigs); } } diff --git a/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs index c11c4788..715a2866 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/ConfigStatusUpdateRegister.cs @@ -16,12 +16,12 @@ internal class ConfigStatusUpdateRegister : IEventRegister public ConfigStatusUpdateRegister( IRemoteServerNodeProxy remoteServerNodeProxy, - EventRegisterTransient serverNodeServiceAccessor, - EventRegisterTransient appServiceAccessor) + IServerNodeService serverNodeService, + IAppService appService) { _remoteServerNodeProxy = remoteServerNodeProxy; - _serverNodeService = serverNodeServiceAccessor(); - _appService = appServiceAccessor(); + _serverNodeService = serverNodeService; + _appService = appService; } public void Register() @@ -34,38 +34,36 @@ public void Register() { Task.Run(async () => { - { - var nodes = await _serverNodeService.GetAllNodesAsync(); - var noticeApps = await GetNeedNoticeInheritancedFromAppsAction(timelineNode.AppId); - noticeApps.Add(timelineNode.AppId, - new WebsocketAction { Action = ActionConst.Reload, Module = ActionModule.ConfigCenter }); + var nodes = await _serverNodeService.GetAllNodesAsync(); + var noticeApps = await GetNeedNoticeInheritancedFromAppsAction(timelineNode.AppId); + noticeApps.Add(timelineNode.AppId, + new WebsocketAction { Action = ActionConst.Reload, Module = ActionModule.ConfigCenter }); - foreach (var node in nodes) + foreach (var node in nodes) + { + if (node.Status == NodeStatus.Offline) { - if (node.Status == NodeStatus.Offline) - { - continue; - } - - //all server cache - await _remoteServerNodeProxy.ClearConfigServiceCache(node.Id); + continue; } - foreach (var node in nodes) + //all server cache + await _remoteServerNodeProxy.ClearConfigServiceCache(node.Id); + } + + foreach (var node in nodes) + { + if (node.Status == NodeStatus.Offline) { - if (node.Status == NodeStatus.Offline) - { - continue; - } + continue; + } - foreach (var item in noticeApps) - { - await _remoteServerNodeProxy.AppClientsDoActionAsync( - node.Id, - item.Key, - timelineNode.Env, - item.Value); - } + foreach (var item in noticeApps) + { + await _remoteServerNodeProxy.AppClientsDoActionAsync( + node.Id, + item.Key, + timelineNode.Env, + item.Value); } } }); @@ -80,26 +78,24 @@ await _remoteServerNodeProxy.AppClientsDoActionAsync( { Task.Run(async () => { - { - var nodes = await _serverNodeService.GetAllNodesAsync(); - var noticeApps = await GetNeedNoticeInheritancedFromAppsAction(timelineNode.AppId); - noticeApps.Add(timelineNode.AppId, - new WebsocketAction - { Action = ActionConst.Reload, Module = ActionModule.ConfigCenter }); + var nodes = await _serverNodeService.GetAllNodesAsync(); + var noticeApps = await GetNeedNoticeInheritancedFromAppsAction(timelineNode.AppId); + noticeApps.Add(timelineNode.AppId, + new WebsocketAction + { Action = ActionConst.Reload, Module = ActionModule.ConfigCenter }); - foreach (var node in nodes) + foreach (var node in nodes) + { + if (node.Status == NodeStatus.Offline) { - if (node.Status == NodeStatus.Offline) - { - continue; - } + continue; + } - foreach (var item in noticeApps) - { - await _remoteServerNodeProxy.AppClientsDoActionAsync(node.Id, item.Key, - timelineNode.Env, - item.Value); - } + foreach (var item in noticeApps) + { + await _remoteServerNodeProxy.AppClientsDoActionAsync(node.Id, item.Key, + timelineNode.Env, + item.Value); } } }); @@ -116,21 +112,20 @@ private async Task> GetNeedNoticeInheritance Dictionary needNoticeAppsActions = new Dictionary { }; + var currentApp = await _appService.GetAsync(appId); + if (currentApp.Type == AppType.Inheritance) { - var currentApp = await _appService.GetAsync(appId); - if (currentApp.Type == AppType.Inheritance) + var inheritancedFromApps = await _appService.GetInheritancedFromAppsAsync(appId); + inheritancedFromApps.ForEach(x => { - var inheritancedFromApps = await _appService.GetInheritancedFromAppsAsync(appId); - inheritancedFromApps.ForEach(x => + needNoticeAppsActions.Add(x.Id, new WebsocketAction { - needNoticeAppsActions.Add(x.Id, new WebsocketAction - { - Action = ActionConst.Reload, Module = ActionModule.ConfigCenter - }); + Action = ActionConst.Reload, + Module = ActionModule.ConfigCenter }); - } - - return needNoticeAppsActions; + }); } + + return needNoticeAppsActions; } } \ No newline at end of file diff --git a/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs index f81e02e5..72fded57 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/ServiceInfoStatusUpdateRegister.cs @@ -24,14 +24,14 @@ public ServiceInfoStatusUpdateRegister( IRemoteServerNodeProxy remoteServerNodeProxy, ILoggerFactory loggerFactory, IRestClient restClient, - EventRegisterTransient serverNodeServiceAccessor, - EventRegisterTransient serviceInfoServiceAccessor + IServerNodeService serverNodeService, + IServiceInfoService serviceInfoService ) { _remoteServerNodeProxy = remoteServerNodeProxy; _restClient = restClient; - _serverNodeService = serverNodeServiceAccessor(); - _serviceInfoService = serviceInfoServiceAccessor(); + _serverNodeService = serverNodeService; + _serviceInfoService = serviceInfoService; _logger = loggerFactory.CreateLogger(); } diff --git a/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs index 1ccaf3a9..ba17c5e8 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs @@ -10,9 +10,9 @@ internal class SysLogRegister : IEventRegister { private readonly ISysLogService _sysLogService; - public SysLogRegister(EventRegisterTransient sysLogServiceAccessor) + public SysLogRegister(ISysLogService sysLogService) { - _sysLogService = sysLogServiceAccessor(); + _sysLogService = sysLogService; } public void Register() From 7057e5005edc86c6a830fddd7ef748b4854a1121 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sat, 6 Jan 2024 17:22:43 +0800 Subject: [PATCH 26/45] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=20Unitofwork=20?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F=E6=9D=A5=E9=80=82=E9=85=8D=E4=BA=8B=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../IRepository.cs | 2 + .../IUow.cs | 14 +++++++ .../FreeSqlUow.cs | 39 +++++++++++++++++++ .../FreesqlRepository.cs | 16 ++++++++ .../ServiceCollectionExt.cs | 4 +- .../MongodbRepository.cs | 3 ++ .../ConfigRepository.cs | 4 +- .../RepositoryExtension.cs | 17 ++++++++ .../ConfigService.cs | 29 +++++++++----- 9 files changed, 116 insertions(+), 12 deletions(-) create mode 100644 src/AgileConfig.Server.Data.Abstraction/IUow.cs create mode 100644 src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs diff --git a/src/AgileConfig.Server.Data.Abstraction/IRepository.cs b/src/AgileConfig.Server.Data.Abstraction/IRepository.cs index 584dc22a..ba324997 100644 --- a/src/AgileConfig.Server.Data.Abstraction/IRepository.cs +++ b/src/AgileConfig.Server.Data.Abstraction/IRepository.cs @@ -27,5 +27,7 @@ Task> QueryPageAsync(Expression> exp, int pageIndex, int p string defaultSortField = "Id", string defaultSortType = "ASC"); Task CountAsync(Expression>? exp = null); + + IUow Uow { get; set; } } } diff --git a/src/AgileConfig.Server.Data.Abstraction/IUow.cs b/src/AgileConfig.Server.Data.Abstraction/IUow.cs new file mode 100644 index 00000000..462cbe9d --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/IUow.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AgileConfig.Server.Data.Abstraction +{ + public interface IUow : IDisposable + { + Task SaveChangesAsync(); + + } +} diff --git a/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs b/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs new file mode 100644 index 00000000..14572802 --- /dev/null +++ b/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs @@ -0,0 +1,39 @@ +using FreeSql; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AgileConfig.Server.Data.Freesql +{ + public class FreeSqlUow : Abstraction.IUow + { + private readonly IFreeSql _freeSql; + private IUnitOfWork _unitOfWork; + + + public FreeSqlUow(IFreeSql freeSql) + { + this._freeSql = freeSql; + _unitOfWork = _freeSql.CreateUnitOfWork(); + } + + public IUnitOfWork GetFreesqlUnitOfWork() + { + return _unitOfWork; + } + + public Task SaveChangesAsync() + { + _unitOfWork.Commit(); + + return Task.FromResult(true); + } + + public void Dispose() + { + _unitOfWork?.Dispose(); + } + } +} diff --git a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs index 10c41034..ef43613f 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreesqlRepository.cs @@ -11,10 +11,26 @@ namespace AgileConfig.Server.Data.Freesql public abstract class FreesqlRepository : IRepository where T : class, IEntity { private readonly IBaseRepository _repository; + private readonly IFreeSql _freeSql; + private IUow _uow; + public IUow Uow + { + get + { + return _uow; + } + set + { + _uow = value; + var freesqlUow = value as FreeSqlUow; + _repository.UnitOfWork = freesqlUow.GetFreesqlUnitOfWork(); + } + } public FreesqlRepository(IFreeSql freeSql) { _repository = freeSql.GetRepository(); + _freeSql = freeSql; } public Task> AllAsync() diff --git a/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs b/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs index 94c79d98..120e5e81 100644 --- a/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs +++ b/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.Data.Abstraction; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Freesql { @@ -6,6 +7,7 @@ public static class ServiceCollectionExt { public static void AddFreeSqlFactory(this IServiceCollection sc) { + sc.AddScoped(); sc.AddSingleton(FreeSQL.Instance); sc.AddSingleton(); } diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs index 6dea867a..a37870d4 100644 --- a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs @@ -1,5 +1,6 @@ using System.Linq.Expressions; using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using MongoDB.Driver; @@ -12,6 +13,8 @@ public class MongodbRepository : Abstraction.IRepository _access; + public IUow Uow { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public MongodbRepository(string? connectionString) { _access = new MongodbAccess(connectionString); diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs index 9917b27a..7569340d 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs @@ -6,11 +6,11 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class ConfigRepository : FreesqlRepository, IConfigRepository { - private readonly IFreeSql freeSql; + private readonly IFreeSql _freeSql; public ConfigRepository(IFreeSql freeSql) : base(freeSql) { - this.freeSql = freeSql; + this._freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs b/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs index 12ba4760..1fbbfad6 100644 --- a/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs +++ b/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs @@ -50,6 +50,22 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) #endregion #region these repositories genereated dependency env provider, if no env provider use default provider + sc.AddScoped>(sp => env => + { + string envProvider = GetEnvProvider(env, config, defaultProvider); + + if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + else + { + var factory = sp.GetService(); + var fsq = factory.Create(env); + return new FreeSqlUow(fsq); + } + }); + sc.AddScoped>(sp => env => { string envProvider = GetEnvProvider(env, config, defaultProvider); @@ -76,6 +92,7 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) else { var factory = sp.GetService(); + return new Freesql.ConfigRepository(factory.Create(env)); } }); diff --git a/src/AgileConfig.Server.Service/ConfigService.cs b/src/AgileConfig.Server.Service/ConfigService.cs index 03e62444..3c5b907a 100644 --- a/src/AgileConfig.Server.Service/ConfigService.cs +++ b/src/AgileConfig.Server.Service/ConfigService.cs @@ -20,6 +20,7 @@ public class ConfigService : IConfigService private readonly IAppService _appService; private readonly ISettingService _settingService; private readonly IUserService _userService; + private readonly Func _uowAccessor; private readonly Func _configRepositoryAccessor; private readonly Func _configPublishedRepositoryAccessor; private readonly Func _publishDetailRepositoryAccessor; @@ -29,19 +30,21 @@ public ConfigService(IMemoryCache memoryCache, IAppService appService, ISettingService settingService, IUserService userService, - Func configRepository, - Func configPublishedRepository, - Func publishDetailRepository, - Func publishTimelineRepository) + Func uowAccessor, + Func configRepositoryAccessor, + Func configPublishedRepositoryAccessor, + Func publishDetailRepositoryAccessor, + Func publishTimelineRepositoryAccessor) { _memoryCache = memoryCache; _appService = appService; _settingService = settingService; _userService = userService; - _configRepositoryAccessor = configRepository; - _configPublishedRepositoryAccessor = configPublishedRepository; - _publishDetailRepositoryAccessor = publishDetailRepository; - _publishTimelineRepositoryAccsssor = publishTimelineRepository; + _uowAccessor = uowAccessor; + _configRepositoryAccessor = configRepositoryAccessor; + _configPublishedRepositoryAccessor = configPublishedRepositoryAccessor; + _publishDetailRepositoryAccessor = publishDetailRepositoryAccessor; + _publishTimelineRepositoryAccsssor = publishTimelineRepositoryAccessor; } public async Task IfEnvEmptySetDefaultAsync(string env) @@ -349,7 +352,7 @@ public async Task AddRangeAsync(List configs, string env) }); using var repository = _configRepositoryAccessor(env); - await _configRepositoryAccessor(env).InsertAsync(configs); + await repository.InsertAsync(configs); ClearAppPublishedConfigsMd5Cache(configs.First().AppId, env); ClearAppPublishedConfigsMd5CacheWithInheritanced(configs.First().AppId, env); @@ -469,10 +472,16 @@ public void Dispose() await _lock.WaitAsync(); try { + using var uow = _uowAccessor(env); + using var configRepository = _configRepositoryAccessor(env); + configRepository.Uow = uow; using var publishTimelineRepository = _publishTimelineRepositoryAccsssor(env); + publishTimelineRepository.Uow = uow; using var configPublishedRepository = _configPublishedRepositoryAccessor(env); + configPublishedRepository.Uow = uow; using var publishDetailRepository = _publishDetailRepositoryAccessor(env); + publishDetailRepository.Uow = uow; var waitPublishConfigs = await configRepository.QueryAsync(x => x.AppId == appId && @@ -617,6 +626,8 @@ public void Dispose() await configPublishedRepository.UpdateAsync(publishedConfigs); await configPublishedRepository.InsertAsync(publishedConfigsCopy); + await uow?.SaveChangesAsync(); + ClearAppPublishedConfigsMd5Cache(appId, env); ClearAppPublishedConfigsMd5CacheWithInheritanced(appId, env); From 304c9066269d99afdc434e925b25c4552bb2f0d5 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sat, 6 Jan 2024 17:25:28 +0800 Subject: [PATCH 27/45] Refactor FreesqlUow --- src/AgileConfig.Server.Data.Abstraction/IUow.cs | 2 ++ src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs | 7 ++++++- src/AgileConfig.Server.Service/ConfigService.cs | 12 +++++++----- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/AgileConfig.Server.Data.Abstraction/IUow.cs b/src/AgileConfig.Server.Data.Abstraction/IUow.cs index 462cbe9d..dd8fa9aa 100644 --- a/src/AgileConfig.Server.Data.Abstraction/IUow.cs +++ b/src/AgileConfig.Server.Data.Abstraction/IUow.cs @@ -8,6 +8,8 @@ namespace AgileConfig.Server.Data.Abstraction { public interface IUow : IDisposable { + void Begin(); + Task SaveChangesAsync(); } diff --git a/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs b/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs index 14572802..b6f4a819 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs @@ -22,7 +22,7 @@ public FreeSqlUow(IFreeSql freeSql) public IUnitOfWork GetFreesqlUnitOfWork() { return _unitOfWork; - } + } public Task SaveChangesAsync() { @@ -35,5 +35,10 @@ public void Dispose() { _unitOfWork?.Dispose(); } + + public void Begin() + { + // freeSql的uow不需要手动begin + } } } diff --git a/src/AgileConfig.Server.Service/ConfigService.cs b/src/AgileConfig.Server.Service/ConfigService.cs index 3c5b907a..48289bc0 100644 --- a/src/AgileConfig.Server.Service/ConfigService.cs +++ b/src/AgileConfig.Server.Service/ConfigService.cs @@ -33,8 +33,8 @@ public ConfigService(IMemoryCache memoryCache, Func uowAccessor, Func configRepositoryAccessor, Func configPublishedRepositoryAccessor, - Func publishDetailRepositoryAccessor, - Func publishTimelineRepositoryAccessor) + Func publishDetailRepositoryAccessor, + Func publishTimelineRepositoryAccessor) { _memoryCache = memoryCache; _appService = appService; @@ -70,7 +70,7 @@ public async Task AddAsync(Config config, string env) config.Value = ""; } - using var repoistory = _configRepositoryAccessor(env); + using var repoistory = _configRepositoryAccessor(env); await repoistory.InsertAsync(config); return true; @@ -284,7 +284,7 @@ public string GenerateKey(ConfigPublished config) /// public async Task AppPublishedConfigsMd5(string appId, string env) { - using var repository = _configPublishedRepositoryAccessor(env); + using var repository = _configPublishedRepositoryAccessor(env); var configs = await repository.QueryAsync(c => c.AppId == appId && c.Status == ConfigStatus.Enabled && c.Env == env @@ -472,7 +472,7 @@ public void Dispose() await _lock.WaitAsync(); try { - using var uow = _uowAccessor(env); + using var uow = _uowAccessor(env); using var configRepository = _configRepositoryAccessor(env); configRepository.Uow = uow; @@ -483,6 +483,8 @@ public void Dispose() using var publishDetailRepository = _publishDetailRepositoryAccessor(env); publishDetailRepository.Uow = uow; + uow?.Begin(); + var waitPublishConfigs = await configRepository.QueryAsync(x => x.AppId == appId && x.Env == env && From abedae36c0184de32e2935da2e1bfb2ac0fc9739 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 7 Jan 2024 02:09:55 +0800 Subject: [PATCH 28/45] Refactor freesql respository; Add an empty UoW for mongodb; --- src/AgileConfig.Server.Apisite/Startup.cs | 1 + .../DbConfig/DbConfigInfo.cs | 23 ++++++ .../DbConfig/DbConfigInfoFactory.cs | 70 +++++++++++++++++++ .../DbConfig/IDbConfigInfo.cs | 10 +++ .../ISysLogRepository.cs | 2 +- src/AgileConfig.Server.Data.Entity/SysLog.cs | 11 ++- .../FreeSQL.cs | 41 +++-------- .../FreeSqlDbContextFactory.cs | 14 ---- .../IFreeSqlFactory.cs | 2 +- .../ServiceCollectionExt.cs | 1 - .../MongodbRepository.cs | 10 +-- .../MongodbUow.cs | 21 ++++++ .../AppInheritancedRepository.cs | 6 +- .../AppRepository.cs | 6 +- .../ConfigRepository.cs | 4 +- .../ServerNodeRepository.cs | 6 +- .../ServiceInfoRepository.cs | 6 +- .../SettingRepository.cs | 6 +- .../SysInitRepository.cs | 11 ++- .../SysLogRepository.cs | 8 +-- .../UserAppAuthRepository.cs | 6 +- .../UserRepository.cs | 7 +- .../UserRoleRepository.cs | 6 +- .../MongodbRepositoryExt.cs | 2 + .../SysLogRepository.cs | 2 +- .../RepositoryExtension.cs | 58 ++++++--------- .../ConfigService.cs | 17 +++++ .../EventRegisterService/SysLogRegister.cs | 13 +++- .../SysLogService.cs | 2 +- 29 files changed, 243 insertions(+), 129 deletions(-) create mode 100644 src/AgileConfig.Server.Data.Abstraction/DbConfig/DbConfigInfo.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/DbConfig/DbConfigInfoFactory.cs create mode 100644 src/AgileConfig.Server.Data.Abstraction/DbConfig/IDbConfigInfo.cs create mode 100644 src/AgileConfig.Server.Data.Mongodb/MongodbUow.cs diff --git a/src/AgileConfig.Server.Apisite/Startup.cs b/src/AgileConfig.Server.Apisite/Startup.cs index 5a675870..0cce4b93 100644 --- a/src/AgileConfig.Server.Apisite/Startup.cs +++ b/src/AgileConfig.Server.Apisite/Startup.cs @@ -19,6 +19,7 @@ using AgileConfig.Server.Data.Repository.Freesql; using AgileConfig.Server.Data.Repository.Mongodb; using AgileConfig.Server.Data.Repository.Selector; +using AgileConfig.Server.Data.Abstraction.DbProvider; namespace AgileConfig.Server.Apisite { diff --git a/src/AgileConfig.Server.Data.Abstraction/DbConfig/DbConfigInfo.cs b/src/AgileConfig.Server.Data.Abstraction/DbConfig/DbConfigInfo.cs new file mode 100644 index 00000000..b2a8544e --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/DbConfig/DbConfigInfo.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AgileConfig.Server.Data.Abstraction.DbProvider +{ + public class DbConfigInfo : IDbConfigInfo + { + public DbConfigInfo(string env, string provider, string conn) + { + this.Env = env; + this.Provider = provider; + this.ConnectionString = conn; + } + public string Env { get; } + + public string Provider { get; } + + public string ConnectionString { get; } + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/DbConfig/DbConfigInfoFactory.cs b/src/AgileConfig.Server.Data.Abstraction/DbConfig/DbConfigInfoFactory.cs new file mode 100644 index 00000000..49c3a869 --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/DbConfig/DbConfigInfoFactory.cs @@ -0,0 +1,70 @@ +using AgileConfig.Server.Common; +using System.Collections.Concurrent; + +namespace AgileConfig.Server.Data.Abstraction.DbProvider +{ + public static class DbConfigInfoFactory + { + private static ConcurrentDictionary _envProviders = new ConcurrentDictionary(); + private static IDbConfigInfo _default { get; } + + static DbConfigInfoFactory() + { + var providerPath = $"db:provider"; + var connPath = $"db:conn"; + + var providerValue = Global.Config[providerPath]; + var connValue = Global.Config[connPath]; + + if (string.IsNullOrEmpty(providerValue)) + { + throw new ArgumentNullException(providerPath); + } + if (string.IsNullOrEmpty(connValue)) + { + throw new ArgumentNullException(connPath); + } + + var configInfo = new DbConfigInfo("", providerValue, connValue); + _default = configInfo; + _envProviders.TryAdd(providerPath, configInfo); + } + + public static IDbConfigInfo GetConfigInfo(string env = "") + { + if (string.IsNullOrEmpty(env)) + { + return _default; + } + + var providerPath = $""; + var connPath = $""; + providerPath = $"db:env:{env}:provider"; + connPath = $"db:env:{env}:conn"; + + _envProviders.TryGetValue(providerPath, out IDbConfigInfo configInfo); + + if (configInfo != null) + { + return configInfo; + } + + var providerValue = Global.Config[providerPath]; + var connValue = Global.Config[connPath]; + + if (string.IsNullOrEmpty(providerValue)) + { + return _default; + } + if (string.IsNullOrEmpty(connValue)) + { + return _default; + } + + configInfo = new DbConfigInfo(env, providerValue, connValue); + _envProviders.TryAdd(providerPath, configInfo); + + return configInfo; + } + } +} diff --git a/src/AgileConfig.Server.Data.Abstraction/DbConfig/IDbConfigInfo.cs b/src/AgileConfig.Server.Data.Abstraction/DbConfig/IDbConfigInfo.cs new file mode 100644 index 00000000..7ae24c36 --- /dev/null +++ b/src/AgileConfig.Server.Data.Abstraction/DbConfig/IDbConfigInfo.cs @@ -0,0 +1,10 @@ +namespace AgileConfig.Server.Data.Abstraction.DbProvider +{ + public interface IDbConfigInfo + { + string ConnectionString { get; } + string Env { get; } + + string Provider { get; } + } +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Abstraction/ISysLogRepository.cs b/src/AgileConfig.Server.Data.Abstraction/ISysLogRepository.cs index ea0508b0..a350d145 100644 --- a/src/AgileConfig.Server.Data.Abstraction/ISysLogRepository.cs +++ b/src/AgileConfig.Server.Data.Abstraction/ISysLogRepository.cs @@ -2,7 +2,7 @@ namespace AgileConfig.Server.Data.Abstraction { - public interface ISysLogRepository : IRepository + public interface ISysLogRepository : IRepository { } } diff --git a/src/AgileConfig.Server.Data.Entity/SysLog.cs b/src/AgileConfig.Server.Data.Entity/SysLog.cs index 825f56a9..435adb9f 100644 --- a/src/AgileConfig.Server.Data.Entity/SysLog.cs +++ b/src/AgileConfig.Server.Data.Entity/SysLog.cs @@ -13,10 +13,15 @@ public enum SysLogType [Table(Name = "agc_sys_log")] [OraclePrimaryKeyName("agc_sys_log_pk")] - public class SysLog: IEntity + public class SysLog: IEntity { - [Column(Name = "id", IsIdentity = true)] - public int Id { get; set; } + public SysLog() + { + Id = Guid.NewGuid().ToString("N"); + } + + [Column(Name = "id", StringLength = 36)] + public string Id { get; set; } [Column(Name = "app_id", StringLength = 36)] public string AppId { get; set; } diff --git a/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs b/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs index ade93a16..788152e3 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs @@ -1,5 +1,4 @@ -using AgileConfig.Server.Common; -using Microsoft.Extensions.Configuration; +using AgileConfig.Server.Data.Abstraction.DbProvider; using System; using System.Collections.Generic; @@ -7,21 +6,9 @@ namespace AgileConfig.Server.Data.Freesql { public static class FreeSQL { - private static IFreeSql _freesql; - private static Dictionary _envFreesqls = new (); + private static Dictionary _envFreesqls = new(); private static object _lock = new object(); - static FreeSQL() - { - _freesql = new FreeSql.FreeSqlBuilder() - .UseConnectionString(ProviderToFreesqlDbType(DbProvider), DbConnection) - .Build(); - FluentApi.Config(_freesql); - EnsureTables.Ensure(_freesql); - } - - public static IFreeSql Instance => _freesql; - /// /// 根据环境配置的字符串返回freesql 实例 /// @@ -29,20 +16,15 @@ static FreeSQL() /// public static IFreeSql GetInstanceByEnv(string env) { - if (string.IsNullOrEmpty(env)) - { - return Instance; - } - - var provider = Global.Config[$"db:env:{env}:provider"]; - var conn = Global.Config[$"db:env:{env}:conn"]; + var dbConfig = DbConfigInfoFactory.GetConfigInfo(env); - if (string.IsNullOrEmpty(provider)) + var dbType = ProviderToFreesqlDbType(dbConfig.Provider); + if (!dbType.HasValue) { - return Instance; + throw new ArgumentException(nameof(dbConfig.Provider), $"[{dbConfig.Provider}] is not a freesql supported provider."); } - var key = provider; + var key = dbConfig.ConnectionString; if (_envFreesqls.ContainsKey(key)) { @@ -57,7 +39,7 @@ public static IFreeSql GetInstanceByEnv(string env) } var sql = new FreeSql.FreeSqlBuilder() - .UseConnectionString(ProviderToFreesqlDbType(provider), conn) + .UseConnectionString(dbType.Value, dbConfig.ConnectionString) .Build(); FluentApi.Config(sql); EnsureTables.Ensure(sql); @@ -68,10 +50,7 @@ public static IFreeSql GetInstanceByEnv(string env) } } - private static string DbProvider => Global.Config["db:provider"]; - private static string DbConnection => Global.Config["db:conn"]; - - private static FreeSql.DataType ProviderToFreesqlDbType(string provider) + private static FreeSql.DataType? ProviderToFreesqlDbType(string provider) { switch (provider.ToLower()) { @@ -91,7 +70,7 @@ private static FreeSql.DataType ProviderToFreesqlDbType(string provider) break; } - return FreeSql.DataType.Sqlite; + return null; } } } diff --git a/src/AgileConfig.Server.Data.Freesql/FreeSqlDbContextFactory.cs b/src/AgileConfig.Server.Data.Freesql/FreeSqlDbContextFactory.cs index 5f65f488..1b179442 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreeSqlDbContextFactory.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreeSqlDbContextFactory.cs @@ -14,20 +14,6 @@ public class FreeSqlDbContextFactory /// public static FreeSqlContext Create(string env) { - if (string.IsNullOrEmpty(env)) - { - //如果没有环境,使用默认连接 - return new FreeSqlContext(FreeSQL.Instance); - } - - //是否配置的环境的连接 - var envDbProvider = Global.Config[$"db:env:{env}:provider"]; - if (string.IsNullOrEmpty(envDbProvider)) - { - //如果没有配置对应环境的连接,使用默认连接 - return new FreeSqlContext(FreeSQL.Instance); - } - Console.WriteLine("create env:{env} freesql dbcontext instance ."); return new FreeSqlContext(FreeSQL.GetInstanceByEnv(env)); } diff --git a/src/AgileConfig.Server.Data.Freesql/IFreeSqlFactory.cs b/src/AgileConfig.Server.Data.Freesql/IFreeSqlFactory.cs index e7966ed1..9e618d39 100644 --- a/src/AgileConfig.Server.Data.Freesql/IFreeSqlFactory.cs +++ b/src/AgileConfig.Server.Data.Freesql/IFreeSqlFactory.cs @@ -2,6 +2,6 @@ { public interface IFreeSqlFactory { - IFreeSql Create(string env); + IFreeSql Create(string env = ""); } } \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs b/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs index 120e5e81..660fe15d 100644 --- a/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs +++ b/src/AgileConfig.Server.Data.Freesql/ServiceCollectionExt.cs @@ -8,7 +8,6 @@ public static class ServiceCollectionExt public static void AddFreeSqlFactory(this IServiceCollection sc) { sc.AddScoped(); - sc.AddSingleton(FreeSQL.Instance); sc.AddSingleton(); } } diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs index a37870d4..4d0e3d2d 100644 --- a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs @@ -13,7 +13,7 @@ public class MongodbRepository : Abstraction.IRepository _access; - public IUow Uow { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } + public IUow Uow { get; set; } public MongodbRepository(string? connectionString) { @@ -36,8 +36,8 @@ public async Task> AllAsync() { return await _access.MongoQueryable.ToListAsync(); } - - private Expression> GetIdPropertyFilter(TId id) + + private Expression> GetIdPropertyFilter(TId id) { Expression> expression = x => Equals(x.Id, id); return expression; @@ -89,7 +89,7 @@ public async Task InsertAsync(TEntity entity) public async Task InsertAsync(IList entities) { - if(entities.Count > 0) + if (entities.Count > 0) await _access.Collection.InsertManyAsync(entities); } @@ -127,7 +127,7 @@ private Expression> Sort(string defaultSortField) } var parameter = Expression.Parameter(typeof(TEntity), "__q"); var memberExpress = Expression.Property(parameter, property); - return Expression.Lambda>(memberExpress, parameter); + return Expression.Lambda>(memberExpress, parameter); } return defaultSort; } diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbUow.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbUow.cs new file mode 100644 index 00000000..ad8f89a9 --- /dev/null +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbUow.cs @@ -0,0 +1,21 @@ +namespace AgileConfig.Server.Data.Mongodb +{ + /// + /// This is a empty implementation of IUow for mongodb. + /// + public class MongodbUow : Abstraction.IUow + { + public Task SaveChangesAsync() + { + return Task.FromResult(true); + } + + public void Dispose() + { + } + + public void Begin() + { + } + } +} diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs index 6fd9ece6..2866f81f 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/AppInheritancedRepository.cs @@ -6,11 +6,11 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class AppInheritancedRepository : FreesqlRepository, IAppInheritancedRepository { - private readonly IFreeSql freeSql; + private readonly IFreeSqlFactory freeSqlFactory; - public AppInheritancedRepository(IFreeSql freeSql) : base(freeSql) + public AppInheritancedRepository(IFreeSqlFactory freeSqlFactory) : base(freeSqlFactory.Create()) { - this.freeSql = freeSql; + this.freeSqlFactory = freeSqlFactory; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs index 523d159e..c63b9e26 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/AppRepository.cs @@ -6,11 +6,11 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class AppRepository : FreesqlRepository, IAppRepository { - private readonly IFreeSql freeSql; + private readonly IFreeSqlFactory freeSqlFactory; - public AppRepository(IFreeSql freeSql) : base(freeSql) + public AppRepository(IFreeSqlFactory freeSqlFactory) : base(freeSqlFactory.Create()) { - this.freeSql = freeSql; + this.freeSqlFactory = freeSqlFactory; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs index 7569340d..9917b27a 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ConfigRepository.cs @@ -6,11 +6,11 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class ConfigRepository : FreesqlRepository, IConfigRepository { - private readonly IFreeSql _freeSql; + private readonly IFreeSql freeSql; public ConfigRepository(IFreeSql freeSql) : base(freeSql) { - this._freeSql = freeSql; + this.freeSql = freeSql; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs index 9a7b1644..e472101e 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServerNodeRepository.cs @@ -6,11 +6,11 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class ServerNodeRepository : FreesqlRepository, IServerNodeRepository { - private readonly IFreeSql freeSql; + private readonly IFreeSqlFactory freeSqlFactory; - public ServerNodeRepository(IFreeSql freeSql) : base(freeSql) + public ServerNodeRepository(IFreeSqlFactory freeSqlFactory) : base(freeSqlFactory.Create()) { - this.freeSql = freeSql; + this.freeSqlFactory = freeSqlFactory; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs index 47c60d1e..0efb712c 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/ServiceInfoRepository.cs @@ -6,11 +6,11 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class ServiceInfoRepository : FreesqlRepository, IServiceInfoRepository { - private readonly IFreeSql freeSql; + private readonly IFreeSqlFactory freeSqlFactory; - public ServiceInfoRepository(IFreeSql freeSql) : base(freeSql) + public ServiceInfoRepository(IFreeSqlFactory freeSqlFactory) : base(freeSqlFactory.Create()) { - this.freeSql = freeSql; + this.freeSqlFactory = freeSqlFactory; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs index e0ac6097..e5bd5d62 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SettingRepository.cs @@ -6,11 +6,11 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class SettingRepository : FreesqlRepository, ISettingRepository { - private readonly IFreeSql freeSql; + private readonly IFreeSqlFactory freeSqlFactory; - public SettingRepository(IFreeSql freeSql) : base(freeSql) + public SettingRepository(IFreeSqlFactory freeSqlFactory) : base(freeSqlFactory.Create()) { - this.freeSql = freeSql; + this.freeSqlFactory = freeSqlFactory; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs index f5b2f8e4..e80789e0 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs @@ -7,15 +7,22 @@ namespace AgileConfig.Server.Data.Repository.Freesql; public class SysInitRepository : ISysInitRepository { + private readonly IFreeSqlFactory freeSqlFactory; + + public SysInitRepository(IFreeSqlFactory freeSqlFactory) + { + this.freeSqlFactory = freeSqlFactory; + } + public string? GetJwtTokenSecret() { - var setting = FreeSQL.Instance.Select().Where(x => x.Id == SystemSettings.DefaultJwtSecretKey) + var setting = freeSqlFactory.Create().Select().Where(x => x.Id == SystemSettings.DefaultJwtSecretKey) .ToOne(); return setting?.Value; } public void SaveInitSetting(Setting setting) { - FreeSQL.Instance.Insert(setting).ExecuteAffrows(); + freeSqlFactory.Create().Insert(setting).ExecuteAffrows(); } } \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs index 37ae0da2..bc5bbe69 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SysLogRepository.cs @@ -4,14 +4,14 @@ namespace AgileConfig.Server.Data.Repository.Freesql { - public class SysLogRepository : FreesqlRepository, ISysLogRepository + public class SysLogRepository : FreesqlRepository, ISysLogRepository { - private readonly IFreeSql freeSql; + private readonly IFreeSqlFactory freeSqlFactory; - public SysLogRepository(IFreeSql freeSql) : base(freeSql) + public SysLogRepository(IFreeSqlFactory freeSqlFactory) : base(freeSqlFactory.Create()) { - this.freeSql = freeSql; + this.freeSqlFactory = freeSqlFactory; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs index 5333a5d8..9dde4915 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserAppAuthRepository.cs @@ -7,11 +7,11 @@ namespace AgileConfig.Server.Data.Repository.Freesql public class UserAppAuthRepository : FreesqlRepository, IUserAppAuthRepository { - private readonly IFreeSql freeSql; + private readonly IFreeSqlFactory freeSqlFactory; - public UserAppAuthRepository(IFreeSql freeSql) : base(freeSql) + public UserAppAuthRepository(IFreeSqlFactory freeSqlFactory) : base(freeSqlFactory.Create()) { - this.freeSql = freeSql; + this.freeSqlFactory = freeSqlFactory; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs index a93e3324..a54326f8 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserRepository.cs @@ -1,18 +1,17 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Data.Repository.Freesql { public class UserRepository : FreesqlRepository, IUserRepository { - private readonly IFreeSql freeSql; + private readonly IFreeSqlFactory freeSqlFactory; - public UserRepository(IFreeSql freeSql) : base(freeSql) + public UserRepository(IFreeSqlFactory freeSqlFactory) : base(freeSqlFactory.Create()) { - this.freeSql = freeSql; + this.freeSqlFactory = freeSqlFactory; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs index a85d12d0..e8ff5c24 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/UserRoleRepository.cs @@ -6,11 +6,11 @@ namespace AgileConfig.Server.Data.Repository.Freesql { public class UserRoleRepository : FreesqlRepository, IUserRoleRepository { - private readonly IFreeSql freeSql; + private readonly IFreeSqlFactory freeSqlFactory; - public UserRoleRepository(IFreeSql freeSql) : base(freeSql) + public UserRoleRepository(IFreeSqlFactory freeSqlFactory) : base(freeSqlFactory.Create()) { - this.freeSql = freeSql; + this.freeSqlFactory = freeSqlFactory; } } } diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs index e9f341d7..177c91a1 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/MongodbRepositoryExt.cs @@ -4,6 +4,8 @@ public static class MongodbRepositoryExt { public static void AddMongodbRepository(this IServiceCollection services) { + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/SysLogRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/SysLogRepository.cs index d4dca8f3..60cff515 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/SysLogRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/SysLogRepository.cs @@ -1,6 +1,6 @@ namespace AgileConfig.Server.Data.Repository.Mongodb; -public class SysLogRepository: MongodbRepository, ISysLogRepository +public class SysLogRepository: MongodbRepository, ISysLogRepository { public SysLogRepository(string? connectionString) : base(connectionString) { diff --git a/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs b/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs index 1fbbfad6..246bb6c7 100644 --- a/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs +++ b/src/AgileConfig.Server.Data.Repository.Selector/RepositoryExtension.cs @@ -1,6 +1,8 @@ using AgileConfig.Server.Common; using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Abstraction.DbProvider; using AgileConfig.Server.Data.Freesql; +using AgileConfig.Server.Data.Mongodb; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -12,16 +14,15 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) { sc.AddFreeRepository(); - var config = Global.Config; - var defaultProvider = config["db:provider"]; + var defaultProvider = DbConfigInfoFactory.GetConfigInfo(); - if (string.IsNullOrEmpty(defaultProvider)) + if (string.IsNullOrEmpty(defaultProvider.Provider)) { throw new ArgumentNullException(nameof(defaultProvider)); } - #region these repository will use default conn provider - if (defaultProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) + #region these repository will use default provider + if (defaultProvider.Provider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) { sc.AddScoped(); sc.AddScoped(); @@ -52,11 +53,11 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) #region these repositories genereated dependency env provider, if no env provider use default provider sc.AddScoped>(sp => env => { - string envProvider = GetEnvProvider(env, config, defaultProvider); + var envDbConfig = DbConfigInfoFactory.GetConfigInfo(env); - if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) + if (envDbConfig.Provider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) { - return null; + return new MongodbUow(); // currently this is an empty uow } else { @@ -68,11 +69,11 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) sc.AddScoped>(sp => env => { - string envProvider = GetEnvProvider(env, config, defaultProvider); + var envDbConfig = DbConfigInfoFactory.GetConfigInfo(env); - if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) + if (envDbConfig.Provider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) { - return new Mongodb.ConfigPublishedRepository(GetConnectionString(env, config)); + return new Mongodb.ConfigPublishedRepository(envDbConfig.ConnectionString); } else { @@ -83,11 +84,11 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) sc.AddScoped>(sp => env => { - string envProvider = GetEnvProvider(env, config, defaultProvider); + var envDbConfig = DbConfigInfoFactory.GetConfigInfo(env); - if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) + if (envDbConfig.Provider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) { - return new Mongodb.ConfigRepository(GetConnectionString(env, config)); + return new Mongodb.ConfigRepository(envDbConfig.ConnectionString); } else { @@ -99,11 +100,11 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) sc.AddScoped>(sp => env => { - string envProvider = GetEnvProvider(env, config, defaultProvider); + var envDbConfig = DbConfigInfoFactory.GetConfigInfo(env); - if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) + if (envDbConfig.Provider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) { - return new Mongodb.PublishDetailRepository(GetConnectionString(env, config)); + return new Mongodb.PublishDetailRepository(envDbConfig.ConnectionString); } else { @@ -114,11 +115,11 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) sc.AddScoped>(sp => env => { - string envProvider = GetEnvProvider(env, config, defaultProvider); + var envDbConfig = DbConfigInfoFactory.GetConfigInfo(env); - if (envProvider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) + if (envDbConfig.Provider.Equals("mongodb", StringComparison.OrdinalIgnoreCase)) { - return new Mongodb.PublishTimelineRepository(GetConnectionString(env, config)); + return new Mongodb.PublishTimelineRepository(envDbConfig.ConnectionString); } else { @@ -131,22 +132,5 @@ public static IServiceCollection AddRepositories(this IServiceCollection sc) return sc; } - private static string GetEnvProvider(string env, IConfiguration config, string defaultProvider) - { - var envProviderKey = $"db:env:{env}:provider"; - var envProvider = config[envProviderKey]; - if (string.IsNullOrEmpty(envProvider)) - { - // use default provider - envProvider = defaultProvider; - } - - return envProvider; - } - - private static string? GetConnectionString(string env, IConfiguration config) - { - return string.IsNullOrEmpty(env) ? config["db:conn"] : config[$"db:env:{env}:conn"]; - } } } \ No newline at end of file diff --git a/src/AgileConfig.Server.Service/ConfigService.cs b/src/AgileConfig.Server.Service/ConfigService.cs index 48289bc0..04e2a49d 100644 --- a/src/AgileConfig.Server.Service/ConfigService.cs +++ b/src/AgileConfig.Server.Service/ConfigService.cs @@ -720,11 +720,19 @@ public async Task GetPublishedConfigAsync(string configId, stri public async Task RollbackAsync(string publishTimelineId, string env) { + using var uow = _uowAccessor(env); + using var configRepository = _configRepositoryAccessor(env); using var publishTimelineRepository = _publishTimelineRepositoryAccsssor(env); using var configPublishedRepository = _configPublishedRepositoryAccessor(env); using var publishDetailRepository = _publishDetailRepositoryAccessor(env); + configRepository.Uow = uow; + publishTimelineRepository.Uow = uow; + configPublishedRepository.Uow = uow; + publishDetailRepository.Uow = uow; + + uow?.Begin(); var publishNode = (await publishTimelineRepository.QueryAsync(x => x.Id == publishTimelineId && x.Env == env)).FirstOrDefault(); @@ -782,6 +790,8 @@ public async Task RollbackAsync(string publishTimelineId, string env) var deletePublishDetailItems = await publishDetailRepository.QueryAsync(x => x.AppId == appId && x.Env == env && x.Version > version); await publishDetailRepository.DeleteAsync(deletePublishDetailItems); + await uow?.SaveChangesAsync(); + ClearAppPublishedConfigsMd5Cache(appId, env); ClearAppPublishedConfigsMd5CacheWithInheritanced(appId, env); @@ -865,8 +875,13 @@ public async Task>> GetKvListAsync(string appI private async Task SaveFromDictAsync(IDictionary dict, string appId, string env, bool isPatch) { + using var uow = _uowAccessor(env); using var configRepository = _configRepositoryAccessor(env); + configRepository.Uow = uow; + + uow?.Begin(); + var currentConfigs = await configRepository .QueryAsync(x => x.AppId == appId && x.Env == env && x.Status == ConfigStatus.Enabled); var addConfigs = new List(); @@ -959,6 +974,8 @@ private async Task SaveFromDictAsync(IDictionary dict, str await configRepository.UpdateAsync(deleteConfigs); } + await uow?.SaveChangesAsync(); + return true; } diff --git a/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs b/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs index ba17c5e8..5aef004e 100644 --- a/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs +++ b/src/AgileConfig.Server.Service/EventRegisterService/SysLogRegister.cs @@ -62,7 +62,18 @@ public void Register() Task.Run(async () => { await _sysLogService.AddSysLogAsync(log); - }); + }) + .ContinueWith(x => + { + if (x.IsFaulted) + { + foreach (var ex in x.Exception?.InnerExceptions ?? new(Array.Empty())) + { + throw ex; + } + } + }) + ; }); TinyEventBus.Instance.Register(EventKeys.CHANGE_USER_PASSWORD_SUCCESS, (param) => diff --git a/src/AgileConfig.Server.Service/SysLogService.cs b/src/AgileConfig.Server.Service/SysLogService.cs index b7c570f4..79fa8999 100644 --- a/src/AgileConfig.Server.Service/SysLogService.cs +++ b/src/AgileConfig.Server.Service/SysLogService.cs @@ -87,7 +87,7 @@ public async Task> SearchPage(string appId, SysLogType? logType, Da exp = exp.And(x => x.LogType == logType); } - var list = await _sysLogRepository.QueryPageAsync(exp, pageIndex, pageSize, defaultSortType: "DESC"); + var list = await _sysLogRepository.QueryPageAsync(exp, pageIndex, pageSize, defaultSortField: "LogTime", defaultSortType: "DESC"); return list; } } From 5e77ba9287d421b03664154e120dad8b71af7295 Mon Sep 17 00:00:00 2001 From: pengqian089 Date: Sun, 7 Jan 2024 07:37:25 +0800 Subject: [PATCH 29/45] =?UTF-8?q?mongodb=20=E4=BA=8B=E5=8A=A1=E9=80=82?= =?UTF-8?q?=E9=85=8D;=20=E4=BF=AE=E5=A4=8D=E6=89=B9=E9=87=8F=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=EF=BC=8C=E7=A9=BA=E9=A1=B9=E9=9B=86=E5=90=88=E6=8A=A5?= =?UTF-8?q?=E9=94=99=E7=9A=84bug;=20=E4=BF=AE=E5=A4=8D=E5=88=86=E9=A1=B5?= =?UTF-8?q?=E6=8E=92=E5=BA=8F=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../IUow.cs | 2 + .../FreeSqlUow.cs | 5 + .../IRepository.cs | 118 --- .../MongodbRepository.cs | 118 ++- .../MongodbUow.cs | 43 +- .../Repository.cs | 181 ---- .../ConfigService.cs | 4 +- .../AgileConfig.Server.ServiceTests.csproj | 2 + .../mongodb/Basic.cs | 75 ++ .../mongodb/ConfigServiceTests.cs | 929 ++++++++++++++++++ .../mongodb/SysLogServiceTests.cs | 217 ++++ 11 files changed, 1367 insertions(+), 327 deletions(-) delete mode 100644 src/AgileConfig.Server.Data.Mongodb/IRepository.cs delete mode 100644 src/AgileConfig.Server.Data.Mongodb/Repository.cs create mode 100644 test/AgileConfig.Server.ServiceTests/mongodb/Basic.cs create mode 100644 test/AgileConfig.Server.ServiceTests/mongodb/ConfigServiceTests.cs create mode 100644 test/AgileConfig.Server.ServiceTests/mongodb/SysLogServiceTests.cs diff --git a/src/AgileConfig.Server.Data.Abstraction/IUow.cs b/src/AgileConfig.Server.Data.Abstraction/IUow.cs index dd8fa9aa..00861a67 100644 --- a/src/AgileConfig.Server.Data.Abstraction/IUow.cs +++ b/src/AgileConfig.Server.Data.Abstraction/IUow.cs @@ -12,5 +12,7 @@ public interface IUow : IDisposable Task SaveChangesAsync(); + void Rollback(); + } } diff --git a/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs b/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs index b6f4a819..cbe7cbda 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs @@ -31,6 +31,11 @@ public Task SaveChangesAsync() return Task.FromResult(true); } + public void Rollback() + { + _unitOfWork.Rollback(); + } + public void Dispose() { _unitOfWork?.Dispose(); diff --git a/src/AgileConfig.Server.Data.Mongodb/IRepository.cs b/src/AgileConfig.Server.Data.Mongodb/IRepository.cs deleted file mode 100644 index ba32027f..00000000 --- a/src/AgileConfig.Server.Data.Mongodb/IRepository.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System.Linq.Expressions; -using MongoDB.Bson; -using MongoDB.Driver; -using MongoDB.Driver.Linq; - -namespace AgileConfig.Server.Data.Mongodb; - -public interface IRepository -{ - IMongoDatabase Database { get; } -} - -public interface IRepository : IRepository where T : new() -{ - /// - /// mongodb客户端 - /// - IMongoClient Client { get; } - - /// - /// 获取 该实体Mongodb的集合 - /// - IMongoCollection Collection { get; } - - /// - /// Mongodb queryable - /// - IMongoQueryable MongodbQueryable { get; } - - /// - /// 查询数据 - /// - /// - /// - IMongoQueryable SearchFor(Expression> predicate); - - /// - /// 异步 数据查询 - /// - /// - /// - IAsyncEnumerable SearchForAsync(FilterDefinition filter); - - /// - /// 根据 Id 获取单条记录,不存在将会返回null - /// - /// - /// - T? Find(object id); - - /// - /// 根据 Id 获取单条记录,不存在将会返回null - /// - /// - /// - Task FindAsync(object id); - - void Insert(params T[] source); - - void Insert(IReadOnlyCollection source); - - /// - /// 插入数据 - /// - /// - /// - Task InsertAsync(params T[] source); - - /// - /// 插入数据 - /// - /// - /// - Task InsertAsync(IReadOnlyCollection source); - - /// - /// 删除数据 - /// - /// - /// - Task DeleteAsync(Expression> filter); - - /// - /// 删除数据 - /// - /// - /// - Task DeleteAsync(FilterDefinition filter); - - /// - /// 根据ID删除 - /// - /// - /// - Task DeleteAsync(string id); - - /// - /// 根据查询条件更新数据 - /// - /// - /// - /// - Task UpdateAsync(Expression> predicate, UpdateDefinition update); - - /// - /// 根据实体修改数据 - /// - /// - /// - /// If the entity no exists property 'id',then will throw exception. - Task UpdateAsync(T entity); - - Task> UpdateAsync(IEnumerable entities); - - ReplaceOneResult Update(T entity); - - BulkWriteResult Update(IEnumerable entities); -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs index 4d0e3d2d..066e411d 100644 --- a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs @@ -8,12 +8,25 @@ namespace AgileConfig.Server.Data.Mongodb; -public class MongodbRepository : Abstraction.IRepository +public class MongodbRepository : IRepository where TEntity : IEntity, new() { private readonly MongodbAccess _access; - public IUow Uow { get; set; } + public IUow Uow + { + get => _mongodbUow; + set + { + _mongodbUow = value as MongodbUow; + if (_mongodbUow?.Session == null && _mongodbUow?.Session?.IsInTransaction != true) + { + _mongodbUow?.SetSession(_access.Client.StartSession()); + } + } + } + + private MongodbUow? _mongodbUow; public MongodbRepository(string? connectionString) { @@ -51,8 +64,16 @@ private Expression> GetIdPropertyFilter(TId id) public async Task UpdateAsync(TEntity entity) { - var filter = GetIdPropertyFilter(entity.Id); - await _access.Collection.ReplaceOneAsync(filter, entity); + if (_mongodbUow?.Session == null) + { + var filter = GetIdPropertyFilter(entity.Id); + await _access.Collection.ReplaceOneAsync(filter, entity); + } + else + { + var filter = GetIdPropertyFilter(entity.Id); + await _access.Collection.ReplaceOneAsync(_mongodbUow.Session, filter, entity); + } } public async Task UpdateAsync(IList entities) @@ -60,37 +81,85 @@ public async Task UpdateAsync(IList entities) var writes = entities .Select(x => new ReplaceOneModel(GetIdPropertyFilter(x.Id), x)) .ToList(); - await _access.Collection.BulkWriteAsync(writes); + if (writes.Count > 0) + { + if (_mongodbUow?.Session == null) + { + await _access.Collection.BulkWriteAsync(writes); + } + else + { + await _access.Collection.BulkWriteAsync(_mongodbUow.Session, writes); + } + } } public async Task DeleteAsync(TId id) { var filter = Builders.Filter.Eq(x => x.Id, id); - await _access.Collection.DeleteOneAsync(filter); + if (_mongodbUow?.Session == null) + { + await _access.Collection.DeleteOneAsync(filter); + } + else + { + await _access.Collection.DeleteOneAsync(_mongodbUow.Session, filter); + } } public async Task DeleteAsync(TEntity entity) { var filter = GetIdPropertyFilter(entity.Id); - await _access.Collection.DeleteOneAsync(filter); + if (_mongodbUow?.Session == null) + { + await _access.Collection.DeleteOneAsync(filter); + } + else + { + await _access.Collection.DeleteOneAsync(_mongodbUow.Session, filter); + } } public async Task DeleteAsync(IList entities) { var filter = Builders.Filter.In(x => x.Id, entities.Select(y => y.Id)); - await _access.Collection.DeleteManyAsync(filter); + if (_mongodbUow?.Session == null) + { + await _access.Collection.DeleteManyAsync(filter); + } + else + { + await _access.Collection.DeleteManyAsync(_mongodbUow.Session, filter); + } } public async Task InsertAsync(TEntity entity) { - await _access.Collection.InsertOneAsync(entity); + if (_mongodbUow?.Session == null) + { + await _access.Collection.InsertOneAsync(entity); + } + else + { + await _access.Collection.InsertOneAsync(_mongodbUow.Session, entity); + } + return entity; } public async Task InsertAsync(IList entities) { if (entities.Count > 0) - await _access.Collection.InsertManyAsync(entities); + { + if (_mongodbUow?.Session == null) + { + await _access.Collection.InsertManyAsync(entities); + } + else + { + await _access.Collection.InsertManyAsync(_mongodbUow.Session, entities); + } + } } public async Task> QueryAsync(Expression> exp) @@ -98,23 +167,23 @@ public async Task> QueryAsync(Expression> exp) return await _access.MongoQueryable.Where(exp).ToListAsync(); } - public async Task> QueryPageAsync(Expression> exp, int pageIndex, int pageSize, string defaultSortField = "Id", + public async Task> QueryPageAsync(Expression> exp, int pageIndex, int pageSize, + string defaultSortField = "Id", string defaultSortType = "ASC") { + if (pageIndex < 1) + return new List(); + if (pageSize <= 0) + return new List(); var query = _access.MongoQueryable.Where(exp); var sort = Sort(defaultSortField); - if (string.Equals(defaultSortField, "DESC", StringComparison.OrdinalIgnoreCase)) - { - query.OrderByDescending(sort); - } - else - { - query.OrderBy(sort); - } + query = string.Equals(defaultSortField, "DESC", StringComparison.OrdinalIgnoreCase) + ? query.OrderByDescending(sort) + : query.OrderBy(sort); return await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); } - private Expression> Sort(string defaultSortField) + private static Expression> Sort(string defaultSortField) { Expression> defaultSort = x => x.Id; if (!string.IsNullOrEmpty(defaultSortField) && @@ -125,15 +194,20 @@ private Expression> Sort(string defaultSortField) { return defaultSort; } + var parameter = Expression.Parameter(typeof(TEntity), "__q"); var memberExpress = Expression.Property(parameter, property); - return Expression.Lambda>(memberExpress, parameter); + var convertExpress = Expression.Convert(memberExpress, typeof(object)); + return Expression.Lambda>(convertExpress, parameter); } + return defaultSort; } public async Task CountAsync(Expression>? exp = null) { - return await (exp == null ? _access.MongoQueryable.CountAsync() : _access.MongoQueryable.Where(exp).CountAsync()); + return await (exp == null + ? _access.MongoQueryable.CountAsync() + : _access.MongoQueryable.Where(exp).CountAsync()); } } \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbUow.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbUow.cs index ad8f89a9..e4f65827 100644 --- a/src/AgileConfig.Server.Data.Mongodb/MongodbUow.cs +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbUow.cs @@ -1,21 +1,56 @@ -namespace AgileConfig.Server.Data.Mongodb +using MongoDB.Driver; + +namespace AgileConfig.Server.Data.Mongodb { /// /// This is a empty implementation of IUow for mongodb. /// public class MongodbUow : Abstraction.IUow { - public Task SaveChangesAsync() + public IClientSessionHandle? Session { get; private set; } + + public async Task SaveChangesAsync() + { + await Session?.CommitTransactionAsync()!; + return true; + } + + public void Rollback() { - return Task.FromResult(true); + Session?.AbortTransaction(); + } + + private bool _disposed; + private void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + Session?.Dispose(); + } + + _disposed = true; + } } public void Dispose() { + Dispose(true); + GC.SuppressFinalize(this); } public void Begin() { + if (Session?.IsInTransaction != true) + { + Session?.StartTransaction(); + } + } + + internal void SetSession(IClientSessionHandle session) + { + Session = session; } } -} +} \ No newline at end of file diff --git a/src/AgileConfig.Server.Data.Mongodb/Repository.cs b/src/AgileConfig.Server.Data.Mongodb/Repository.cs deleted file mode 100644 index 7ff6f006..00000000 --- a/src/AgileConfig.Server.Data.Mongodb/Repository.cs +++ /dev/null @@ -1,181 +0,0 @@ -using System.Linq.Expressions; -using System.Reflection; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using MongoDB.Bson.Serialization.Attributes; -using MongoDB.Driver; -using MongoDB.Driver.Linq; - -namespace AgileConfig.Server.Data.Mongodb; - -public class Repository : IRepository where T : new() -{ - public IMongoDatabase Database => _access.Database; - public IMongoClient Client => _access.Client; - public IMongoCollection Collection => _access.Collection; - public IMongoQueryable MongodbQueryable => _access.MongoQueryable; - - private readonly MongodbAccess _access; - - public Repository(string? connectionString) - { - _access = new MongodbAccess(connectionString); - } - - [ActivatorUtilitiesConstructor] - public Repository(IConfiguration configuration) - { - var connectionString = configuration["db:conn"]; - _access = new MongodbAccess(connectionString); - } - - public IMongoQueryable SearchFor(Expression> predicate) - { - return _access.MongoQueryable.Where(predicate); - } - - public async IAsyncEnumerable SearchForAsync(FilterDefinition filter) - { - var result = await Collection.FindAsync(filter); - while (await result.MoveNextAsync()) - { - foreach (var item in result.Current) - { - yield return item; - } - } - } - - public T? Find(object id) - { - var filter = GetIdPropertyFilter(id); - return Collection.Find(filter).SingleOrDefault(); - } - - public async Task FindAsync(object id) - { - var filter = GetIdPropertyFilter(id); - return await (await Collection.FindAsync(filter)).SingleOrDefaultAsync(); - } - - private static Expression> GetIdPropertyFilter(object idValue) - { - var idProperty = GetIdProperty(); - if (idValue == null) - throw new Exception($"The entity property '{idProperty.Name}' value is null."); - - var parameter = Expression.Parameter(typeof(T), "__q"); - var memberExpress = Expression.Property(parameter, idProperty); - var expression = - Expression.Lambda>(Expression.Equal(memberExpress, Expression.Constant(idValue)),parameter); - - return expression; - } - - public void Insert(params T[] source) - { - if(source.Length != 0) - Collection.InsertMany(source); - } - - public void Insert(IReadOnlyCollection source) - { - if(source.Count != 0) - Collection.InsertMany(source); - } - - public async Task InsertAsync(params T[] source) - { - if(source.Length != 0) - await Collection.InsertManyAsync(source); - } - - public async Task InsertAsync(IReadOnlyCollection source) - { - if(source.Count != 0) - await Collection.InsertManyAsync(source); - } - - public async Task DeleteAsync(Expression> filter) - { - var result = await Collection.DeleteManyAsync(filter); - return result; - } - - public async Task DeleteAsync(FilterDefinition filter) - { - var result = await Collection.DeleteManyAsync(filter); - return result; - } - - public async Task DeleteAsync(string id) - { - var filter = GetIdPropertyFilter(id); - return await Collection.DeleteOneAsync(filter); - } - - public async Task UpdateAsync(Expression> predicate, UpdateDefinition update) - { - var result = await Collection.UpdateManyAsync(predicate, update); - return result; - } - - private static PropertyInfo GetIdProperty() - { - var idProperty = typeof(T).GetProperty("Id") ?? typeof(T).GetProperties().FirstOrDefault(x => - { - var attribute = x.GetCustomAttribute(typeof(BsonIdAttribute)); - return attribute != null; - }); - if (idProperty == null) - throw new Exception("In the entity no exists property 'id'."); - return idProperty; - } - - private static Expression> GetIdPropertyFilter(T entity) - { - var idProperty = GetIdProperty(); - var idValue = idProperty.GetValue(entity); - if (idValue == null) - throw new ArgumentException($"The entity property '{idProperty.Name}' value is null.", nameof(entity)); - - var parameter = Expression.Parameter(typeof(T), "__q"); - var memberExpress = Expression.Property(parameter, idProperty); - var expression = - Expression.Lambda>(Expression.Equal(memberExpress, Expression.Constant(idValue))); - - return expression; - } - - public async Task UpdateAsync(T entity) - { - var filter = GetIdPropertyFilter(entity); - var result = await Collection.ReplaceOneAsync(filter, entity); - return result; - } - - public async Task> UpdateAsync(IEnumerable entities) - { - var writes = entities - .Select(x => new ReplaceOneModel(GetIdPropertyFilter(x), x)) - .ToList(); - return await Collection.BulkWriteAsync(writes); - } - - public ReplaceOneResult Update(T entity) - { - var filter = GetIdPropertyFilter(entity); - var result = Collection.ReplaceOne(filter, entity); - return result; - } - - public BulkWriteResult Update(IEnumerable entities) - { - var writes = entities - .Select(x => new ReplaceOneModel(GetIdPropertyFilter(x), x)) - .ToList(); - return Collection.BulkWrite(writes); - } - - -} \ No newline at end of file diff --git a/src/AgileConfig.Server.Service/ConfigService.cs b/src/AgileConfig.Server.Service/ConfigService.cs index 04e2a49d..f5342d78 100644 --- a/src/AgileConfig.Server.Service/ConfigService.cs +++ b/src/AgileConfig.Server.Service/ConfigService.cs @@ -470,10 +470,9 @@ public void Dispose() public async Task<(bool result, string publishTimelineId)> Publish(string appId, string[] ids, string log, string operatorr, string env) { await _lock.WaitAsync(); + using var uow = _uowAccessor(env); try { - using var uow = _uowAccessor(env); - using var configRepository = _configRepositoryAccessor(env); configRepository.Uow = uow; using var publishTimelineRepository = _publishTimelineRepositoryAccsssor(env); @@ -637,6 +636,7 @@ public void Dispose() } catch (Exception exc) { + uow?.Rollback(); throw; } finally diff --git a/test/AgileConfig.Server.ServiceTests/AgileConfig.Server.ServiceTests.csproj b/test/AgileConfig.Server.ServiceTests/AgileConfig.Server.ServiceTests.csproj index 4de281c3..11941be0 100644 --- a/test/AgileConfig.Server.ServiceTests/AgileConfig.Server.ServiceTests.csproj +++ b/test/AgileConfig.Server.ServiceTests/AgileConfig.Server.ServiceTests.csproj @@ -19,6 +19,8 @@ + + diff --git a/test/AgileConfig.Server.ServiceTests/mongodb/Basic.cs b/test/AgileConfig.Server.ServiceTests/mongodb/Basic.cs new file mode 100644 index 00000000..544d7263 --- /dev/null +++ b/test/AgileConfig.Server.ServiceTests/mongodb/Basic.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.Data.Repository.Mongodb; +using AgileConfig.Server.IService; +using AgileConfig.Server.Service; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Moq; + +namespace AgileConfig.Server.ServiceTests.mongodb; + +public abstract class Basic +{ + private static readonly Dictionary ConfigurationData = new Dictionary + { + { + "db:provider", + "mongodb" + }, + { + "db:conn", + "mongodb://localhost:27017;localhost:37017/AgileConfig" + } + }; + private static void InitServices(IServiceCollection sc, string connectionString) + { + sc.AddTransient>(_ => _ => new MongodbUow()); + + sc.AddScoped>( + _ => _ => new ConfigPublishedRepository(connectionString)); + + sc.AddScoped>(_ => _ => new ConfigRepository(connectionString)); + + sc.AddScoped>(_ => _ => new PublishDetailRepository(connectionString)); + + sc.AddScoped>( + _ => _ => new PublishTimelineRepository(connectionString)); + } + + private readonly ServiceProvider _serviceProvider; + + protected Basic() + { + var config = new ConfigurationBuilder() + .AddInMemoryCollection(ConfigurationData) + .Build(); + var cache = new Mock(); + IServiceCollection services = new ServiceCollection(); + services.AddScoped(_ => cache.Object); + services.AddSingleton(config); + InitServices(services, ConfigurationData["db:conn"]); + services.AddMongodbRepository(); + services.AddBusinessServices(); + _serviceProvider = services.BuildServiceProvider(); + Console.WriteLine("TestInitialize"); + } + + protected T GetService() + { + return _serviceProvider.GetService(); + } + + protected IConfigRepository ConfigRepository => _serviceProvider.GetService(); + + protected IAppRepository AppRepository => _serviceProvider.GetService(); + + protected IAppInheritancedRepository AppInheritancedRepository => + _serviceProvider.GetService(); + + protected ISysLogRepository SysLogRepository => + _serviceProvider.GetService(); +} \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mongodb/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mongodb/ConfigServiceTests.cs new file mode 100644 index 00000000..b0f7f02e --- /dev/null +++ b/test/AgileConfig.Server.ServiceTests/mongodb/ConfigServiceTests.cs @@ -0,0 +1,929 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Abstraction.DbProvider; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Freesql; +using AgileConfig.Server.Data.Mongodb; +using AgileConfig.Server.Data.Repository.Mongodb; +using AgileConfig.Server.Data.Repository.Selector; +using AgileConfig.Server.IService; +using AgileConfig.Server.Service; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace AgileConfig.Server.ServiceTests.mongodb; + +[TestClass] +public class ConfigServiceTests : Basic +{ + IConfigService service = null; + + + [TestInitialize] + public void TestInitialize() + { + service = GetService(); + } + + + [TestCleanup] + public void Clean() + { + } + + [TestMethod()] + public async Task AddAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var config = await ConfigRepository.GetAsync(id); + + + Assert.IsTrue(result); + Assert.IsNotNull(config); + + Assert.AreEqual(source.Id, config.Id); + Assert.AreEqual(source.Group, config.Group); + Assert.AreEqual(source.Key, config.Key); + Assert.AreEqual(source.Value, config.Value); + Assert.AreEqual(source.Description, config.Description); + Assert.AreEqual(source.AppId, config.AppId); + Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), + config.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), + config.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.Status, config.Status); + Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); + } + + [TestMethod()] + public async Task UpdateAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + + source.AppId = "1"; + source.Group = "1"; + source.Key = "1"; + source.Value = "1"; + source.Description = "1"; + source.CreateTime = DateTime.Now; + source.UpdateTime = DateTime.Now; + source.Status = ConfigStatus.Enabled; + source.OnlineStatus = OnlineStatus.WaitPublish; + + var result1 = await service.UpdateAsync(source, ""); + var config = await ConfigRepository.GetAsync(id); + + Assert.IsTrue(result1); + Assert.IsNotNull(config); + + Assert.AreEqual(source.Id, config.Id); + Assert.AreEqual(source.Group, config.Group); + Assert.AreEqual(source.Key, config.Key); + Assert.AreEqual(source.Value, config.Value); + Assert.AreEqual(source.Description, config.Description); + Assert.AreEqual(source.AppId, config.AppId); + Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), + config.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), + config.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.Status, config.Status); + Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); + } + + [TestMethod()] + public async Task UpdateAsyncListTest() + { + var ids = Enumerable.Range(0, 10).ToDictionary(x => x, _ => Guid.NewGuid().ToString()); + var list = Enumerable.Range(0, 10).Select(x => new Config + { + AppId = "001", + Id = ids[x], + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }).ToList(); + + var result = await service.AddRangeAsync(list, ""); + Assert.IsTrue(result); + + foreach (var item in list) + { + var index = list.IndexOf(item); + item.AppId = "1" + index; + item.Group = "1" + index; + item.Key = "1" + index; + item.Value = "1" + index; + item.Description = "1"; + item.CreateTime = DateTime.Now; + item.UpdateTime = DateTime.Now; + item.Status = ConfigStatus.Enabled; + item.OnlineStatus = OnlineStatus.WaitPublish; + } + + var result1 = await service.UpdateAsync(list, ""); + var idsValue = ids.Select(x => x.Value).ToList(); + var dbConfigs = await ConfigRepository.QueryAsync(x => idsValue.Contains(x.Id)); + + Assert.IsTrue(result1); + Assert.IsNotNull(dbConfigs); + Assert.IsTrue(dbConfigs.Count > 0); + + foreach (var item in list) + { + var current = dbConfigs.FirstOrDefault(x => x.Id == item.Id); + Assert.IsNotNull(current); + + Assert.AreEqual(item.Id, current.Id); + Assert.AreEqual(item.Group, current.Group); + Assert.AreEqual(item.Key, current.Key); + Assert.AreEqual(item.Value, current.Value); + Assert.AreEqual(item.Description, current.Description); + Assert.AreEqual(item.AppId, current.AppId); + Assert.AreEqual(item.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), + current.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(item.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), + current.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(item.Status, current.Status); + Assert.AreEqual(item.OnlineStatus, current.OnlineStatus); + } + } + + [TestMethod()] + public async Task DeleteAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + + var result1 = await service.DeleteAsync(source, ""); + Assert.IsTrue(result1); + + var config = await ConfigRepository.GetAsync(id); + + Assert.IsNull(config); + } + + [TestMethod()] + public async Task DeleteAsyncTest1() + { + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + + var result1 = await service.DeleteAsync(id, ""); + Assert.IsTrue(result1); + + var config = await ConfigRepository.GetAsync(id); + + Assert.IsNull(config); + } + + [TestMethod()] + public async Task GetAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + + var config = await service.GetAsync(id, ""); + Assert.IsNotNull(config); + + Assert.AreEqual(source.Id, config.Id); + Assert.AreEqual(source.Group, config.Group); + Assert.AreEqual(source.Key, config.Key); + Assert.AreEqual(source.Value, config.Value); + Assert.AreEqual(source.Description, config.Description); + Assert.AreEqual(source.AppId, config.AppId); + Assert.AreEqual(source.CreateTime, config.CreateTime); + Assert.AreEqual(source.UpdateTime, config.UpdateTime); + Assert.AreEqual(source.Status, config.Status); + Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); + } + + [TestMethod()] + public async Task GetAllConfigsAsyncTest() + { + var all = await ConfigRepository.AllAsync(); + await ConfigRepository.DeleteAsync(all); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + + var configs = await service.GetAllConfigsAsync(""); + Assert.IsNotNull(configs); + Assert.AreEqual(1, configs.Count); + } + + [TestMethod()] + public async Task GetByAppIdKeyTest() + { + var all = await ConfigRepository.AllAsync(); + await ConfigRepository.DeleteAsync(all); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var id2 = Guid.NewGuid().ToString(); + var source2 = new Config + { + AppId = "002", + Id = id2, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + var result2 = await service.AddAsync(source2, ""); + Assert.IsTrue(result2); + + var config = await service.GetByAppIdKeyEnv("001", "g", "k", "env"); + Assert.IsNotNull(config); + + var config1 = await service.GetByAppIdKeyEnv("002", "g", "k", "env"); + Assert.IsNull(config1); + } + + [TestMethod()] + public async Task GetByAppIdTest() + { + var all = await ConfigRepository.AllAsync(); + await ConfigRepository.DeleteAsync(all); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var id2 = Guid.NewGuid().ToString(); + var source2 = new Config + { + AppId = "002", + Id = id2, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + var result2 = await service.AddAsync(source2, ""); + Assert.IsTrue(result2); + + var configs = await service.GetByAppIdAsync("001", ""); + Assert.IsNotNull(configs); + Assert.AreEqual(1, configs.Count); + } + + [TestMethod()] + public async Task SearchTest() + { + var all = await ConfigRepository.AllAsync(); + await ConfigRepository.DeleteAsync(all); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "group", + Key = "key", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var id2 = Guid.NewGuid().ToString(); + var source2 = new Config + { + AppId = "002", + Id = id2, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + var result2 = await service.AddAsync(source2, ""); + Assert.IsTrue(result2); + + var configs = await service.Search("001", "", "", ""); + Assert.IsNotNull(configs); + Assert.AreEqual(1, configs.Count); + var configs1 = await service.Search("", "o", "", ""); + Assert.IsNotNull(configs1); + Assert.AreEqual(1, configs1.Count); + var configs2 = await service.Search("", "", "e", ""); + Assert.IsNotNull(configs2); + Assert.AreEqual(1, configs2.Count); + } + + [TestMethod()] + public async Task CountEnabledConfigsAsyncTest() + { + var all = await ConfigRepository.AllAsync(); + await ConfigRepository.DeleteAsync(all); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "group", + Key = "key", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var id2 = Guid.NewGuid().ToString(); + var source2 = new Config + { + AppId = "002", + Id = id2, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + var result2 = await service.AddAsync(source2, ""); + Assert.IsTrue(result2); + + var count = await service.CountEnabledConfigsAsync(); + Assert.AreEqual(1, count); + } + + [TestMethod()] + public async Task AppPublishedConfigsMd5Test() + { + var all = await ConfigRepository.AllAsync(); + await ConfigRepository.DeleteAsync(all); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "group", + Key = "key", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var id2 = Guid.NewGuid().ToString(); + var source2 = new Config + { + AppId = "002", + Id = id2, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + var result2 = await service.AddAsync(source2, ""); + Assert.IsTrue(result2); + + var md5 = await service.AppPublishedConfigsMd5("001", ""); + Assert.IsNotNull(md5); + } + + [TestMethod()] + public void AppPublishedConfigsMd5CacheTest() + { + } + + [TestMethod()] + public async Task GetPublishedConfigsByAppIdTest() + { + var all = await ConfigRepository.AllAsync(); + await ConfigRepository.DeleteAsync(all); + + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "group", + Key = "key", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var id2 = Guid.NewGuid().ToString(); + var source2 = new Config + { + AppId = "002", + Id = id2, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + var result = await service.AddAsync(source, ""); + Assert.IsTrue(result); + var result1 = await service.AddAsync(source1, ""); + Assert.IsTrue(result1); + var result2 = await service.AddAsync(source2, ""); + Assert.IsTrue(result2); + + //var configs = await service.GetPublishedConfigsByAppId("001"); + //Assert.IsNotNull(configs); + //Assert.AreEqual(1, configs.Count); + } + + [TestMethod()] + public async Task AddRangeAsyncTest() + { + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Group = "group", + Key = "key", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Group = "g", + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Deleted, + OnlineStatus = OnlineStatus.Online + }; + + var result = await service.AddRangeAsync(new List + { + source, + source1 + }, ""); + Assert.IsTrue(result); + + var config = await ConfigRepository.GetAsync(id); + Assert.IsNotNull(config); + var config1 = await ConfigRepository.GetAsync(id); + Assert.IsNotNull(config1); + } + + [TestMethod()] + public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() + { + var appAll = await AppRepository.AllAsync(); + await AppRepository.DeleteAsync(appAll); + + var all = await ConfigRepository.AllAsync(); + await ConfigRepository.DeleteAsync(all); + + var appInheritancedAll = await AppInheritancedRepository.AllAsync(); + await AppInheritancedRepository.DeleteAsync(appInheritancedAll); + + var app = new App(); + app.Id = "001"; + app.Name = "x"; + app.Enabled = true; + app.CreateTime = DateTime.Now; + app.UpdateTime = DateTime.Now; + app.Type = AppType.PRIVATE; + var app1 = new App(); + app1.Id = "002"; + app1.Name = "x"; + app1.Enabled = true; + app1.CreateTime = DateTime.Now; + app1.UpdateTime = DateTime.Now; + app.Type = AppType.Inheritance; + var id = Guid.NewGuid().ToString(); + var source = new Config + { + AppId = "001", + Id = id, + Key = "k", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var id1 = Guid.NewGuid().ToString(); + var source1 = new Config + { + AppId = "001", + Id = id1, + Key = "k1", + Value = "v1", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var source2 = new Config + { + AppId = "002", + Id = Guid.NewGuid().ToString(), + Key = "k2", + Value = "v", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var source3 = new Config + { + AppId = "002", + Id = Guid.NewGuid().ToString(), + Key = "k21", + Value = "v2", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var appref = new AppInheritanced(); + appref.AppId = app.Id; + appref.InheritancedAppId = app1.Id; + appref.Sort = 1; + appref.Id = Guid.NewGuid().ToString(); + + await AppRepository.InsertAsync(app); + await AppRepository.InsertAsync(app1); + await ConfigRepository.InsertAsync(source); + await ConfigRepository.InsertAsync(source1); + await ConfigRepository.InsertAsync(source2); + await ConfigRepository.InsertAsync(source3); + await AppInheritancedRepository.InsertAsync(appref); + + + var dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); + Assert.IsNotNull(dict); + Assert.AreEqual(4, dict.Keys.Count); + + Assert.IsTrue(dict.ContainsKey(source.Key)); + Assert.IsTrue(dict.ContainsKey(source1.Key)); + Assert.IsTrue(dict.ContainsKey(source2.Key)); + Assert.IsTrue(dict.ContainsKey(source3.Key)); + + Assert.IsTrue(dict[source.Key].Value == "v"); + Assert.IsTrue(dict[source1.Key].Value == "v1"); + Assert.IsTrue(dict[source2.Key].Value == "v"); + Assert.IsTrue(dict[source3.Key].Value == "v2"); + + var source4 = new Config + { + AppId = "001", + Id = Guid.NewGuid().ToString(), + Key = "k4", + Value = "v3", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + var source5 = new Config + { + AppId = "002", + Id = Guid.NewGuid().ToString(), + Key = "k4", + Value = "v2", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + + await ConfigRepository.InsertAsync(source4); + await ConfigRepository.InsertAsync(source5); + + dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); + Assert.IsNotNull(dict); + Assert.AreEqual(5, dict.Keys.Count); + + var config1 = dict["k4"]; + Assert.AreEqual(source4.Value, config1.Value); + + var app2 = new App(); + app2.Id = "003"; + app2.Name = "x"; + app2.Enabled = true; + app2.CreateTime = DateTime.Now; + app2.UpdateTime = DateTime.Now; + app2.Type = AppType.Inheritance; + await AppRepository.InsertAsync(app2); + var source6 = new Config + { + AppId = "003", + Id = Guid.NewGuid().ToString(), + Key = "k2", + Value = "k4444", + Description = "d", + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + Status = ConfigStatus.Enabled, + OnlineStatus = OnlineStatus.Online + }; + + + var appInheritancedAll2 = await AppInheritancedRepository.AllAsync(); + await AppInheritancedRepository.DeleteAsync(appInheritancedAll2); + await ConfigRepository.InsertAsync(source6); + await AppInheritancedRepository.InsertAsync(appref); + + + var appref1 = new AppInheritanced(); + appref1.AppId = app.Id; + appref1.InheritancedAppId = app2.Id; + appref1.Sort = 2; + appref1.Id = Guid.NewGuid().ToString(); + await AppInheritancedRepository.InsertAsync(appref1); + dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); + Assert.IsNotNull(dict); + Assert.AreEqual(5, dict.Keys.Count); + + config1 = dict["k2"]; + Assert.AreEqual(source6.Value, config1.Value); + } +} \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mongodb/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mongodb/SysLogServiceTests.cs new file mode 100644 index 00000000..9872d267 --- /dev/null +++ b/test/AgileConfig.Server.ServiceTests/mongodb/SysLogServiceTests.cs @@ -0,0 +1,217 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.IService; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace AgileConfig.Server.ServiceTests.mongodb; + +[TestClass()] +public class SysLogServiceTests : Basic +{ + ISysLogService service = null; + + [TestInitialize] + public void TestInitialize() + { + service = GetService(); + } + + + [TestCleanup] + public void Clean() + { + } + + [TestMethod()] + public async Task AddSysLogAsyncTest() + { + var source = new SysLog + { + AppId = "001", + LogType = SysLogType.Normal, + LogTime = DateTime.Now, + LogText = "123" + }; + + var result = await service.AddSysLogAsync(source); + Assert.IsTrue(result); + + var log = await SysLogRepository.GetAsync(source.Id); + + Assert.IsNotNull(log); + + Assert.AreEqual(source.Id, log.Id); + Assert.AreEqual(source.AppId, log.AppId); + Assert.AreEqual(source.LogType, log.LogType); + Assert.AreEqual(source.LogTime, log.LogTime); + Assert.AreEqual(source.LogText, log.LogText); + } + + [TestMethod()] + public async Task AddSysLogTransactionAsyncTest() + { + var uowAccessor = GetService>(); + var uow = uowAccessor(""); + + var id = Guid.NewGuid().ToString(); + var source = new SysLog + { + Id = id, + AppId = "001", + LogType = SysLogType.Normal, + LogTime = DateTime.Now, + LogText = "123" + }; + + + try + { + SysLogRepository.Uow = uow; + uow?.Begin(); + await SysLogRepository.InsertAsync(source); + throw new Exception(); + } + catch (Exception e) + { + Console.WriteLine(e); + uow?.Rollback(); + } + finally + { + uow?.Dispose(); + } + + var log = await SysLogRepository.GetAsync(id); + + Assert.IsNull(log); + + + var uowAccessor2 = GetService>(); + var uow2 = uowAccessor2(""); + SysLogRepository.Uow = uow2; + uow2.Begin(); + await SysLogRepository.InsertAsync(source); + await uow2.SaveChangesAsync(); + var log2 = await SysLogRepository.GetAsync(id); + uow2.Dispose(); + + Assert.AreEqual(source.Id, log2.Id); + Assert.AreEqual(source.AppId, log2.AppId); + Assert.AreEqual(source.LogType, log2.LogType); + Assert.AreEqual(source.LogTime?.ToString("yyyy/MM/dd HH:mm:ss"), log2.LogTime?.ToString("yyyy/MM/dd HH:mm:ss")); + Assert.AreEqual(source.LogText, log2.LogText); + } + + + [TestMethod()] + public async Task AddRangeAsyncTest() + { + var source = new SysLog + { + AppId = "001", + LogType = SysLogType.Normal, + LogTime = DateTime.Now, + LogText = "123" + }; + var source1 = new SysLog + { + AppId = "002", + LogType = SysLogType.Warn, + LogTime = DateTime.Now, + LogText = "124" + }; + var result = await service.AddRangeAsync(new List + { + source, source1 + }); + Assert.IsTrue(result); + + var log = await SysLogRepository.GetAsync(source.Id); + Assert.IsNotNull(log); + Assert.AreEqual(source.Id, log.Id); + Assert.AreEqual(source.AppId, log.AppId); + Assert.AreEqual(source.LogType, log.LogType); + Assert.AreEqual(source.LogTime, log.LogTime); + Assert.AreEqual(source.LogText, log.LogText); + + var log1 = await SysLogRepository.GetAsync(source.Id); + Assert.IsNotNull(log1); + Assert.AreEqual(source1.Id, log1.Id); + Assert.AreEqual(source1.AppId, log1.AppId); + Assert.AreEqual(source1.LogType, log1.LogType); + Assert.AreEqual(source1.LogTime, log1.LogTime); + Assert.AreEqual(source1.LogText, log1.LogText); + } + + + [TestMethod()] + public async Task CountTest() + { + var all = await SysLogRepository.AllAsync(); + await SysLogRepository.DeleteAsync(all); + + var source = new SysLog + { + AppId = "001", + LogType = SysLogType.Normal, + LogTime = DateTime.Now, + LogText = "123" + }; + var source1 = new SysLog + { + AppId = "002", + LogType = SysLogType.Warn, + LogTime = DateTime.Now, + LogText = "124" + }; + var result = await service.AddRangeAsync(new List + { + source, source1 + }); + Assert.IsTrue(result); + + var count = await service.Count("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1)); + Assert.AreEqual(1, count); + + var count1 = await service.Count("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1)); + Assert.AreEqual(0, count1); + } + + [TestMethod()] + public async Task SearchPageTest() + { + var all = await SysLogRepository.AllAsync(); + await SysLogRepository.DeleteAsync(all); + + var source = new SysLog + { + AppId = "001", + LogType = SysLogType.Normal, + LogTime = DateTime.Now, + LogText = "123" + }; + var source1 = new SysLog + { + AppId = "002", + LogType = SysLogType.Warn, + LogTime = DateTime.Now, + LogText = "124" + }; + var result = await service.AddRangeAsync(new List + { + source, source1 + }); + Assert.IsTrue(result); + + var page = await service.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1), + 1, 1); + Assert.AreEqual(1, page.Count); + + var page1 = await service.SearchPage("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), + 0, 0); + Assert.AreEqual(0, page1.Count); + } +} \ No newline at end of file From 462654d739803d9430b4ab49c4be547153b145d0 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 7 Jan 2024 22:17:56 +0800 Subject: [PATCH 30/45] Add more unit test cases; Add master-pr-ci.yml; --- .github/workflows/master-ci.yml | 2 +- .github/workflows/master-pr-ci.yml | 40 +++++ AgileConfig.sln | 16 +- .../FreeSqlUow.cs | 2 +- ...Config.Server.Data.AbstractionTests.csproj | 24 +++ .../DbConfig/DbConfigInfoFactoryTests.cs | 47 ++++++ ...gileConfig.Server.Data.FreesqlTests.csproj | 23 +++ .../FreeSQLTests.cs | 49 ++++++ .../FreeSqlUowTests.cs | 141 ++++++++++++++++++ 9 files changed, 341 insertions(+), 3 deletions(-) create mode 100644 .github/workflows/master-pr-ci.yml create mode 100644 test/AgileConfig.Server.Data.AbstractionTests/AgileConfig.Server.Data.AbstractionTests.csproj create mode 100644 test/AgileConfig.Server.Data.AbstractionTests/DbConfig/DbConfigInfoFactoryTests.cs create mode 100644 test/AgileConfig.Server.Data.FreesqlTests/AgileConfig.Server.Data.FreesqlTests.csproj create mode 100644 test/AgileConfig.Server.Data.FreesqlTests/FreeSQLTests.cs create mode 100644 test/AgileConfig.Server.Data.FreesqlTests/FreeSqlUowTests.cs diff --git a/.github/workflows/master-ci.yml b/.github/workflows/master-ci.yml index 0ad47092..12d6d03d 100644 --- a/.github/workflows/master-ci.yml +++ b/.github/workflows/master-ci.yml @@ -7,7 +7,7 @@ on: - '**/*.md' - '**/*.yml' pull_request: - branches: [ master ] + branches: [ ] workflow_dispatch: jobs: diff --git a/.github/workflows/master-pr-ci.yml b/.github/workflows/master-pr-ci.yml new file mode 100644 index 00000000..8b4a295e --- /dev/null +++ b/.github/workflows/master-pr-ci.yml @@ -0,0 +1,40 @@ +name: master pr ci workflow + +on: + pull_request: + branches: [ master ] + workflow_dispatch: + +jobs: + build-reactapp: + runs-on: ubuntu-latest + defaults: + run: + working-directory: src/AgileConfig.Server.UI/react-ui-antd + strategy: + matrix: + node-version: [16.x] + + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + + - run: npm install + - run: npm run build + build-dotnet: + needs: build-reactapp + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Setup .NET Core + uses: actions/setup-dotnet@v1 + with: + dotnet-version: 8.0.* + - name: Install dependencies + run: dotnet restore + - name: Build + run: dotnet build --configuration Release --no-restore diff --git a/AgileConfig.sln b/AgileConfig.sln index cc090078..f3149929 100644 --- a/AgileConfig.sln +++ b/AgileConfig.sln @@ -46,7 +46,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.Data.Rep EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.Data.Repository.Mongodb", "src\AgileConfig.Server.Data.Repository.Mongodb\AgileConfig.Server.Data.Repository.Mongodb.csproj", "{C6B7A5A6-7287-4A20-9336-EBE82A5256F1}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgileConfig.Server.Data.Repository.Selector", "src\AgileConfig.Server.Data.Repository.Selector\AgileConfig.Server.Data.Repository.Selector.csproj", "{15089E5A-12E4-4953-BA35-0CBB2B1189C0}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.Data.Repository.Selector", "src\AgileConfig.Server.Data.Repository.Selector\AgileConfig.Server.Data.Repository.Selector.csproj", "{15089E5A-12E4-4953-BA35-0CBB2B1189C0}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.Data.AbstractionTests", "test\AgileConfig.Server.Data.AbstractionTests\AgileConfig.Server.Data.AbstractionTests.csproj", "{964F5F7A-3BBD-47B3-8C28-EC16B1038A5A}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgileConfig.Server.Data.FreesqlTests", "test\AgileConfig.Server.Data.FreesqlTests\AgileConfig.Server.Data.FreesqlTests.csproj", "{AC7E4D24-D5E8-4E30-BFB0-5DDC581CB0C2}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -118,6 +122,14 @@ Global {15089E5A-12E4-4953-BA35-0CBB2B1189C0}.Debug|Any CPU.Build.0 = Debug|Any CPU {15089E5A-12E4-4953-BA35-0CBB2B1189C0}.Release|Any CPU.ActiveCfg = Release|Any CPU {15089E5A-12E4-4953-BA35-0CBB2B1189C0}.Release|Any CPU.Build.0 = Release|Any CPU + {964F5F7A-3BBD-47B3-8C28-EC16B1038A5A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {964F5F7A-3BBD-47B3-8C28-EC16B1038A5A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {964F5F7A-3BBD-47B3-8C28-EC16B1038A5A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {964F5F7A-3BBD-47B3-8C28-EC16B1038A5A}.Release|Any CPU.Build.0 = Release|Any CPU + {AC7E4D24-D5E8-4E30-BFB0-5DDC581CB0C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AC7E4D24-D5E8-4E30-BFB0-5DDC581CB0C2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AC7E4D24-D5E8-4E30-BFB0-5DDC581CB0C2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AC7E4D24-D5E8-4E30-BFB0-5DDC581CB0C2}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -139,6 +151,8 @@ Global {955F64CC-9EAC-4563-804D-6E2CF9547357} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {C6B7A5A6-7287-4A20-9336-EBE82A5256F1} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} {15089E5A-12E4-4953-BA35-0CBB2B1189C0} = {1D2FD643-CB85-40F9-BC8A-CE4A39E9F43E} + {964F5F7A-3BBD-47B3-8C28-EC16B1038A5A} = {F277EC27-8C0E-4490-9645-F5F3244F9246} + {AC7E4D24-D5E8-4E30-BFB0-5DDC581CB0C2} = {F277EC27-8C0E-4490-9645-F5F3244F9246} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {7F10DB58-5B6F-4EAC-994F-14E8046B306F} diff --git a/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs b/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs index cbe7cbda..76b5e56e 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreeSqlUow.cs @@ -33,7 +33,7 @@ public Task SaveChangesAsync() public void Rollback() { - _unitOfWork.Rollback(); + _unitOfWork?.Rollback(); } public void Dispose() diff --git a/test/AgileConfig.Server.Data.AbstractionTests/AgileConfig.Server.Data.AbstractionTests.csproj b/test/AgileConfig.Server.Data.AbstractionTests/AgileConfig.Server.Data.AbstractionTests.csproj new file mode 100644 index 00000000..b69a2ab9 --- /dev/null +++ b/test/AgileConfig.Server.Data.AbstractionTests/AgileConfig.Server.Data.AbstractionTests.csproj @@ -0,0 +1,24 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + + + + + + + + + diff --git a/test/AgileConfig.Server.Data.AbstractionTests/DbConfig/DbConfigInfoFactoryTests.cs b/test/AgileConfig.Server.Data.AbstractionTests/DbConfig/DbConfigInfoFactoryTests.cs new file mode 100644 index 00000000..ee6806a6 --- /dev/null +++ b/test/AgileConfig.Server.Data.AbstractionTests/DbConfig/DbConfigInfoFactoryTests.cs @@ -0,0 +1,47 @@ +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction.DbProvider; +using Microsoft.Extensions.Configuration; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace AgileConfig.Server.Data.AbstractionTests.DbConfig +{ + [TestClass] + public class DbConfigInfoFactoryTests + { + [TestMethod] + public void TestGetConfigInfo() + { + var configMap = new Dictionary() { + {"db:provider","sqlserver" }, + {"db:conn","localhost" }, + {"db:env:test:provider","sqlite" }, + {"db:env:test:conn","Data Source=agile_config.db" }, + }; + + ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); + configurationBuilder.AddInMemoryCollection(configMap); + var configuration = configurationBuilder.Build(); + Global.Config = configuration; + + var configInfo = DbConfigInfoFactory.GetConfigInfo(); + Assert.IsNotNull(configInfo); + Assert.AreEqual("sqlserver", configInfo.Provider); + Assert.AreEqual("localhost", configInfo.ConnectionString); + + configInfo = DbConfigInfoFactory.GetConfigInfo("test"); + Assert.IsNotNull(configInfo); + Assert.AreEqual("sqlite", configInfo.Provider); + Assert.AreEqual("Data Source=agile_config.db", configInfo.ConnectionString); + + configInfo = DbConfigInfoFactory.GetConfigInfo("x"); + Assert.IsNotNull(configInfo); + Assert.AreEqual("sqlserver", configInfo.Provider); + Assert.AreEqual("localhost", configInfo.ConnectionString); + } + } +} diff --git a/test/AgileConfig.Server.Data.FreesqlTests/AgileConfig.Server.Data.FreesqlTests.csproj b/test/AgileConfig.Server.Data.FreesqlTests/AgileConfig.Server.Data.FreesqlTests.csproj new file mode 100644 index 00000000..186faef1 --- /dev/null +++ b/test/AgileConfig.Server.Data.FreesqlTests/AgileConfig.Server.Data.FreesqlTests.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + + + + + + + + + diff --git a/test/AgileConfig.Server.Data.FreesqlTests/FreeSQLTests.cs b/test/AgileConfig.Server.Data.FreesqlTests/FreeSQLTests.cs new file mode 100644 index 00000000..a871b1fb --- /dev/null +++ b/test/AgileConfig.Server.Data.FreesqlTests/FreeSQLTests.cs @@ -0,0 +1,49 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using AgileConfig.Server.Data.Freesql; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using AgileConfig.Server.Common; + +namespace AgileConfig.Server.Data.Freesql.Tests +{ + [TestClass()] + public class FreeSQLTests + { + [TestMethod()] + public void GetInstanceByEnvTest() + { + var configMap = new Dictionary() { + {"db:provider","sqlite" }, + {"db:conn","Data Source=agile_config.db" }, + {"db:env:test:provider","sqlite" }, + {"db:env:test:conn","Data Source=agile_config1.db" }, + }; + ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); + configurationBuilder.AddInMemoryCollection(configMap); + var configuration = configurationBuilder.Build(); + Global.Config = configuration; + + var fsq = FreeSQL.GetInstanceByEnv(""); + Assert.IsNotNull(fsq); + Assert.AreEqual(FreeSql.DataType.Sqlite, fsq.Ado.DataType); + + var fsqtest = FreeSQL.GetInstanceByEnv("test"); + Assert.IsNotNull(fsqtest); + Assert.AreEqual(FreeSql.DataType.Sqlite, fsqtest.Ado.DataType); + + Assert.AreNotSame(fsq, fsqtest); + var fsqtest_ag = FreeSQL.GetInstanceByEnv("test"); + Assert.AreSame(fsqtest, fsqtest_ag); + + + var fsq_none = FreeSQL.GetInstanceByEnv("x"); + Assert.IsNotNull(fsq_none); + Assert.AreEqual(FreeSql.DataType.Sqlite, fsq_none.Ado.DataType); + Assert.AreSame(fsq, fsq_none); + } + } +} \ No newline at end of file diff --git a/test/AgileConfig.Server.Data.FreesqlTests/FreeSqlUowTests.cs b/test/AgileConfig.Server.Data.FreesqlTests/FreeSqlUowTests.cs new file mode 100644 index 00000000..52d21e41 --- /dev/null +++ b/test/AgileConfig.Server.Data.FreesqlTests/FreeSqlUowTests.cs @@ -0,0 +1,141 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using AgileConfig.Server.Data.Freesql; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Entity; + +namespace AgileConfig.Server.Data.Freesql.Tests +{ + [TestClass()] + public class FreeSqlUowTests + { + [TestInitialize] + public void TestInitialize() + { + var configMap = new Dictionary() { + {"db:provider","sqlite" }, + {"db:conn","Data Source=agile_config.db" }, + {"db:env:test:provider","sqlite" }, + {"db:env:test:conn","Data Source=agile_config1.db" }, + }; + ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); + configurationBuilder.AddInMemoryCollection(configMap); + var configuration = configurationBuilder.Build(); + Global.Config = configuration; + + var fsql = FreeSQL.GetInstanceByEnv(""); + fsql.CodeFirst.SyncStructure(); + fsql.CodeFirst.SyncStructure(); + fsql.Delete(new User_test() { Id = 1 }).ExecuteAffrows(); + fsql.Delete(new Address_test() { Id = 1 }).ExecuteAffrows(); + } + + + [TestMethod()] + public async Task SaveChangesAsyncTest_success() + { + // arrange + var fsql = FreeSQL.GetInstanceByEnv(""); + var user = new User_test() + { + Id = 1, + Name = "abc" + }; + var address = new Address_test() + { + Id = 1, + Address = "Address" + }; + // act + using var uow = new FreeSqlUow(fsql); + + var userrepository = fsql.GetRepository(); + userrepository.UnitOfWork = uow.GetFreesqlUnitOfWork(); + var addressrepository = fsql.GetRepository(); + addressrepository.UnitOfWork = uow.GetFreesqlUnitOfWork(); + + uow.Begin(); + + userrepository.Insert(user); + user.Name = "test1"; + userrepository.Update(user); + addressrepository.Insert(address); + address.Address = "test1"; + addressrepository.Update(address); + + await uow.SaveChangesAsync(); + + // assert + var username = fsql.GetRepository().Where(x => x.Id == 1).ToOne().Name; + var add = fsql.GetRepository().Where(x => x.Id == 1).ToOne().Address; + Assert.AreEqual("test1", username); + Assert.AreEqual("test1", add); + } + + [TestMethod()] + public async Task SaveChangesAsyncTest_rollback() + { + // arrange + var fsql = FreeSQL.GetInstanceByEnv(""); + var user = new User_test() + { + Id = 2, + Name = "abc" + }; + var address = new Address_test() + { + Id = 2, + Address = "Address" + }; + + // act + using var uow = new FreeSqlUow(fsql); + var userrepository = fsql.GetRepository(); + userrepository.UnitOfWork = uow.GetFreesqlUnitOfWork(); + var addressrepository = fsql.GetRepository(); + addressrepository.UnitOfWork = uow.GetFreesqlUnitOfWork(); + + uow.Begin(); + try + { + userrepository.Insert(user); + user.Name = "test1"; + userrepository.Update(user); + throw new Exception("test"); + addressrepository.Insert(address); + address.Address = "test1"; + addressrepository.Update(address); + + await uow.SaveChangesAsync(); + } + catch (Exception exc) + { + Assert.IsNotNull(exc); + } + + + // assert + var _user = fsql.GetRepository().Where(x => x.Id == 2).ToOne(); + var _address = fsql.GetRepository().Where(x => x.Id == 2).ToOne(); + + Assert.IsNull(_user); + Assert.IsNull(_address); + } + } + + public class User_test + { + public int Id { get; set; } + public string Name { get; set; } + } + public class Address_test + { + public int Id { get; set; } + public string Address { get; set; } + } +} \ No newline at end of file From 7bbc27be53d6762a2f16db68e7ac0937f325e56e Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 7 Jan 2024 22:22:39 +0800 Subject: [PATCH 31/45] Update master ci file --- .github/workflows/master-ci.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/workflows/master-ci.yml b/.github/workflows/master-ci.yml index 12d6d03d..b1dfc3c0 100644 --- a/.github/workflows/master-ci.yml +++ b/.github/workflows/master-ci.yml @@ -6,10 +6,6 @@ on: paths-ignore: - '**/*.md' - '**/*.yml' - pull_request: - branches: [ ] - workflow_dispatch: - jobs: build-reactapp: runs-on: ubuntu-latest From 0f9c6a19718c963843996693ef60c9f2577974ae Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Mon, 8 Jan 2024 01:42:27 +0800 Subject: [PATCH 32/45] =?UTF-8?q?=E9=87=8D=E6=9E=84=20SystemInitialization?= =?UTF-8?q?Service=20=E6=8A=8A=E7=8E=AF=E5=A2=83=E5=88=9D=E5=A7=8B?= =?UTF-8?q?=E5=8C=96=E8=B7=9FJwt=20secret=E5=88=9D=E5=A7=8B=E5=8C=96?= =?UTF-8?q?=E6=95=B4=E5=90=88=E5=88=B0=E4=B8=80=E8=B5=B7=EF=BC=9B=20?= =?UTF-8?q?=E9=87=8D=E6=9E=84=20AppService=20=E7=9A=84=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=94=A8=E4=BE=8B;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ConfigureJwtBearerOptions.cs | 4 +- src/AgileConfig.Server.Apisite/InitService.cs | 18 +- src/AgileConfig.Server.Apisite/Startup.cs | 3 - .../ISysInitRepository.cs | 6 + .../FreeSQL.cs | 9 +- .../SysInitRepository.cs | 7 + .../SysInitRepository.cs | 9 + .../ISettingService.cs | 6 - .../ISystemInitializationService.cs | 6 +- .../SettingService.cs | 19 - .../SystemInitializationService.cs | 22 +- .../sqlite/AppServiceTests.cs | 218 +++++++---- .../sqlserver/AppServiceTests.cs | 366 +----------------- 13 files changed, 216 insertions(+), 477 deletions(-) diff --git a/src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs b/src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs index ad25cf0e..4676b6ec 100644 --- a/src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs +++ b/src/AgileConfig.Server.Apisite/ConfigureJwtBearerOptions.cs @@ -7,12 +7,10 @@ namespace AgileConfig.Server.Apisite; public class ConfigureJwtBearerOptions( - IJwtService jwtService, - ISystemInitializationService systemInitializationService) : IConfigureNamedOptions + IJwtService jwtService) : IConfigureNamedOptions { public void Configure(JwtBearerOptions options) { - systemInitializationService.TryInitJwtSecret(); options.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = jwtService.Issuer, diff --git a/src/AgileConfig.Server.Apisite/InitService.cs b/src/AgileConfig.Server.Apisite/InitService.cs index 3e64455e..e37913af 100644 --- a/src/AgileConfig.Server.Apisite/InitService.cs +++ b/src/AgileConfig.Server.Apisite/InitService.cs @@ -5,7 +5,6 @@ using System.Threading.Tasks; using AgileConfig.Server.Apisite.Utilites; using AgileConfig.Server.IService; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -19,10 +18,12 @@ public class InitService : IHostedService private readonly ISettingService _settingService; private readonly IServerNodeService _serverNodeService; private readonly IServiceHealthCheckService _serviceHealthCheckService; + private readonly ISystemInitializationService _systemInitializationService; private readonly ILogger _logger; - public InitService(IServiceScopeFactory serviceScopeFactory, ILogger logger) + public InitService(IServiceScopeFactory serviceScopeFactory, ISystemInitializationService systemInitializationService, ILogger logger) { _logger = logger; + _systemInitializationService = systemInitializationService; using (var scope = serviceScopeFactory.CreateScope()) { _remoteServerNodeProxy = scope.ServiceProvider.GetService(); @@ -34,13 +35,14 @@ public InitService(IServiceScopeFactory serviceScopeFactory, ILogger string? GetJwtTokenSecret(); + /// + /// get default environment from db + /// + /// + Task GetDefaultEnvironmentAsync(); + /// /// save initialization setting /// diff --git a/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs b/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs index 788152e3..224fe9f3 100644 --- a/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs +++ b/src/AgileConfig.Server.Data.Freesql/FreeSQL.cs @@ -41,8 +41,7 @@ public static IFreeSql GetInstanceByEnv(string env) var sql = new FreeSql.FreeSqlBuilder() .UseConnectionString(dbType.Value, dbConfig.ConnectionString) .Build(); - FluentApi.Config(sql); - EnsureTables.Ensure(sql); + ApplyDatabaseStructrue(sql); _envFreesqls.Add(key, sql); @@ -50,6 +49,12 @@ public static IFreeSql GetInstanceByEnv(string env) } } + private static void ApplyDatabaseStructrue(IFreeSql sql) + { + FluentApi.Config(sql); + EnsureTables.Ensure(sql); + } + private static FreeSql.DataType? ProviderToFreesqlDbType(string provider) { switch (provider.ToLower()) diff --git a/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs b/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs index e80789e0..5638f507 100644 --- a/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Freesql/SysInitRepository.cs @@ -14,6 +14,13 @@ public SysInitRepository(IFreeSqlFactory freeSqlFactory) this.freeSqlFactory = freeSqlFactory; } + public async Task GetDefaultEnvironmentAsync() + { + var setting = await freeSqlFactory.Create().Select().Where(x => x.Id == SystemSettings.DefaultEnvironmentKey) + .ToOneAsync(); + return setting?.Value; + } + public string? GetJwtTokenSecret() { var setting = freeSqlFactory.Create().Select().Where(x => x.Id == SystemSettings.DefaultJwtSecretKey) diff --git a/src/AgileConfig.Server.Data.Repository.Mongodb/SysInitRepository.cs b/src/AgileConfig.Server.Data.Repository.Mongodb/SysInitRepository.cs index 05f676f2..867f01ac 100644 --- a/src/AgileConfig.Server.Data.Repository.Mongodb/SysInitRepository.cs +++ b/src/AgileConfig.Server.Data.Repository.Mongodb/SysInitRepository.cs @@ -1,4 +1,5 @@ using AgileConfig.Server.Common; +using MongoDB.Driver; namespace AgileConfig.Server.Data.Repository.Mongodb; @@ -6,6 +7,14 @@ public class SysInitRepository : ISysInitRepository { private readonly MongodbAccess _access = new(Global.Config["db:conn"]); + public Task GetDefaultEnvironmentAsync() + { + var setting = _access.MongoQueryable.FirstOrDefault(x => x.Id == SystemSettings.DefaultEnvironmentKey); + var val = setting?.Value; + + return Task.FromResult(val); + } + public string? GetJwtTokenSecret() { var setting = _access.MongoQueryable.FirstOrDefault(x => x.Id == SystemSettings.DefaultJwtSecretKey); diff --git a/src/AgileConfig.Server.IService/ISettingService.cs b/src/AgileConfig.Server.IService/ISettingService.cs index a0ed09b6..cabc8bee 100644 --- a/src/AgileConfig.Server.IService/ISettingService.cs +++ b/src/AgileConfig.Server.IService/ISettingService.cs @@ -35,12 +35,6 @@ public interface ISettingService: IDisposable /// Task SetSuperAdminPassword(string password); - /// - /// 初始化环境列表 - /// - /// - Task InitDefaultEnvironment(); - /// /// 获取环境列表 /// diff --git a/src/AgileConfig.Server.IService/ISystemInitializationService.cs b/src/AgileConfig.Server.IService/ISystemInitializationService.cs index c76b240a..0016056d 100644 --- a/src/AgileConfig.Server.IService/ISystemInitializationService.cs +++ b/src/AgileConfig.Server.IService/ISystemInitializationService.cs @@ -1,6 +1,10 @@ -namespace AgileConfig.Server.IService; +using System.Threading.Tasks; + +namespace AgileConfig.Server.IService; public interface ISystemInitializationService { bool TryInitJwtSecret(); + + Task TryInitDefaultEnvironmentAsync(); } \ No newline at end of file diff --git a/src/AgileConfig.Server.Service/SettingService.cs b/src/AgileConfig.Server.Service/SettingService.cs index f616aae2..83dcae60 100644 --- a/src/AgileConfig.Server.Service/SettingService.cs +++ b/src/AgileConfig.Server.Service/SettingService.cs @@ -114,25 +114,6 @@ public async Task HasSuperAdmin() return admin != null; } - public async Task InitDefaultEnvironment() - { - var env = await _settingRepository.GetAsync(SystemSettings.DefaultEnvironmentKey); - if (env == null) - { - var setting = new Setting - { - Id = SystemSettings.DefaultEnvironmentKey, - Value = SystemSettings.DefaultEnvironment, - CreateTime = DateTime.Now - }; - await _settingRepository.InsertAsync(setting); - - return true; - } - - return true; - } - public void Dispose() { _settingRepository.Dispose(); diff --git a/src/AgileConfig.Server.Service/SystemInitializationService.cs b/src/AgileConfig.Server.Service/SystemInitializationService.cs index 78c8646a..0c3895dd 100644 --- a/src/AgileConfig.Server.Service/SystemInitializationService.cs +++ b/src/AgileConfig.Server.Service/SystemInitializationService.cs @@ -1,4 +1,5 @@ using System; +using System.Threading.Tasks; using AgileConfig.Server.Common; using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; @@ -44,7 +45,26 @@ public bool TryInitJwtSecret() return true; } - + + public async Task TryInitDefaultEnvironmentAsync() + { + var env = await sysInitRepository.GetDefaultEnvironmentAsync(); + if (env == null) + { + var setting = new Setting + { + Id = SystemSettings.DefaultEnvironmentKey, + Value = SystemSettings.DefaultEnvironment, + CreateTime = DateTime.Now + }; + sysInitRepository.SaveInitSetting(setting); + + return true; + } + + return true; + } + /// /// 生成一个 jwt 加密的 key ,38位 /// diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs index 9b053e55..f26ed8d8 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs @@ -1,5 +1,4 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; using System; using System.Collections.Generic; using System.Text; @@ -8,37 +7,108 @@ using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; using AgileConfig.Server.IService; -using System.Runtime.CompilerServices; - -namespace AgileConfig.Server.Service.Tests +using AgileConfig.Server.Service; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.Common; +using MongoDB.Driver.Linq; + +namespace AgileConfig.Server.ServiceTests.sqlite { [TestClass()] public class AppServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IAppService service = null; + + private ServiceProvider _serviceProvider; + IFreeSql _fsq = null; + IAppService _appservice = null; + + public virtual Dictionary GetConfigurationData() + { + return + new Dictionary + { + {"db:provider","sqlite" }, + {"db:conn","Data Source=agile_config.db" } + }; + } [TestInitialize] public void TestInitialize() { - string conn = "Data Source=agile_config.db"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, conn) - .UseAutoSyncStructure(true) - .Build(); - freeSqlContext = new FreeSqlContext(fsq); - // todo - //service = new AppService(freeSqlContext); - fsq.Delete().Where("1=1"); + var config = new ConfigurationBuilder() + .AddInMemoryCollection(GetConfigurationData()) + .Build(); + Global.Config = config; + + var factory = new EnvFreeSqlFactory(); + _fsq = factory.Create(""); + + var cache = new Mock(); + IServiceCollection services = new ServiceCollection(); + services.AddScoped(_ => cache.Object); + services.AddSingleton(config); + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + services.AddBusinessServices(); + AddEnvRepositiroies(services); + + _serviceProvider = services.BuildServiceProvider(); + var systeminitializationService = _serviceProvider.GetService(); + systeminitializationService.TryInitDefaultEnvironmentAsync();//初始化环境 DEV TEST STAGE PROD + systeminitializationService.TryInitJwtSecret();//初始化 jwt secret + + _appservice = _serviceProvider.GetService(); + + _fsq.Delete().Where("1=1"); Console.WriteLine("TestInitialize"); } + + private static void AddEnvRepositiroies(IServiceCollection sc) + { + sc.AddScoped>(sp => env => + { + var factory = sp.GetService(); + var fsq = factory.Create(env); + return new FreeSqlUow(fsq); + }); + + sc.AddScoped>(sp => env => + { + var factory = sp.GetService(); + return new ConfigPublishedRepository(factory.Create(env)); + }); + + sc.AddScoped>(sp => env => + { + var factory = sp.GetService(); + + return new ConfigRepository(factory.Create(env)); + }); + + sc.AddScoped>(sp => env => + { + var factory = sp.GetService(); + return new PublishDetailRepository(factory.Create(env)); + }); + + sc.AddScoped>(sp => env => + { + var factory = sp.GetService(); + return new PublishTimelineRepository(factory.Create(env)); + }); + } + [TestMethod()] public async Task AddAsyncTest() { var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App + var source = new App { Id = id, Name = "xx", @@ -47,8 +117,8 @@ public async Task AddAsyncTest() UpdateTime = DateTime.Now, Enabled = true }; - var result = await service.AddAsync(source); - var app = fsq.Select(new + var result = await _appservice.AddAsync(source); + var app = _fsq.Select(new { Id = id }).ToOne(); @@ -59,8 +129,8 @@ public async Task AddAsyncTest() Assert.AreEqual(source.Id, app.Id); Assert.AreEqual(source.Name, app.Name); Assert.AreEqual(source.Secret, app.Secret); - Assert.AreEqual(source.CreateTime, app.CreateTime); - Assert.AreEqual(source.UpdateTime, app.UpdateTime); + Assert.AreEqual(source.CreateTime.ToString("yyyyMMddhhmmss"), app.CreateTime.ToString("yyyyMMddhhmmss")); + Assert.AreEqual(source.UpdateTime.Value.ToString("yyyyMMddhhmmss"), app.UpdateTime.Value.ToString("yyyyMMddhhmmss")); Assert.AreEqual(source.Enabled, app.Enabled); } @@ -68,7 +138,7 @@ public async Task AddAsyncTest() public async Task DeleteAsyncTest() { var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App + var source = new App { Id = id, Name = "xx", @@ -77,13 +147,13 @@ public async Task DeleteAsyncTest() UpdateTime = DateTime.Now, Enabled = true }; - var result = await service.AddAsync(source); + var result = await _appservice.AddAsync(source); Assert.IsTrue(result); - var delResult = await service.DeleteAsync(source); + var delResult = await _appservice.DeleteAsync(source); Assert.IsTrue(delResult); - var app = fsq.Select(new + var app = _fsq.Select(new { Id = id }).ToOne(); @@ -95,7 +165,7 @@ public async Task DeleteAsyncTest() public async Task DeleteAsyncTest1() { var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App + var source = new App { Id = id, Name = "xx", @@ -104,13 +174,13 @@ public async Task DeleteAsyncTest1() UpdateTime = DateTime.Now, Enabled = true }; - var result = await service.AddAsync(source); + var result = await _appservice.AddAsync(source); Assert.IsTrue(result); - var delResult = await service.DeleteAsync(id); + var delResult = await _appservice.DeleteAsync(id); Assert.IsTrue(delResult); - var app = fsq.Select(new + var app = _fsq.Select(new { Id = id }).ToOne(); @@ -122,7 +192,7 @@ public async Task DeleteAsyncTest1() public async Task GetAsyncTest() { var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App + var source = new App { Id = id, Name = "xx", @@ -131,26 +201,26 @@ public async Task GetAsyncTest() UpdateTime = DateTime.Now, Enabled = true }; - var result = await service.AddAsync(source); + var result = await _appservice.AddAsync(source); Assert.IsTrue(result); - var app = await service.GetAsync(id); + var app = await _appservice.GetAsync(id); Assert.IsNotNull(app); Assert.AreEqual(source.Id, app.Id); Assert.AreEqual(source.Name, app.Name); Assert.AreEqual(source.Secret, app.Secret); - Assert.AreEqual(source.CreateTime, app.CreateTime); - Assert.AreEqual(source.UpdateTime, app.UpdateTime); + Assert.AreEqual(source.CreateTime.ToString("yyyyMMddhhmmss"), app.CreateTime.ToString("yyyyMMddhhmmss")); + Assert.AreEqual(source.UpdateTime.Value.ToString("yyyyMMddhhmmss"), app.UpdateTime.Value.ToString("yyyyMMddhhmmss")); Assert.AreEqual(source.Enabled, app.Enabled); } [TestMethod()] public async Task GetAllAppsAsyncTest() { - fsq.Delete().Where("1=1").ExecuteAffrows() ; + _fsq.Delete().Where("1=1").ExecuteAffrows(); var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App + var source = new App { Id = id, Name = "xx", @@ -159,10 +229,10 @@ public async Task GetAllAppsAsyncTest() UpdateTime = DateTime.Now, Enabled = true }; - var result = await service.AddAsync(source); + var result = await _appservice.AddAsync(source); Assert.IsTrue(result); var id1 = Guid.NewGuid().ToString(); - var source1 = new Data.Entity.App + var source1 = new App { Id = id1, Name = "xx", @@ -171,10 +241,10 @@ public async Task GetAllAppsAsyncTest() UpdateTime = DateTime.Now, Enabled = true }; - var result1 = await service.AddAsync(source1); + var result1 = await _appservice.AddAsync(source1); Assert.IsTrue(result1); - var apps = await service.GetAllAppsAsync(); + var apps = await _appservice.GetAllAppsAsync(); Assert.IsNotNull(apps); Assert.AreEqual(2, apps.Count); @@ -185,7 +255,7 @@ public async Task GetAllAppsAsyncTest() public async Task UpdateAsyncTest() { var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App + var source = new App { Id = id, Name = "xx", @@ -194,7 +264,7 @@ public async Task UpdateAsyncTest() UpdateTime = DateTime.Now, Enabled = true }; - var result = await service.AddAsync(source); + var result = await _appservice.AddAsync(source); Assert.IsTrue(result); source.Name = "new name"; @@ -203,10 +273,10 @@ public async Task UpdateAsyncTest() source.UpdateTime = DateTime.Now.AddDays(1); source.Enabled = false; - var result1 = await service.UpdateAsync(source); + var result1 = await _appservice.UpdateAsync(source); Assert.IsTrue(result1); - var app = fsq.Select(new + var app = _fsq.Select(new { Id = id }).ToOne(); @@ -214,17 +284,17 @@ public async Task UpdateAsyncTest() Assert.AreEqual(source.Id, app.Id); Assert.AreEqual(source.Name, app.Name); Assert.AreEqual(source.Secret, app.Secret); - Assert.AreEqual(source.CreateTime, app.CreateTime); - Assert.AreEqual(source.UpdateTime, app.UpdateTime); + Assert.AreEqual(source.CreateTime.ToString("yyyyMMddhhmmss"), app.CreateTime.ToString("yyyyMMddhhmmss")); + Assert.AreEqual(source.UpdateTime.Value.ToString("yyyyMMddhhmmss"), app.UpdateTime.Value.ToString("yyyyMMddhhmmss")); Assert.AreEqual(source.Enabled, app.Enabled); } [TestMethod()] public async Task CountEnabledAppsAsyncTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App + var source = new App { Id = id, Name = "xx", @@ -233,10 +303,10 @@ public async Task CountEnabledAppsAsyncTest() UpdateTime = DateTime.Now, Enabled = true }; - var result = await service.AddAsync(source); + var result = await _appservice.AddAsync(source); Assert.IsTrue(result); var id1 = Guid.NewGuid().ToString(); - var source1 = new Data.Entity.App + var source1 = new App { Id = id1, Name = "xx", @@ -245,19 +315,19 @@ public async Task CountEnabledAppsAsyncTest() UpdateTime = DateTime.Now, Enabled = false }; - var result1 = await service.AddAsync(source1); + var result1 = await _appservice.AddAsync(source1); Assert.IsTrue(result1); - var count = await service.CountEnabledAppsAsync(); + var count = await _appservice.CountEnabledAppsAsync(); Assert.AreEqual(1, count); } [TestMethod()] public async Task GetAllInheritancedAppsAsyncTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App + var source = new App { Id = id, Name = "xx", @@ -267,7 +337,7 @@ public async Task GetAllInheritancedAppsAsyncTest() Enabled = true, Type = AppType.PRIVATE }; - var source1 = new Data.Entity.App + var source1 = new App { Id = Guid.NewGuid().ToString(), Name = "xxx", @@ -277,7 +347,7 @@ public async Task GetAllInheritancedAppsAsyncTest() Enabled = true, Type = AppType.PRIVATE }; - var source2 = new Data.Entity.App + var source2 = new App { Id = Guid.NewGuid().ToString(), Name = "xxxx", @@ -287,7 +357,7 @@ public async Task GetAllInheritancedAppsAsyncTest() Enabled = true, Type = AppType.Inheritance }; - var source3 = new Data.Entity.App + var source3 = new App { Id = Guid.NewGuid().ToString(), Name = "xxxx", @@ -297,25 +367,25 @@ public async Task GetAllInheritancedAppsAsyncTest() Enabled = false, Type = AppType.Inheritance }; - var result = await service.AddAsync(source); - await service.AddAsync(source1); - await service.AddAsync(source2); - await service.AddAsync(source3); + var result = await _appservice.AddAsync(source); + await _appservice.AddAsync(source1); + await _appservice.AddAsync(source2); + await _appservice.AddAsync(source3); Assert.IsTrue(result); - var apps = await service.GetAllInheritancedAppsAsync(); + var apps = await _appservice.GetAllInheritancedAppsAsync(); Assert.AreEqual(2, apps.Count); } [TestMethod()] public async Task GetInheritancedAppsAsyncTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App + var source = new App { Id = id, Name = "xx", @@ -325,7 +395,7 @@ public async Task GetInheritancedAppsAsyncTest() Enabled = true, Type = AppType.PRIVATE }; - var source1 = new Data.Entity.App + var source1 = new App { Id = Guid.NewGuid().ToString(), Name = "xx1", @@ -335,7 +405,7 @@ public async Task GetInheritancedAppsAsyncTest() Enabled = true, Type = AppType.Inheritance }; - var source2 = new Data.Entity.App + var source2 = new App { Id = Guid.NewGuid().ToString(), Name = "xx2", @@ -357,15 +427,15 @@ public async Task GetInheritancedAppsAsyncTest() appInher1.InheritancedAppId = source2.Id; appInher1.Sort = 2; - var result = await service.AddAsync(source); - await service.AddAsync(source1); - await service.AddAsync(source2); - fsq.Insert(appInher).ExecuteAffrows(); - fsq.Insert(appInher1).ExecuteAffrows(); + var result = await _appservice.AddAsync(source); + await _appservice.AddAsync(source1); + await _appservice.AddAsync(source2); + _fsq.Insert(appInher).ExecuteAffrows(); + _fsq.Insert(appInher1).ExecuteAffrows(); Assert.IsTrue(result); - var apps = await service.GetInheritancedAppsAsync(source.Id); + var apps = await _appservice.GetInheritancedAppsAsync(source.Id); Assert.AreEqual(2, apps.Count); } @@ -373,8 +443,6 @@ public async Task GetInheritancedAppsAsyncTest() [TestCleanup] public void Clean() { - freeSqlContext.Dispose(); - fsq.Dispose(); } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs index 57683985..fffc3332 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs @@ -9,372 +9,22 @@ using System.Threading.Tasks; using AgileConfig.Server.IService; using System.Runtime.CompilerServices; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.Service.Tests.sqlserver { [TestClass()] - public class AppServiceTests + public class AppServiceTests_sqlserver: AppServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IAppService service = null; + string conn = "TrustServerCertificate=True;Persist Security Info = False; User ID =dev; Password =dev; Initial Catalog =agile_config_test; Server =."; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Persist Security Info = False; User ID =dev; Password =dev@123,; Initial Catalog =agile_config_test; Server =www..com"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.SqlServer, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); - // todo - //service = new AppService(freeSqlContext); - fsq.Delete().Where("1=1"); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "sqlserver"; + dict["db:conn"] = conn; - Console.WriteLine("TestInitialize"); - } - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - var app = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsTrue(result); - Assert.IsNotNull(app); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - // Assert.AreEqual(source.CreateTime, app.CreateTime); - // Assert.AreEqual(source.UpdateTime, app.UpdateTime); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var delResult = await service.DeleteAsync(source); - Assert.IsTrue(delResult); - - var app = fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNull(app); - - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var delResult = await service.DeleteAsync(id); - Assert.IsTrue(delResult); - - var app = fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNull(app); - - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var app = await service.GetAsync(id); - Assert.IsNotNull(app); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - // Assert.AreEqual(source.CreateTime, app.CreateTime); - // Assert.AreEqual(source.UpdateTime, app.UpdateTime); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [TestMethod()] - public async Task GetAllAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows() ; - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Data.Entity.App - { - Id = id1, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var apps = await service.GetAllAppsAsync(); - Assert.IsNotNull(apps); - Assert.AreEqual(2, apps.Count); - - - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.Name = "new name"; - source.Secret = "new sec"; - source.CreateTime = DateTime.Now.AddDays(1); - source.UpdateTime = DateTime.Now.AddDays(1); - source.Enabled = false; - - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result1); - - var app = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - // Assert.AreEqual(source.CreateTime, app.CreateTime); - // Assert.AreEqual(source.UpdateTime, app.UpdateTime); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [TestMethod()] - public async Task CountEnabledAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Data.Entity.App - { - Id = id1, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = false - }; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var count = await service.CountEnabledAppsAsync(); - Assert.AreEqual(1, count); - } - - [TestMethod()] - public async Task GetAllInheritancedAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source1 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source2 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - var source3 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = false, - Type = AppType.Inheritance - }; - var result = await service.AddAsync(source); - await service.AddAsync(source1); - await service.AddAsync(source2); - await service.AddAsync(source3); - - Assert.IsTrue(result); - - var apps = await service.GetAllInheritancedAppsAsync(); - - Assert.AreEqual(2, apps.Count); - } - [TestMethod()] - public async Task GetInheritancedAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source1 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xx1", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - var source2 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xx2", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - // - var appInher = new AppInheritanced(); - appInher.Id = Guid.NewGuid().ToString(); - appInher.AppId = source.Id; - appInher.InheritancedAppId = source1.Id; - appInher.Sort = 1; - var appInher1 = new AppInheritanced(); - appInher1.Id = Guid.NewGuid().ToString(); - appInher1.AppId = source.Id; - appInher1.InheritancedAppId = source2.Id; - appInher1.Sort = 2; - - var result = await service.AddAsync(source); - await service.AddAsync(source1); - await service.AddAsync(source2); - fsq.Insert(appInher).ExecuteAffrows(); - fsq.Insert(appInher1).ExecuteAffrows(); - - Assert.IsTrue(result); - - var apps = await service.GetInheritancedAppsAsync(source.Id); - - Assert.AreEqual(2, apps.Count); - } - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); + return dict; } } } \ No newline at end of file From eb9a34d3f4fe4cc387be22f07614355bd25c18b2 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sat, 13 Jan 2024 21:04:41 +0800 Subject: [PATCH 33/45] When standalone cluster run action without transaction. --- .../appsettings.Development.json | 8 ++++---- .../MongodbUow.cs | 19 ++++++++++++++++--- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/AgileConfig.Server.Apisite/appsettings.Development.json b/src/AgileConfig.Server.Apisite/appsettings.Development.json index 7a6779ab..22ade014 100644 --- a/src/AgileConfig.Server.Apisite/appsettings.Development.json +++ b/src/AgileConfig.Server.Apisite/appsettings.Development.json @@ -16,8 +16,8 @@ "cluster": false, // 集群模式:服务启动后自动加入节点列表,服务启动的时候会获取容器的ip,端口默认5000,适合 docker compose 环境使用 "preview_mode": false, "db": { - "provider": "sqlite", //sqlite,mysql,sqlserver,npgsql,oracle,mongodb - "conn": "Data Source=agile_config.db", + //"provider": "sqlite", //sqlite,mysql,sqlserver,npgsql,oracle,mongodb + //"conn": "Data Source=agile_config.db", //"provider": "sqlserver", //"conn": "Encrypt=True;TrustServerCertificate=True;Persist Security Info = False; User ID =dev; Password =dev@123; Initial Catalog =agile_config; Server =192.168.18.82" //"provider": "npgsql", @@ -26,8 +26,8 @@ //"conn": "user id=CLINIC;password=CLINIC;data source=192.168.0.91/orcl" //"provider": "mysql", //"conn": "Database=agile_config;Data Source=192.168.0.125;User Id=root;Password=x;port=13306;Allow User Variables=true;", - //"provider": "mongodb", - //"conn": "mongodb://localhost:27017,localhost:37017/AgileConfig", + "provider": "mongodb", + "conn": "mongodb://192.168.0.125:27017/agile_config_1", "env": { "TEST": { "provider": "sqlite", //sqlite,mysql,sqlserver,npgsql,oracle diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbUow.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbUow.cs index e4f65827..d5276232 100644 --- a/src/AgileConfig.Server.Data.Mongodb/MongodbUow.cs +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbUow.cs @@ -11,7 +11,13 @@ public class MongodbUow : Abstraction.IUow public async Task SaveChangesAsync() { - await Session?.CommitTransactionAsync()!; + if (Session == null) + { + } + else + { + await Session.CommitTransactionAsync(); + } return true; } @@ -47,10 +53,17 @@ public void Begin() Session?.StartTransaction(); } } - + internal void SetSession(IClientSessionHandle session) { - Session = session; + if (session.Client.Cluster.Description.Type == MongoDB.Driver.Core.Clusters.ClusterType.Standalone) + { + // standalone mode is not support transaction. + } + else + { + Session = session; + } } } } \ No newline at end of file From 51805e2bee196dee2d33e1ca7855246ee7dd252d Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sat, 13 Jan 2024 22:35:17 +0800 Subject: [PATCH 34/45] Update AppServiceTests for mysql --- .../mysql/AppServiceTests.cs | 374 +----------------- 1 file changed, 9 insertions(+), 365 deletions(-) diff --git a/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs index ad473766..1360ff25 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs @@ -1,378 +1,22 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; +using AgileConfig.Server.ServiceTests.sqlite; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.IService; -using System.Runtime.CompilerServices; namespace AgileConfig.Server.Service.Tests.mysql { [TestClass()] - public class AppServiceTests + public class AppServiceTests_mysql: AppServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IAppService service = null; + string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=123456;port=13306"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Database=agile_config_test;Data Source=localhost;User Id=root;Password=dev@123;port=3306"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.MySql, conn) - .UseAutoSyncStructure(true) - .Build(); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "mysql"; + dict["db:conn"] = conn; - // todo - - //service = new AppService(freeSqlContext); - fsq.Delete().Where("1=1"); - } - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - var app = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsTrue(result); - Assert.IsNotNull(app); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - //Assert.AreEqual(source.CreateTime, app.CreateTime); - // Assert.AreEqual(source.UpdateTime, app.UpdateTime); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var delResult = await service.DeleteAsync(source); - Assert.IsTrue(delResult); - - var app = fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNull(app); - - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var delResult = await service.DeleteAsync(id); - Assert.IsTrue(delResult); - - var app = fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNull(app); - - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var app = await service.GetAsync(id); - Assert.IsNotNull(app); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - // Assert.AreEqual(source.CreateTime, app.CreateTime); - // Assert.AreEqual(source.UpdateTime, app.UpdateTime); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [TestMethod()] - public async Task GetAllAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows() ; - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Data.Entity.App - { - Id = id1, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var apps = await service.GetAllAppsAsync(); - Assert.IsNotNull(apps); - Assert.AreEqual(2, apps.Count); - - - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.Name = "new name"; - source.Secret = "new sec"; - source.CreateTime = DateTime.Now.AddDays(1); - source.UpdateTime = DateTime.Now.AddDays(1); - source.Enabled = false; - - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result1); - - var app = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - // Assert.AreEqual(source.CreateTime, app.CreateTime); - // Assert.AreEqual(source.UpdateTime, app.UpdateTime); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [TestMethod()] - public async Task CountEnabledAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Data.Entity.App - { - Id = id1, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = false - }; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var count = await service.CountEnabledAppsAsync(); - Assert.AreEqual(1, count); - } - [TestMethod()] - public async Task GetAllInheritancedAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source1 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source2 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - var source3 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = false, - Type = AppType.Inheritance - }; - var result = await service.AddAsync(source); - await service.AddAsync(source1); - await service.AddAsync(source2); - await service.AddAsync(source3); - - Assert.IsTrue(result); - - var apps = await service.GetAllInheritancedAppsAsync(); - - Assert.AreEqual(2, apps.Count); - } - [TestMethod()] - public async Task GetInheritancedAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source1 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xx1", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - var source2 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xx2", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - // - var appInher = new AppInheritanced(); - appInher.Id = Guid.NewGuid().ToString(); - appInher.AppId = source.Id; - appInher.InheritancedAppId = source1.Id; - appInher.Sort = 1; - var appInher1 = new AppInheritanced(); - appInher1.Id = Guid.NewGuid().ToString(); - appInher1.AppId = source.Id; - appInher1.InheritancedAppId = source2.Id; - appInher1.Sort = 2; - - var result = await service.AddAsync(source); - await service.AddAsync(source1); - await service.AddAsync(source2); - fsq.Insert(appInher).ExecuteAffrows(); - fsq.Insert(appInher1).ExecuteAffrows(); - - Assert.IsTrue(result); - - var apps = await service.GetInheritancedAppsAsync(source.Id); - - Assert.AreEqual(2, apps.Count); - } - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); + return dict; } + } } \ No newline at end of file From 0643debc4a71e7fe5e31c1e81915877e1421cfb3 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Mon, 15 Jan 2024 00:38:04 +0800 Subject: [PATCH 35/45] Update AppServiceTests for pg --- .../PostgreSQL/AppServiceTests.cs | 373 +----------------- 1 file changed, 8 insertions(+), 365 deletions(-) diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/AppServiceTests.cs index 1e6582bb..71921c27 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/AppServiceTests.cs @@ -1,379 +1,22 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.IService; -using System.Runtime.CompilerServices; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.Service.Tests.PostgreSQL { [TestClass()] - public class AppServiceTests + public class AppServiceTests_pg : AppServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IAppService service = null; + string conn = "Host=192.168.0.125;Port=15432;Database=agileconfig;Username=postgres;Password=123456"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Host=127.0.0.1;Database=agile_config;Username=postgres;Password=dev@123"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.PostgreSQL, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); - // todo - //service = new AppService(freeSqlContext); - fsq.Delete().Where("1=1"); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "npgsql"; + dict["db:conn"] = conn; - Console.WriteLine("TestInitialize"); + return dict; } - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - var app = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsTrue(result); - Assert.IsNotNull(app); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - // Assert.AreEqual(source.CreateTime, app.CreateTime); - // Assert.AreEqual(source.UpdateTime, app.UpdateTime); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var delResult = await service.DeleteAsync(source); - Assert.IsTrue(delResult); - - var app = fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNull(app); - - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var delResult = await service.DeleteAsync(id); - Assert.IsTrue(delResult); - var app = fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNull(app); - - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var app = await service.GetAsync(id); - Assert.IsNotNull(app); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - // Assert.AreEqual(source.CreateTime, app.CreateTime); - // Assert.AreEqual(source.UpdateTime, app.UpdateTime); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [TestMethod()] - public async Task GetAllAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows() ; - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Data.Entity.App - { - Id = id1, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var apps = await service.GetAllAppsAsync(); - Assert.IsNotNull(apps); - Assert.AreEqual(2, apps.Count); - - - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.Name = "new name"; - source.Secret = "new sec"; - source.CreateTime = DateTime.Now.AddDays(1); - source.UpdateTime = DateTime.Now.AddDays(1); - source.Enabled = false; - - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result1); - - var app = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - // Assert.AreEqual(source.CreateTime, app.CreateTime); - // Assert.AreEqual(source.UpdateTime, app.UpdateTime); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [TestMethod()] - public async Task CountEnabledAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Data.Entity.App - { - Id = id1, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = false - }; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var count = await service.CountEnabledAppsAsync(); - Assert.AreEqual(1, count); - } - [TestMethod()] - public async Task GetAllInheritancedAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source1 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source2 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - var source3 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = false, - Type = AppType.Inheritance - }; - var result = await service.AddAsync(source); - await service.AddAsync(source1); - await service.AddAsync(source2); - await service.AddAsync(source3); - - Assert.IsTrue(result); - - var apps = await service.GetAllInheritancedAppsAsync(); - - Assert.AreEqual(2, apps.Count); - } - [TestMethod()] - public async Task GetInheritancedAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source1 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xx1", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - var source2 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xx2", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - // - var appInher = new AppInheritanced(); - appInher.Id = Guid.NewGuid().ToString(); - appInher.AppId = source.Id; - appInher.InheritancedAppId = source1.Id; - appInher.Sort = 1; - var appInher1 = new AppInheritanced(); - appInher1.Id = Guid.NewGuid().ToString(); - appInher1.AppId = source.Id; - appInher1.InheritancedAppId = source2.Id; - appInher1.Sort = 2; - - var result = await service.AddAsync(source); - await service.AddAsync(source1); - await service.AddAsync(source2); - fsq.Insert(appInher).ExecuteAffrows(); - fsq.Insert(appInher1).ExecuteAffrows(); - - Assert.IsTrue(result); - - var apps = await service.GetInheritancedAppsAsync(source.Id); - - Assert.AreEqual(2, apps.Count); - } - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } } } \ No newline at end of file From 7932587c866d5bf0732fc1125310cfbf2f5f5048 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Mon, 15 Jan 2024 00:41:38 +0800 Subject: [PATCH 36/45] update AppServiceTests for oracle --- .../appsettings.Development.json | 2 +- .../oracle/AppServiceTests.cs | 373 +----------------- 2 files changed, 9 insertions(+), 366 deletions(-) diff --git a/src/AgileConfig.Server.Apisite/appsettings.Development.json b/src/AgileConfig.Server.Apisite/appsettings.Development.json index 22ade014..6271b2e5 100644 --- a/src/AgileConfig.Server.Apisite/appsettings.Development.json +++ b/src/AgileConfig.Server.Apisite/appsettings.Development.json @@ -23,7 +23,7 @@ //"provider": "npgsql", //"conn": "Host=127.0.0.1;Database=agileconfig;Username=postgres;Password=123456" //"provider": "oracle", - //"conn": "user id=CLINIC;password=CLINIC;data source=192.168.0.91/orcl" + //"conn": "user id=x;password=x;data source=192.168.0.123/orcl" //"provider": "mysql", //"conn": "Database=agile_config;Data Source=192.168.0.125;User Id=root;Password=x;port=13306;Allow User Variables=true;", "provider": "mongodb", diff --git a/test/AgileConfig.Server.ServiceTests/oracle/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/AppServiceTests.cs index 3f0a932b..9841894e 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/AppServiceTests.cs @@ -2,380 +2,23 @@ using AgileConfig.Server.Service; using System; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.IService; -using System.Runtime.CompilerServices; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.Service.Tests.oracle { [TestClass()] - public class AppServiceTests + public class AppServiceTests_oracle : AppServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IAppService service = null; + string conn = "user id=x;password=x;data source=192.168.0.123/orcl"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "user id=CLINIC;password=CLINIC;data source=192.168.0.91/orcl"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Oracle, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); - - // todo - - //service = new AppService(freeSqlContext); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - var app = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsTrue(result); - Assert.IsNotNull(app); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - // Assert.AreEqual(source.CreateTime, app.CreateTime); - // Assert.AreEqual(source.UpdateTime, app.UpdateTime); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var delResult = await service.DeleteAsync(source); - Assert.IsTrue(delResult); - - var app = fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNull(app); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "oracle"; + dict["db:conn"] = conn; + return dict; } - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var delResult = await service.DeleteAsync(id); - Assert.IsTrue(delResult); - - var app = fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNull(app); - - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var app = await service.GetAsync(id); - Assert.IsNotNull(app); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - // Assert.AreEqual(source.CreateTime, app.CreateTime); - // Assert.AreEqual(source.UpdateTime, app.UpdateTime); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [TestMethod()] - public async Task GetAllAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows() ; - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Data.Entity.App - { - Id = id1, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var apps = await service.GetAllAppsAsync(); - Assert.IsNotNull(apps); - Assert.AreEqual(2, apps.Count); - - - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.Name = "new name"; - source.Secret = "new sec"; - source.CreateTime = DateTime.Now.AddDays(1); - source.UpdateTime = DateTime.Now.AddDays(1); - source.Enabled = false; - - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result1); - - var app = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.AreEqual(source.Id, app.Id); - Assert.AreEqual(source.Name, app.Name); - Assert.AreEqual(source.Secret, app.Secret); - // Assert.AreEqual(source.CreateTime, app.CreateTime); - // Assert.AreEqual(source.UpdateTime, app.UpdateTime); - Assert.AreEqual(source.Enabled, app.Enabled); - } - - [TestMethod()] - public async Task CountEnabledAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true - }; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Data.Entity.App - { - Id = id1, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = false - }; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var count = await service.CountEnabledAppsAsync(); - Assert.AreEqual(1, count); - } - [TestMethod()] - public async Task GetAllInheritancedAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source1 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source2 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - var source3 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xxxx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = false, - Type = AppType.Inheritance - }; - var result = await service.AddAsync(source); - await service.AddAsync(source1); - await service.AddAsync(source2); - await service.AddAsync(source3); - - Assert.IsTrue(result); - - var apps = await service.GetAllInheritancedAppsAsync(); - - Assert.AreEqual(2, apps.Count); - } - [TestMethod()] - public async Task GetInheritancedAppsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Data.Entity.App - { - Id = id, - Name = "xx", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.PRIVATE - }; - var source1 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xx1", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - var source2 = new Data.Entity.App - { - Id = Guid.NewGuid().ToString(), - Name = "xx2", - Secret = "sec", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Enabled = true, - Type = AppType.Inheritance - }; - // - var appInher = new AppInheritanced(); - appInher.Id = Guid.NewGuid().ToString(); - appInher.AppId = source.Id; - appInher.InheritancedAppId = source1.Id; - appInher.Sort = 1; - var appInher1 = new AppInheritanced(); - appInher1.Id = Guid.NewGuid().ToString(); - appInher1.AppId = source.Id; - appInher1.InheritancedAppId = source2.Id; - appInher1.Sort = 2; - - var result = await service.AddAsync(source); - await service.AddAsync(source1); - await service.AddAsync(source2); - fsq.Insert(appInher).ExecuteAffrows(); - fsq.Insert(appInher1).ExecuteAffrows(); - - Assert.IsTrue(result); - - var apps = await service.GetInheritancedAppsAsync(source.Id); - - Assert.AreEqual(2, apps.Count); - } - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } } } \ No newline at end of file From f72f3ca960f898bba1540e9d0513120ccb4bcf3c Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Mon, 15 Jan 2024 01:50:09 +0800 Subject: [PATCH 37/45] Update testcases; --- .../PostgreSQL/ServerNodeServiceTests.cs | 194 +-------------- .../PostgreSQL/SettingServiceTests.cs | 225 +---------------- .../PostgreSQL/SysLogServiceTests.cs | 188 +-------------- .../mysql/AppServiceTests.cs | 8 +- .../mysql/ServerNodeServiceTests.cs | 204 +--------------- .../mysql/SettingServiceTests.cs | 227 +----------------- .../mysql/SysLogServiceTests.cs | 188 +-------------- .../oracle/ServerNodeServiceTests.cs | 203 +--------------- .../oracle/SettingServiceTests.cs | 225 +---------------- .../oracle/SysLogServiceTests.cs | 186 +------------- .../sqlite/AppServiceTests.cs | 71 +----- .../sqlite/BasicTestService.cs | 94 ++++++++ .../sqlite/ServerNodeServiceTests.cs | 107 ++++----- .../sqlite/SettingServiceTests.cs | 127 +++------- .../sqlite/SysLogServiceTests.cs | 91 +++---- .../sqlserver/AppServiceTests.cs | 9 - .../sqlserver/ServerNodeServiceTests.cs | 203 +--------------- .../sqlserver/SettingServiceTests.cs | 225 +---------------- .../sqlserver/SysLogServiceTests.cs | 186 +------------- 19 files changed, 314 insertions(+), 2647 deletions(-) create mode 100644 test/AgileConfig.Server.ServiceTests/sqlite/BasicTestService.cs diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs index 2afdf5e1..5b812c98 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs @@ -10,200 +10,22 @@ using AgileConfig.Server.Data.Repository.Freesql; using AgileConfig.Server.IService; using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.Service.Tests.PostgreSQL { [TestClass()] - public class ServerNodeServiceTests + public class ServerNodeServiceTests_pg: ServerNodeServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IServerNodeService service = null; + string conn = "Host=192.168.0.125;Port=15432;Database=agileconfig;Username=postgres;Password=123456"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Host=127.0.0.1;Database=agile_config;Username=postgres;Password=dev@123"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.PostgreSQL, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "npgsql"; + dict["db:conn"] = conn; - IServiceCollection services = new ServiceCollection(); - services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - - [TestMethod()] - public async Task AddAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var node = fsq.Select(new { - Address = "1" - }).ToOne(); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source); - Assert.IsTrue(result1); - - var node = fsq.Select(new - { - Address = "1" - }).ToOne(); - Assert.IsNull(node); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source.Id); - Assert.IsTrue(result1); - - var node = fsq.Select(new - { - Address = "1" - }).ToOne(); - Assert.IsNull(node); - } - - [TestMethod()] - public async Task GetAllNodesAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var nodes = await service.GetAllNodesAsync(); - Assert.IsNotNull(nodes); - - Assert.AreEqual(1, nodes.Count); - } - - [TestMethod()] - public async Task GetAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var node = await service.GetAsync(source.Id); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "3"; - source.Status = NodeStatus.Online; - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result); - - var node = await service.GetAsync(source.Id); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); + return dict; } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/SettingServiceTests.cs index f67f0390..aa99004c 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/SettingServiceTests.cs @@ -1,230 +1,21 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using System.Linq; -using AgileConfig.Server.IService; -using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.Service.Tests.PostgreSQL { [TestClass()] - public class SettingServiceTests + public class SettingServiceTests_pg : SettingServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - ISettingService service = null; + string conn = "Host=192.168.0.125;Port=15432;Database=agileconfig;Username=postgres;Password=123456"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Host=127.0.0.1;Database=agile_config;Username=postgres;Password=dev@123"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.PostgreSQL, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "npgsql"; + dict["db:conn"] = conn; - IServiceCollection services = new ServiceCollection(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var setting = fsq.Select(new { - Id= id - }).ToOne(); - - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - result = await service.DeleteAsync(source); - Assert.IsTrue(result); - - var setting = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(setting); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - result = await service.DeleteAsync(id); - Assert.IsTrue(result); - - var setting = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(setting); - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var setting = await service.GetAsync(id); - - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [TestMethod()] - public async Task GetAllSettingsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Setting(); - source1.Id = id1; - source1.Value = "123"; - source1.CreateTime = DateTime.Now; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var settings = await service.GetAllSettingsAsync(); - - Assert.IsNotNull(settings); - - Assert.AreEqual(2, settings.Count); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.CreateTime = DateTime.Now; - source.Value = "321"; - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result1); - - var setting = await service.GetAsync(id); - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [TestMethod()] - public async Task SetAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - //var list = fsq.Select().Where("1=1").ToList(); - //Assert.IsNotNull(list); - //Assert.AreEqual(2, list.Count); - - //var pass = list.FirstOrDefault(s => s.Id == service.SuperAdminPasswordSettingKey); - //Assert.IsNotNull(pass); - //var salt = list.FirstOrDefault(s => s.Id == service.AdminPasswordHashSaltKey); - //Assert.IsNotNull(salt); - } - - [TestMethod()] - public async Task HasAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - - //var has = await service.HasSuperAdminPassword(); - //Assert.IsTrue(has); - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //has = await service.HasSuperAdminPassword(); - //Assert.IsFalse(has); - } - - [TestMethod()] - public async Task ValidateAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - - //var v = await service.ValidateAdminPassword("123456"); - //Assert.IsTrue(v); - //v = await service.ValidateAdminPassword("1234561"); - //Assert.IsFalse(v); + return dict; } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/SysLogServiceTests.cs index 097f199f..182b423d 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/SysLogServiceTests.cs @@ -1,192 +1,22 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; + +using AgileConfig.Server.ServiceTests.sqlite; using System.Collections.Generic; -using System.Text; -using AgileConfig.Server.Data.Freesql; -using FreeSql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.Data.Repository.Freesql; -using AgileConfig.Server.IService; -using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests.PostgreSQL { [TestClass()] - public class SysLogServiceTests + public class SysLogServiceTests_pg: SysLogServiceTests { + string conn = "Host=192.168.0.125;Port=15432;Database=agileconfig;Username=postgres;Password=123456"; - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - ISysLogService service = null; - - [TestInitialize] - public void TestInitialize() - { - string conn = "Host=127.0.0.1;Database=agile_config;Username=postgres;Password=dev@123"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.PostgreSQL, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); - - IServiceCollection services = new ServiceCollection(); - services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - [TestMethod()] - public async Task AddSysLogAsyncTest() - { - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - - var result = await service.AddSysLogAsync(source); - Assert.IsTrue(result); - - var log = fsq.Select(new { - Id = source.Id - }).ToOne(); - - Assert.IsNotNull(log); - - Assert.AreEqual(source.Id, log.Id); - Assert.AreEqual(source.AppId, log.AppId); - Assert.AreEqual(source.LogType, log.LogType); - // Assert.AreEqual(source.LogTime, log.LogTime); - Assert.AreEqual(source.LogText, log.LogText); - } - - - [TestMethod()] - public async Task AddRangeAsyncTest() - { - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List { - source, source1 - }); - Assert.IsTrue(result); - - var log = fsq.Select(new - { - Id = source.Id - }).ToOne(); - Assert.IsNotNull(log); - Assert.AreEqual(source.Id, log.Id); - Assert.AreEqual(source.AppId, log.AppId); - Assert.AreEqual(source.LogType, log.LogType); - // Assert.AreEqual(source.LogTime, log.LogTime); - Assert.AreEqual(source.LogText, log.LogText); - - var log1 = fsq.Select(new - { - Id = source1.Id - }).ToOne(); - Assert.IsNotNull(log1); - Assert.AreEqual(source1.Id, log1.Id); - Assert.AreEqual(source1.AppId, log1.AppId); - Assert.AreEqual(source1.LogType, log1.LogType); - // Assert.AreEqual(source1.LogTime, log1.LogTime); - Assert.AreEqual(source1.LogText, log1.LogText); - } - - - [TestMethod()] - public async Task CountTest() + public override Dictionary GetConfigurationData() { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List { - source, source1 - }); - Assert.IsTrue(result); - - var count = await service.Count("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1)); - Assert.AreEqual(1, count); - - var count1 = await service.Count("002", SysLogType.Warn,DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1)); - Assert.AreEqual(0, count1); - } - - [TestMethod()] - public async Task SearchPageTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List { - source, source1 - }); - Assert.IsTrue(result); - - var page = await service.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1),1,0); - Assert.AreEqual(1, page.Count); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "npgsql"; + dict["db:conn"] = conn; - var page1 = await service.SearchPage("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), 1, 0); - Assert.AreEqual(0, page1.Count); + return dict; } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs index 1360ff25..c77cfd76 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs @@ -2,12 +2,12 @@ using AgileConfig.Server.ServiceTests.sqlite; using System.Collections.Generic; -namespace AgileConfig.Server.Service.Tests.mysql +namespace AgileConfig.Server.ServiceTests.mysql { [TestClass()] - public class AppServiceTests_mysql: AppServiceTests + public class AppServiceTests_mysql : AppServiceTests { - string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=123456;port=13306"; + string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=mimi756310;port=13306"; public override Dictionary GetConfigurationData() { @@ -17,6 +17,6 @@ public override Dictionary GetConfigurationData() return dict; } - + } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs index daa7565e..29cb55ac 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs @@ -1,208 +1,22 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; using System; using System.Collections.Generic; -using System.Text; -using AgileConfig.Server.Data.Freesql; -using FreeSql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.Data.Repository.Freesql; -using AgileConfig.Server.IService; -using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.mysql +namespace AgileConfig.Server.ServiceTests.mysql { [TestClass()] - public class ServerNodeServiceTests + public class ServerNodeServiceTests_mysql : ServerNodeServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IServerNodeService service = null; + string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=mimi756310;port=13306"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Database=agile_config_test;Data Source=localhost;User Id=root;Password=dev@123;port=3306"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.MySql, conn) - .UseAutoSyncStructure(true) - .Build(); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "mysql"; + dict["db:conn"] = conn; - IServiceCollection services = new ServiceCollection(); - services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - - [TestMethod()] - public async Task AddAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var node = fsq.Select(new { - Address = "1" - }).ToOne(); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - //Assert.AreEqual(source.CreateTime, node.CreateTime); - //Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source); - Assert.IsTrue(result1); - - var node = fsq.Select(new - { - Address = "1" - }).ToOne(); - Assert.IsNull(node); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source.Id); - Assert.IsTrue(result1); - - var node = fsq.Select(new - { - Address = "1" - }).ToOne(); - Assert.IsNull(node); - } - - [TestMethod()] - public async Task GetAllNodesAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var nodes = await service.GetAllNodesAsync(); - Assert.IsNotNull(nodes); - - Assert.AreEqual(1, nodes.Count); - } - - [TestMethod()] - public async Task GetAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var node = await service.GetAsync(source.Id); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - //Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "3"; - source.Status = NodeStatus.Online; - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result); - - var node = await service.GetAsync(source.Id); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); + return dict; } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs index a73453f9..f215257a 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs @@ -1,230 +1,21 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using System.Linq; -using AgileConfig.Server.Common; -using AgileConfig.Server.IService; -using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.mysql +namespace AgileConfig.Server.ServiceTests.mysql { [TestClass()] - public class SettingServiceTests + public class SettingServiceTests_mysql : SettingServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - ISettingService service = null; + string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=mimi756310;port=13306"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Database=agile_config_test;Data Source=localhost;User Id=root;Password=dev@123;port=3306"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.MySql, conn) - .UseAutoSyncStructure(true) - .Build(); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "mysql"; + dict["db:conn"] = conn; - IServiceCollection services = new ServiceCollection(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var setting = fsq.Select(new { - Id= id - }).ToOne(); - - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - result = await service.DeleteAsync(source); - Assert.IsTrue(result); - - var setting = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(setting); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - result = await service.DeleteAsync(id); - Assert.IsTrue(result); - - var setting = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(setting); - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var setting = await service.GetAsync(id); - - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [TestMethod()] - public async Task GetAllSettingsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Setting(); - source1.Id = id1; - source1.Value = "123"; - source1.CreateTime = DateTime.Now; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var settings = await service.GetAllSettingsAsync(); - - Assert.IsNotNull(settings); - - Assert.AreEqual(2, settings.Count); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.CreateTime = DateTime.Now; - source.Value = "321"; - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result1); - - var setting = await service.GetAsync(id); - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [TestMethod()] - public async Task SetAdminPasswordTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var result = await service.SetSuperAdminPassword("123456"); - Assert.IsTrue(result); - var list = fsq.Select().Where("1=1").ToList(); - Assert.IsNotNull(list); - Assert.AreEqual(2, list.Count); - - var pass = list.FirstOrDefault(s => s.Id == SystemSettings.SuperAdminUserName); - Assert.IsNotNull(pass); - var salt = list.FirstOrDefault(s => s.Id == SystemSettings.SuperAdminId); - Assert.IsNotNull(salt); - } - - [TestMethod()] - public async Task HasAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - - //var has = await service.HasSuperAdminPassword(); - //Assert.IsTrue(has); - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //has = await service.HasSuperAdminPassword(); - //Assert.IsFalse(has); - } - - [TestMethod()] - public async Task ValidateAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - - //var v = await service.ValidateAdminPassword("123456"); - //Assert.IsTrue(v); - //v = await service.ValidateAdminPassword("1234561"); - //Assert.IsFalse(v); + return dict; } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mysql/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/SysLogServiceTests.cs index b4021f00..dd70ec2c 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/SysLogServiceTests.cs @@ -1,191 +1,21 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; +using AgileConfig.Server.ServiceTests.sqlite; using System.Collections.Generic; -using System.Text; -using AgileConfig.Server.Data.Freesql; -using FreeSql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.Data.Repository.Freesql; -using AgileConfig.Server.IService; -using Microsoft.Extensions.DependencyInjection; -namespace AgileConfig.Server.Service.Tests.mysql +namespace AgileConfig.Server.ServiceTests.mysql { [TestClass()] - public class SysLogServiceTests + public class SysLogServiceTests_mysql : SysLogServiceTests { + string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=mimi756310;port=13306"; - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - ISysLogService service = null; - - [TestInitialize] - public void TestInitialize() - { - string conn = "Database=agile_config_test;Data Source=localhost;User Id=root;Password=dev@123;port=3306"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.MySql, conn) - .UseAutoSyncStructure(true) - .Build(); - freeSqlContext = new FreeSqlContext(fsq); - - IServiceCollection services = new ServiceCollection(); - services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() + public override Dictionary GetConfigurationData() { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - [TestMethod()] - public async Task AddSysLogAsyncTest() - { - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - - var result = await service.AddSysLogAsync(source); - Assert.IsTrue(result); - - var log = fsq.Select(new { - Id = source.Id - }).ToOne(); - - Assert.IsNotNull(log); - - Assert.AreEqual(source.Id, log.Id); - Assert.AreEqual(source.AppId, log.AppId); - Assert.AreEqual(source.LogType, log.LogType); - // Assert.AreEqual(source.LogTime, log.LogTime); - Assert.AreEqual(source.LogText, log.LogText); - } - - - [TestMethod()] - public async Task AddRangeAsyncTest() - { - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List { - source, source1 - }); - Assert.IsTrue(result); - - var log = fsq.Select(new - { - Id = source.Id - }).ToOne(); - Assert.IsNotNull(log); - Assert.AreEqual(source.Id, log.Id); - Assert.AreEqual(source.AppId, log.AppId); - Assert.AreEqual(source.LogType, log.LogType); - // Assert.AreEqual(source.LogTime, log.LogTime); - Assert.AreEqual(source.LogText, log.LogText); - - var log1 = fsq.Select(new - { - Id = source1.Id - }).ToOne(); - Assert.IsNotNull(log1); - Assert.AreEqual(source1.Id, log1.Id); - Assert.AreEqual(source1.AppId, log1.AppId); - Assert.AreEqual(source1.LogType, log1.LogType); - // Assert.AreEqual(source1.LogTime, log1.LogTime); - Assert.AreEqual(source1.LogText, log1.LogText); - } - - - [TestMethod()] - public async Task CountTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List { - source, source1 - }); - Assert.IsTrue(result); - - var count = await service.Count("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1)); - Assert.AreEqual(1, count); - - var count1 = await service.Count("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1)); - Assert.AreEqual(0, count1); - } - - [TestMethod()] - public async Task SearchPageTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List { - source, source1 - }); - Assert.IsTrue(result); - - var page = await service.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1),1,0); - Assert.AreEqual(1, page.Count); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "mysql"; + dict["db:conn"] = conn; - var page1 = await service.SearchPage("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), 1, 0); - Assert.AreEqual(0, page1.Count); + return dict; } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs index 59206aef..f4c34bef 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs @@ -1,209 +1,22 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; using System.Collections.Generic; -using System.Text; -using AgileConfig.Server.Data.Freesql; -using FreeSql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.Data.Repository.Freesql; -using AgileConfig.Server.IService; -using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.Service.Tests.oracle { [TestClass()] - public class ServerNodeServiceTests + public class ServerNodeServiceTests_oracle: ServerNodeServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IServerNodeService service = null; + string conn = "user id=x;password=x;data source=192.168.0.123/orcl"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "user id=CLINIC;password=CLINIC;data source=192.168.0.91/orcl"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Oracle, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "oracle"; + dict["db:conn"] = conn; - IServiceCollection services = new ServiceCollection(); - services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - - [TestMethod()] - public async Task AddAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var node = fsq.Select(new { - Address = "1" - }).ToOne(); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source); - Assert.IsTrue(result1); - - var node = fsq.Select(new - { - Address = "1" - }).ToOne(); - Assert.IsNull(node); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source.Id); - Assert.IsTrue(result1); - - var node = fsq.Select(new - { - Address = "1" - }).ToOne(); - Assert.IsNull(node); - } - - [TestMethod()] - public async Task GetAllNodesAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var nodes = await service.GetAllNodesAsync(); - Assert.IsNotNull(nodes); - - Assert.AreEqual(1, nodes.Count); + return dict; } - [TestMethod()] - public async Task GetAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var node = await service.GetAsync(source.Id); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "3"; - source.Status = NodeStatus.Online; - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result); - - var node = await service.GetAsync(source.Id); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/oracle/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/SettingServiceTests.cs index d2669e00..93249637 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/SettingServiceTests.cs @@ -1,230 +1,21 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using System.Linq; -using AgileConfig.Server.IService; -using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.Service.Tests.oracle { [TestClass()] - public class SettingServiceTests + public class SettingServiceTests_oracle : SettingServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - ISettingService service = null; + string conn = "user id=x;password=x;data source=192.168.0.123/orcl"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "user id=CLINIC;password=CLINIC;data source=192.168.0.91/orcl"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Oracle, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "oracle"; + dict["db:conn"] = conn; - IServiceCollection services = new ServiceCollection(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var setting = fsq.Select(new { - Id= id - }).ToOne(); - - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - result = await service.DeleteAsync(source); - Assert.IsTrue(result); - - var setting = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(setting); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - result = await service.DeleteAsync(id); - Assert.IsTrue(result); - - var setting = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(setting); - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var setting = await service.GetAsync(id); - - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [TestMethod()] - public async Task GetAllSettingsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Setting(); - source1.Id = id1; - source1.Value = "123"; - source1.CreateTime = DateTime.Now; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var settings = await service.GetAllSettingsAsync(); - - Assert.IsNotNull(settings); - - Assert.AreEqual(2, settings.Count); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.CreateTime = DateTime.Now; - source.Value = "321"; - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result1); - - var setting = await service.GetAsync(id); - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [TestMethod()] - public async Task SetAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - //var list = fsq.Select().Where("1=1").ToList(); - //Assert.IsNotNull(list); - //Assert.AreEqual(2, list.Count); - - //var pass = list.FirstOrDefault(s => s.Id == service.SuperAdminPasswordSettingKey); - //Assert.IsNotNull(pass); - //var salt = list.FirstOrDefault(s => s.Id == service.AdminPasswordHashSaltKey); - //Assert.IsNotNull(salt); - } - - [TestMethod()] - public async Task HasAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - - //var has = await service.HasSuperAdminPassword(); - //Assert.IsTrue(has); - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //has = await service.HasSuperAdminPassword(); - //Assert.IsFalse(has); - } - - [TestMethod()] - public async Task ValidateAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - - //var v = await service.ValidateAdminPassword("123456"); - //Assert.IsTrue(v); - //v = await service.ValidateAdminPassword("1234561"); - //Assert.IsFalse(v); + return dict; } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/oracle/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/SysLogServiceTests.cs index b0a18c1e..7427d931 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/SysLogServiceTests.cs @@ -1,192 +1,22 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; using System.Collections.Generic; -using System.Text; -using AgileConfig.Server.Data.Freesql; -using FreeSql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.Data.Repository.Freesql; -using AgileConfig.Server.IService; -using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.Service.Tests.oracle { [TestClass()] - public class SysLogServiceTests + public class SysLogServiceTests_oracle : SysLogServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - ISysLogService service = null; + string conn = "user id=x;password=x;data source=192.168.0.123/orcl"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "user id=CLINIC;password=CLINIC;data source=192.168.0.91/orcl"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Oracle, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "oracle"; + dict["db:conn"] = conn; - IServiceCollection services = new ServiceCollection(); - services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - [TestMethod()] - public async Task AddSysLogAsyncTest() - { - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - - var result = await service.AddSysLogAsync(source); - Assert.IsTrue(result); - - var log = fsq.Select(new { - Id = source.Id - }).ToOne(); - - Assert.IsNotNull(log); - - Assert.AreEqual(source.Id, log.Id); - Assert.AreEqual(source.AppId, log.AppId); - Assert.AreEqual(source.LogType, log.LogType); - // Assert.AreEqual(source.LogTime, log.LogTime); - Assert.AreEqual(source.LogText, log.LogText); - } - - - [TestMethod()] - public async Task AddRangeAsyncTest() - { - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List { - source, source1 - }); - Assert.IsTrue(result); - - var log = fsq.Select(new - { - Id = source.Id - }).ToOne(); - Assert.IsNotNull(log); - Assert.AreEqual(source.Id, log.Id); - Assert.AreEqual(source.AppId, log.AppId); - Assert.AreEqual(source.LogType, log.LogType); - // Assert.AreEqual(source.LogTime, log.LogTime); - Assert.AreEqual(source.LogText, log.LogText); - - var log1 = fsq.Select(new - { - Id = source1.Id - }).ToOne(); - Assert.IsNotNull(log1); - Assert.AreEqual(source1.Id, log1.Id); - Assert.AreEqual(source1.AppId, log1.AppId); - Assert.AreEqual(source1.LogType, log1.LogType); - // Assert.AreEqual(source1.LogTime, log1.LogTime); - Assert.AreEqual(source1.LogText, log1.LogText); - } - - - [TestMethod()] - public async Task CountTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List { - source, source1 - }); - Assert.IsTrue(result); - - var count = await service.Count("001", SysLogType.Normal,DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1)); - Assert.AreEqual(1, count); - - var count1 = await service.Count("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1)); - Assert.AreEqual(0, count1); - } - - [TestMethod()] - public async Task SearchPageTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List { - source, source1 - }); - Assert.IsTrue(result); - - var page = await service.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1),1,0); - Assert.AreEqual(1, page.Count); - - var page1 = await service.SearchPage("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), 1, 0); - Assert.AreEqual(0, page1.Count); + return dict; } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs index f26ed8d8..a02685d5 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs @@ -20,16 +20,12 @@ namespace AgileConfig.Server.ServiceTests.sqlite { [TestClass()] - public class AppServiceTests + public class AppServiceTests: BasicTestService { - - private ServiceProvider _serviceProvider; - IFreeSql _fsq = null; IAppService _appservice = null; - - public virtual Dictionary GetConfigurationData() + public override Dictionary GetConfigurationData() { - return + return new Dictionary { {"db:provider","sqlite" }, @@ -40,69 +36,10 @@ public virtual Dictionary GetConfigurationData() [TestInitialize] public void TestInitialize() { - var config = new ConfigurationBuilder() - .AddInMemoryCollection(GetConfigurationData()) - .Build(); - Global.Config = config; - - var factory = new EnvFreeSqlFactory(); - _fsq = factory.Create(""); - - var cache = new Mock(); - IServiceCollection services = new ServiceCollection(); - services.AddScoped(_ => cache.Object); - services.AddSingleton(config); - services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); - services.AddBusinessServices(); - AddEnvRepositiroies(services); - - _serviceProvider = services.BuildServiceProvider(); - var systeminitializationService = _serviceProvider.GetService(); - systeminitializationService.TryInitDefaultEnvironmentAsync();//初始化环境 DEV TEST STAGE PROD - systeminitializationService.TryInitJwtSecret();//初始化 jwt secret - _appservice = _serviceProvider.GetService(); - - _fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); + _fsq.Delete().Where("1=1"); } - private static void AddEnvRepositiroies(IServiceCollection sc) - { - sc.AddScoped>(sp => env => - { - var factory = sp.GetService(); - var fsq = factory.Create(env); - return new FreeSqlUow(fsq); - }); - - sc.AddScoped>(sp => env => - { - var factory = sp.GetService(); - return new ConfigPublishedRepository(factory.Create(env)); - }); - - sc.AddScoped>(sp => env => - { - var factory = sp.GetService(); - - return new ConfigRepository(factory.Create(env)); - }); - - sc.AddScoped>(sp => env => - { - var factory = sp.GetService(); - return new PublishDetailRepository(factory.Create(env)); - }); - - sc.AddScoped>(sp => env => - { - var factory = sp.GetService(); - return new PublishTimelineRepository(factory.Create(env)); - }); - } [TestMethod()] public async Task AddAsyncTest() diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/BasicTestService.cs b/test/AgileConfig.Server.ServiceTests/sqlite/BasicTestService.cs new file mode 100644 index 00000000..1f5f14e8 --- /dev/null +++ b/test/AgileConfig.Server.ServiceTests/sqlite/BasicTestService.cs @@ -0,0 +1,94 @@ +using AgileConfig.Server.Common; +using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Freesql; +using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.IService; +using AgileConfig.Server.Service; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using System; +using System.Collections.Generic; + +namespace AgileConfig.Server.ServiceTests.sqlite +{ + public class BasicTestService + { + protected ServiceProvider _serviceProvider; + protected IFreeSql _fsq = null; + + public virtual Dictionary GetConfigurationData() + { + return + new Dictionary + { + {"db:provider","sqlite" }, + {"db:conn","Data Source=agile_config.db" } + }; + } + + public BasicTestService() + { + var config = new ConfigurationBuilder() + .AddInMemoryCollection(GetConfigurationData()) + .Build(); + Global.Config = config; + + var factory = new EnvFreeSqlFactory(); + _fsq = factory.Create(""); + + var cache = new Mock(); + IServiceCollection services = new ServiceCollection(); + services.AddScoped(_ => cache.Object); + services.AddSingleton(config); + services.AddFreeSqlFactory(); + services.AddFreeSqlRepository(); + services.AddBusinessServices(); + AddEnvRepositiroies(services); + + _serviceProvider = services.BuildServiceProvider(); + var systeminitializationService = _serviceProvider.GetService(); + systeminitializationService.TryInitDefaultEnvironmentAsync();//初始化环境 DEV TEST STAGE PROD + systeminitializationService.TryInitJwtSecret();//初始化 jwt secret + + Console.WriteLine("Run BasicTestService"); + } + + private static void AddEnvRepositiroies(IServiceCollection sc) + { + sc.AddScoped>(sp => env => + { + var factory = sp.GetService(); + var fsq = factory.Create(env); + return new FreeSqlUow(fsq); + }); + + sc.AddScoped>(sp => env => + { + var factory = sp.GetService(); + return new ConfigPublishedRepository(factory.Create(env)); + }); + + sc.AddScoped>(sp => env => + { + var factory = sp.GetService(); + + return new ConfigRepository(factory.Create(env)); + }); + + sc.AddScoped>(sp => env => + { + var factory = sp.GetService(); + return new PublishDetailRepository(factory.Create(env)); + }); + + sc.AddScoped>(sp => env => + { + var factory = sp.GetService(); + return new PublishTimelineRepository(factory.Create(env)); + }); + } + + } +} diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs index 3a7fb9f0..dec1baa8 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs @@ -1,61 +1,39 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; using System; using System.Collections.Generic; -using System.Text; -using AgileConfig.Server.Data.Freesql; -using FreeSql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; -using AgileConfig.Server.Data.Repository.Freesql; using AgileConfig.Server.IService; using Microsoft.Extensions.DependencyInjection; +using MongoDB.Driver.Linq; -namespace AgileConfig.Server.Service.Tests +namespace AgileConfig.Server.ServiceTests.sqlite { [TestClass()] - public class ServerNodeServiceTests + public class ServerNodeServiceTests: BasicTestService { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IServerNodeService service = null; - - [TestInitialize] - public void TestInitialize() + IServerNodeService _serverNodeService = null; + public override Dictionary GetConfigurationData() { - string conn = "Data Source=agile_config.db"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, conn) - .UseAutoSyncStructure(true) - .Build(); - freeSqlContext = new FreeSqlContext(fsq); - - IServiceCollection services = new ServiceCollection(); - services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); + return + new Dictionary + { + {"db:provider","sqlite" }, + {"db:conn","Data Source=agile_config.db" } + }; } - - - [TestCleanup] - public void Clean() + [TestInitialize] + public void TestInitialize() { - freeSqlContext.Dispose(); - fsq.Dispose(); + _serverNodeService = _serviceProvider.GetService(); + _fsq.Delete().Where("1=1"); } [TestMethod()] public async Task AddAsyncTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); source.Id = "1"; @@ -64,17 +42,18 @@ public async Task AddAsyncTest() source.Remark = "2"; source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); + var result = await _serverNodeService.AddAsync(source); Assert.IsTrue(result); - var node = fsq.Select(new { + var node = _fsq.Select(new + { Address = "1" }).ToOne(); Assert.IsNotNull(node); Assert.AreEqual(source.Id, node.Id); - Assert.AreEqual(source.CreateTime, node.CreateTime); - Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); + Assert.AreEqual(source.CreateTime.ToString("yyyyMMddHHmmss"), node.CreateTime.ToString("yyyyMMddHHmmss")); + Assert.AreEqual(source.LastEchoTime.Value.ToString("yyyyMMddHHmmss"), node.LastEchoTime.Value.ToString("yyyyMMddHHmmss")); Assert.AreEqual(source.Remark, node.Remark); Assert.AreEqual(source.Status, node.Status); } @@ -82,7 +61,7 @@ public async Task AddAsyncTest() [TestMethod()] public async Task DeleteAsyncTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); source.Id = "1"; @@ -91,13 +70,13 @@ public async Task DeleteAsyncTest() source.Remark = "2"; source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); + var result = await _serverNodeService.AddAsync(source); Assert.IsTrue(result); - var result1 = await service.DeleteAsync(source); + var result1 = await _serverNodeService.DeleteAsync(source); Assert.IsTrue(result1); - var node = fsq.Select(new + var node = _fsq.Select(new { Address = "1" }).ToOne(); @@ -107,7 +86,7 @@ public async Task DeleteAsyncTest() [TestMethod()] public async Task DeleteAsyncTest1() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); source.Id = "1"; @@ -116,13 +95,13 @@ public async Task DeleteAsyncTest1() source.Remark = "2"; source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); + var result = await _serverNodeService.AddAsync(source); Assert.IsTrue(result); - var result1 = await service.DeleteAsync(source.Id); + var result1 = await _serverNodeService.DeleteAsync(source.Id); Assert.IsTrue(result1); - var node = fsq.Select(new + var node = _fsq.Select(new { Address = "1" }).ToOne(); @@ -132,7 +111,7 @@ public async Task DeleteAsyncTest1() [TestMethod()] public async Task GetAllNodesAsyncTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); source.Id = "1"; @@ -141,10 +120,10 @@ public async Task GetAllNodesAsyncTest() source.Remark = "2"; source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); + var result = await _serverNodeService.AddAsync(source); Assert.IsTrue(result); - var nodes = await service.GetAllNodesAsync(); + var nodes = await _serverNodeService.GetAllNodesAsync(); Assert.IsNotNull(nodes); Assert.AreEqual(1, nodes.Count); @@ -153,7 +132,7 @@ public async Task GetAllNodesAsyncTest() [TestMethod()] public async Task GetAsyncTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); source.Id = "1"; @@ -161,15 +140,15 @@ public async Task GetAsyncTest() source.LastEchoTime = DateTime.Now; source.Remark = "2"; source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); + var result = await _serverNodeService.AddAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Id); + var node = await _serverNodeService.GetAsync(source.Id); Assert.IsNotNull(node); Assert.AreEqual(source.Id, node.Id); - Assert.AreEqual(source.CreateTime, node.CreateTime); - Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); + Assert.AreEqual(source.CreateTime.ToString("yyyyMMddHHmmss"), node.CreateTime.ToString("yyyyMMddHHmmss")); + Assert.AreEqual(source.LastEchoTime.Value.ToString("yyyyMMddHHmmss"), node.LastEchoTime.Value.ToString("yyyyMMddHHmmss")); Assert.AreEqual(source.Remark, node.Remark); Assert.AreEqual(source.Status, node.Status); } @@ -177,7 +156,7 @@ public async Task GetAsyncTest() [TestMethod()] public async Task UpdateAsyncTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new ServerNode(); source.Id = "1"; @@ -185,22 +164,22 @@ public async Task UpdateAsyncTest() source.LastEchoTime = DateTime.Now; source.Remark = "2"; source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); + var result = await _serverNodeService.AddAsync(source); Assert.IsTrue(result); source.CreateTime = DateTime.Now; source.LastEchoTime = DateTime.Now; source.Remark = "3"; source.Status = NodeStatus.Online; - var result1 = await service.UpdateAsync(source); + var result1 = await _serverNodeService.UpdateAsync(source); Assert.IsTrue(result); - var node = await service.GetAsync(source.Id); + var node = await _serverNodeService.GetAsync(source.Id); Assert.IsNotNull(node); Assert.AreEqual(source.Id, node.Id); - Assert.AreEqual(source.CreateTime, node.CreateTime); - Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); + Assert.AreEqual(source.CreateTime.ToString("yyyyMMddHHmmss"), node.CreateTime.ToString("yyyyMMddHHmmss")); + Assert.AreEqual(source.LastEchoTime.Value.ToString("yyyyMMddHHmmss"), node.LastEchoTime.Value.ToString("yyyyMMddHHmmss")); Assert.AreEqual(source.Remark, node.Remark); Assert.AreEqual(source.Status, node.Status); } diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/SettingServiceTests.cs index d96db45e..be5b515d 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/SettingServiceTests.cs @@ -1,55 +1,35 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; using System; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; -using System.Linq; using AgileConfig.Server.IService; using Microsoft.Extensions.DependencyInjection; -namespace AgileConfig.Server.Service.Tests +namespace AgileConfig.Server.ServiceTests.sqlite { [TestClass()] - public class SettingServiceTests + public class SettingServiceTests : BasicTestService { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - ISettingService service = null; + ISettingService _settingService = null; + public override Dictionary GetConfigurationData() + { + return + new Dictionary + { + {"db:provider","sqlite" }, + {"db:conn","Data Source=agile_config.db" } + }; + } [TestInitialize] public void TestInitialize() { - string conn = "Data Source=agile_config.db"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, conn) - .UseAutoSyncStructure(true) - .Build(); - freeSqlContext = new FreeSqlContext(fsq); - - IServiceCollection services = new ServiceCollection(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); + _settingService = _serviceProvider.GetService(); + _fsq.Delete().Where("1=1"); } - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - [TestMethod()] public async Task AddAsyncTest() { @@ -58,11 +38,12 @@ public async Task AddAsyncTest() source.Id = id; source.Value = "123"; source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); + var result = await _settingService.AddAsync(source); Assert.IsTrue(result); - var setting = fsq.Select(new { - Id= id + var setting = _fsq.Select(new + { + Id = id }).ToOne(); Assert.IsNotNull(setting); @@ -79,13 +60,13 @@ public async Task DeleteAsyncTest() source.Id = id; source.Value = "123"; source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); + var result = await _settingService.AddAsync(source); Assert.IsTrue(result); - result = await service.DeleteAsync(source); + result = await _settingService.DeleteAsync(source); Assert.IsTrue(result); - var setting = fsq.Select(new + var setting = _fsq.Select(new { Id = id }).ToOne(); @@ -101,13 +82,13 @@ public async Task DeleteAsyncTest1() source.Id = id; source.Value = "123"; source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); + var result = await _settingService.AddAsync(source); Assert.IsTrue(result); - result = await service.DeleteAsync(id); + result = await _settingService.DeleteAsync(id); Assert.IsTrue(result); - var setting = fsq.Select(new + var setting = _fsq.Select(new { Id = id }).ToOne(); @@ -123,10 +104,10 @@ public async Task GetAsyncTest() source.Id = id; source.Value = "123"; source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); + var result = await _settingService.AddAsync(source); Assert.IsTrue(result); - var setting = await service.GetAsync(id); + var setting = await _settingService.GetAsync(id); Assert.IsNotNull(setting); @@ -137,23 +118,23 @@ public async Task GetAsyncTest() [TestMethod()] public async Task GetAllSettingsAsyncTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var id = Guid.NewGuid().ToString(); var source = new Setting(); source.Id = id; source.Value = "123"; source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); + var result = await _settingService.AddAsync(source); Assert.IsTrue(result); var id1 = Guid.NewGuid().ToString(); var source1 = new Setting(); source1.Id = id1; source1.Value = "123"; source1.CreateTime = DateTime.Now; - var result1 = await service.AddAsync(source1); + var result1 = await _settingService.AddAsync(source1); Assert.IsTrue(result1); - var settings = await service.GetAllSettingsAsync(); + var settings = await _settingService.GetAllSettingsAsync(); Assert.IsNotNull(settings); @@ -168,62 +149,20 @@ public async Task UpdateAsyncTest() source.Id = id; source.Value = "123"; source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); + var result = await _settingService.AddAsync(source); Assert.IsTrue(result); source.CreateTime = DateTime.Now; source.Value = "321"; - var result1 = await service.UpdateAsync(source); + var result1 = await _settingService.UpdateAsync(source); Assert.IsTrue(result1); - var setting = await service.GetAsync(id); + var setting = await _settingService.GetAsync(id); Assert.IsNotNull(setting); Assert.AreEqual(source.Id, setting.Id); Assert.AreEqual(source.Value, setting.Value); } - [TestMethod()] - public async Task SetAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - //var list = fsq.Select().Where("1=1").ToList(); - //Assert.IsNotNull(list); - //Assert.AreEqual(2, list.Count); - - //var pass = list.FirstOrDefault(s => s.Id == service.SuperAdminPasswordSettingKey); - //Assert.IsNotNull(pass); - //var salt = list.FirstOrDefault(s => s.Id == service.AdminPasswordHashSaltKey); - //Assert.IsNotNull(salt); - } - - [TestMethod()] - public async Task HasAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - - //var has = await service.HasSuperAdminPassword(); - //Assert.IsTrue(has); - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //has = await service.HasSuperAdminPassword(); - //Assert.IsFalse(has); - } - - [TestMethod()] - public async Task ValidateAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - - //var v = await service.ValidateAdminPassword("123456"); - //Assert.IsTrue(v); - //v = await service.ValidateAdminPassword("1234561"); - //Assert.IsFalse(v); - } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs index f84493f9..ade1033b 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs @@ -2,56 +2,36 @@ using AgileConfig.Server.Service; using System; using System.Collections.Generic; -using System.Text; -using AgileConfig.Server.Data.Freesql; -using FreeSql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; -using AgileConfig.Server.Data.Repository.Freesql; using AgileConfig.Server.IService; using Microsoft.Extensions.DependencyInjection; +using MongoDB.Driver.Linq; -namespace AgileConfig.Server.Service.Tests +namespace AgileConfig.Server.ServiceTests.sqlite { [TestClass()] - public class SysLogServiceTests + public class SysLogServiceTests: BasicTestService { - - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - ISysLogService service = null; + ISysLogService _syslogservice = null; + public override Dictionary GetConfigurationData() + { + return + new Dictionary + { + {"db:provider","sqlite" }, + {"db:conn","Data Source=agile_config.db" } + }; + } [TestInitialize] public void TestInitialize() { - string conn = "Data Source=agile_config.db"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, conn) - .UseAutoSyncStructure(true) - .Build(); - freeSqlContext = new FreeSqlContext(fsq); - - IServiceCollection services = new ServiceCollection(); - services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); + _syslogservice = _serviceProvider.GetService(); + _fsq.Delete().Where("1=1"); } - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } [TestMethod()] public async Task AddSysLogAsyncTest() { @@ -63,11 +43,12 @@ public async Task AddSysLogAsyncTest() LogText = "123" }; - var result = await service.AddSysLogAsync(source); + var result = await _syslogservice.AddSysLogAsync(source); Assert.IsTrue(result); - var log = fsq.Select(new { - Id = source.Id + var log = _fsq.Select(new + { + source.Id }).ToOne(); Assert.IsNotNull(log); @@ -75,7 +56,7 @@ public async Task AddSysLogAsyncTest() Assert.AreEqual(source.Id, log.Id); Assert.AreEqual(source.AppId, log.AppId); Assert.AreEqual(source.LogType, log.LogType); - Assert.AreEqual(source.LogTime, log.LogTime); + Assert.AreEqual(source.LogTime.Value.ToString("yyyyMMddHHmmss"), log.LogTime.Value.ToString("yyyyMMddHHmmss")); Assert.AreEqual(source.LogText, log.LogText); } @@ -97,39 +78,39 @@ public async Task AddRangeAsyncTest() LogTime = DateTime.Now, LogText = "124" }; - var result = await service.AddRangeAsync(new List { + var result = await _syslogservice.AddRangeAsync(new List { source, source1 }); Assert.IsTrue(result); - var log = fsq.Select(new + var log = _fsq.Select(new { - Id = source.Id + source.Id }).ToOne(); Assert.IsNotNull(log); Assert.AreEqual(source.Id, log.Id); Assert.AreEqual(source.AppId, log.AppId); Assert.AreEqual(source.LogType, log.LogType); - Assert.AreEqual(source.LogTime, log.LogTime); + Assert.AreEqual(source.LogTime.Value.ToString("yyyyMMddHHmmss"), log.LogTime.Value.ToString("yyyyMMddHHmmss")); Assert.AreEqual(source.LogText, log.LogText); - var log1 = fsq.Select(new + var log1 = _fsq.Select(new { - Id = source1.Id + source1.Id }).ToOne(); Assert.IsNotNull(log1); Assert.AreEqual(source1.Id, log1.Id); Assert.AreEqual(source1.AppId, log1.AppId); Assert.AreEqual(source1.LogType, log1.LogType); - Assert.AreEqual(source1.LogTime, log1.LogTime); + Assert.AreEqual(source1.LogTime.Value.ToString("yyyyMMddHHmmss"), log1.LogTime.Value.ToString("yyyyMMddHHmmss")); Assert.AreEqual(source1.LogText, log1.LogText); } - + [TestMethod()] public async Task CountTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new SysLog { @@ -145,22 +126,22 @@ public async Task CountTest() LogTime = DateTime.Now, LogText = "124" }; - var result = await service.AddRangeAsync(new List { + var result = await _syslogservice.AddRangeAsync(new List { source, source1 }); Assert.IsTrue(result); - var count = await service.Count("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1)); + var count = await _syslogservice.Count("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1)); Assert.AreEqual(1, count); - var count1 = await service.Count("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1)); + var count1 = await _syslogservice.Count("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1)); Assert.AreEqual(0, count1); } [TestMethod()] public async Task SearchPageTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var source = new SysLog { @@ -176,15 +157,15 @@ public async Task SearchPageTest() LogTime = DateTime.Now, LogText = "124" }; - var result = await service.AddRangeAsync(new List { + var result = await _syslogservice.AddRangeAsync(new List { source, source1 }); Assert.IsTrue(result); - var page = await service.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1),1,0); + var page = await _syslogservice.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1), 1, 0); Assert.AreEqual(1, page.Count); - var page1 = await service.SearchPage("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), 1, 0); + var page1 = await _syslogservice.SearchPage("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), 1, 0); Assert.AreEqual(0, page1.Count); } } diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs index fffc3332..aaa4fdac 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs @@ -1,14 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.IService; -using System.Runtime.CompilerServices; using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.Service.Tests.sqlserver diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs index 7b13b63f..f6e4494d 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs @@ -1,209 +1,22 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; using System.Collections.Generic; -using System.Text; -using AgileConfig.Server.Data.Freesql; -using FreeSql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.Data.Repository.Freesql; -using AgileConfig.Server.IService; -using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.Service.Tests.sqlserver { [TestClass()] - public class ServerNodeServiceTests + public class ServerNodeServiceTests_sqlserver: ServerNodeServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IServerNodeService service = null; + string conn = "TrustServerCertificate=True;Persist Security Info = False; User ID =dev; Password =dev; Initial Catalog =agile_config_test; Server =."; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Persist Security Info = False; User ID =dev; Password =dev@123,; Initial Catalog =agile_config_test; Server =www..com"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.SqlServer, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); - - IServiceCollection services = new ServiceCollection(); - services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "sqlserver"; + dict["db:conn"] = conn; - Console.WriteLine("TestInitialize"); + return dict; } - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - - [TestMethod()] - public async Task AddAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var node = fsq.Select(new { - Id = "1" - }).ToOne(); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source); - Assert.IsTrue(result1); - - var node = fsq.Select(new - { - Id = "1" - }).ToOne(); - Assert.IsNull(node); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source.Id); - Assert.IsTrue(result1); - - var node = fsq.Select(new - { - Id = "1" - }).ToOne(); - Assert.IsNull(node); - } - - [TestMethod()] - public async Task GetAllNodesAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var nodes = await service.GetAllNodesAsync(); - Assert.IsNotNull(nodes); - - Assert.AreEqual(1, nodes.Count); - } - - [TestMethod()] - public async Task GetAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var node = await service.GetAsync(source.Id); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new ServerNode(); - source.Id = "1"; - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "2"; - source.Status = NodeStatus.Offline; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.CreateTime = DateTime.Now; - source.LastEchoTime = DateTime.Now; - source.Remark = "3"; - source.Status = NodeStatus.Online; - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result); - - var node = await service.GetAsync(source.Id); - Assert.IsNotNull(node); - - Assert.AreEqual(source.Id, node.Id); - // Assert.AreEqual(source.CreateTime, node.CreateTime); - // Assert.AreEqual(source.LastEchoTime, node.LastEchoTime); - Assert.AreEqual(source.Remark, node.Remark); - Assert.AreEqual(source.Status, node.Status); - } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/SettingServiceTests.cs index 06e727d1..772e2f5b 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/SettingServiceTests.cs @@ -1,230 +1,21 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using System.Linq; -using AgileConfig.Server.IService; -using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.Service.Tests.sqlserver { [TestClass()] - public class SettingServiceTests + public class SettingServiceTests_sqlserver : SettingServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - ISettingService service = null; + string conn = "TrustServerCertificate=True;Persist Security Info = False; User ID =dev; Password =dev; Initial Catalog =agile_config_test; Server =."; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Persist Security Info = False; User ID =dev; Password =dev@123,; Initial Catalog =agile_config_test; Server =www..com"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.SqlServer, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); - - IServiceCollection services = new ServiceCollection(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "sqlserver"; + dict["db:conn"] = conn; - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var setting = fsq.Select(new { - Id= id - }).ToOne(); - - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - result = await service.DeleteAsync(source); - Assert.IsTrue(result); - - var setting = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(setting); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - result = await service.DeleteAsync(id); - Assert.IsTrue(result); - - var setting = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(setting); - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - var setting = await service.GetAsync(id); - - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [TestMethod()] - public async Task GetAllSettingsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - var id1 = Guid.NewGuid().ToString(); - var source1 = new Setting(); - source1.Id = id1; - source1.Value = "123"; - source1.CreateTime = DateTime.Now; - var result1 = await service.AddAsync(source1); - Assert.IsTrue(result1); - - var settings = await service.GetAllSettingsAsync(); - - Assert.IsNotNull(settings); - - Assert.AreEqual(2, settings.Count); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Setting(); - source.Id = id; - source.Value = "123"; - source.CreateTime = DateTime.Now; - var result = await service.AddAsync(source); - Assert.IsTrue(result); - - source.CreateTime = DateTime.Now; - source.Value = "321"; - var result1 = await service.UpdateAsync(source); - Assert.IsTrue(result1); - - var setting = await service.GetAsync(id); - Assert.IsNotNull(setting); - - Assert.AreEqual(source.Id, setting.Id); - Assert.AreEqual(source.Value, setting.Value); - } - - [TestMethod()] - public async Task SetAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - //var list = fsq.Select().Where("1=1").ToList(); - //Assert.IsNotNull(list); - //Assert.AreEqual(2, list.Count); - - //var pass = list.FirstOrDefault(s => s.Id == service.SuperAdminPasswordSettingKey); - //Assert.IsNotNull(pass); - //var salt = list.FirstOrDefault(s => s.Id == service.AdminPasswordHashSaltKey); - //Assert.IsNotNull(salt); - } - - [TestMethod()] - public async Task HasAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - - //var has = await service.HasSuperAdminPassword(); - //Assert.IsTrue(has); - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //has = await service.HasSuperAdminPassword(); - //Assert.IsFalse(has); - } - - [TestMethod()] - public async Task ValidateAdminPasswordTest() - { - //fsq.Delete().Where("1=1").ExecuteAffrows(); - //var result = await service.SetSuperAdminPassword("123456"); - //Assert.IsTrue(result); - - //var v = await service.ValidateAdminPassword("123456"); - //Assert.IsTrue(v); - //v = await service.ValidateAdminPassword("1234561"); - //Assert.IsFalse(v); + return dict; } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/SysLogServiceTests.cs index 88eea163..9f4398e3 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/SysLogServiceTests.cs @@ -1,192 +1,22 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; using System.Collections.Generic; -using System.Text; -using AgileConfig.Server.Data.Freesql; -using FreeSql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.Data.Repository.Freesql; -using AgileConfig.Server.IService; -using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.Service.Tests.sqlserver { [TestClass()] - public class SysLogServiceTests + public class SysLogServiceTests_sqlserver : SysLogServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - ISysLogService service = null; + string conn = "TrustServerCertificate=True;Persist Security Info = False; User ID =dev; Password =dev; Initial Catalog =agile_config_test; Server =."; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Persist Security Info = False; User ID =dev; Password =dev@123,; Initial Catalog =agile_config_test; Server =www..com"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.SqlServer, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "sqlserver"; + dict["db:conn"] = conn; - IServiceCollection services = new ServiceCollection(); - services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); - services.AddBusinessServices(); - - - var serviceProvider = services.BuildServiceProvider(); - service = serviceProvider.GetService(); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - [TestMethod()] - public async Task AddSysLogAsyncTest() - { - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - - var result = await service.AddSysLogAsync(source); - Assert.IsTrue(result); - - var log = fsq.Select(new { - Id = source.Id - }).ToOne(); - - Assert.IsNotNull(log); - - Assert.AreEqual(source.Id, log.Id); - Assert.AreEqual(source.AppId, log.AppId); - Assert.AreEqual(source.LogType, log.LogType); - // Assert.AreEqual(source.LogTime, log.LogTime); - Assert.AreEqual(source.LogText, log.LogText); - } - - - [TestMethod()] - public async Task AddRangeAsyncTest() - { - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List { - source, source1 - }); - Assert.IsTrue(result); - - var log = fsq.Select(new - { - Id = source.Id - }).ToOne(); - Assert.IsNotNull(log); - Assert.AreEqual(source.Id, log.Id); - Assert.AreEqual(source.AppId, log.AppId); - Assert.AreEqual(source.LogType, log.LogType); - // Assert.AreEqual(source.LogTime, log.LogTime); - Assert.AreEqual(source.LogText, log.LogText); - - var log1 = fsq.Select(new - { - Id = source1.Id - }).ToOne(); - Assert.IsNotNull(log1); - Assert.AreEqual(source1.Id, log1.Id); - Assert.AreEqual(source1.AppId, log1.AppId); - Assert.AreEqual(source1.LogType, log1.LogType); - // Assert.AreEqual(source1.LogTime, log1.LogTime); - Assert.AreEqual(source1.LogText, log1.LogText); - } - - - [TestMethod()] - public async Task CountTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List { - source, source1 - }); - Assert.IsTrue(result); - - var count = await service.Count("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1)); - Assert.AreEqual(1, count); - - var count1 = await service.Count("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1)); - Assert.AreEqual(0, count1); - } - - [TestMethod()] - public async Task SearchPageTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List { - source, source1 - }); - Assert.IsTrue(result); - - var page = await service.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1),1,0); - Assert.AreEqual(1, page.Count); - - var page1 = await service.SearchPage("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), 1, 0); - Assert.AreEqual(0, page1.Count); + return dict; } } } \ No newline at end of file From be8b09924ae32fff36f8ddcb37c925ec104cc893 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 21 Jan 2024 16:09:17 +0800 Subject: [PATCH 38/45] Fix ConfigServer test cases on sqlite --- .../ConfigService.cs | 4 +- .../sqlite/AppServiceTests.cs | 10 - .../sqlite/ConfigServiceTests.cs | 312 ++++++++++-------- 3 files changed, 175 insertions(+), 151 deletions(-) diff --git a/src/AgileConfig.Server.Service/ConfigService.cs b/src/AgileConfig.Server.Service/ConfigService.cs index f5342d78..5fe86e0d 100644 --- a/src/AgileConfig.Server.Service/ConfigService.cs +++ b/src/AgileConfig.Server.Service/ConfigService.cs @@ -505,8 +505,8 @@ public void Dispose() publishTimelineNode.AppId = appId; publishTimelineNode.Id = Guid.NewGuid().ToString("N"); publishTimelineNode.PublishTime = DateTime.Now; - publishTimelineNode.PublishUserId = user.Id; - publishTimelineNode.PublishUserName = user.UserName; + publishTimelineNode.PublishUserId = user?.Id; + publishTimelineNode.PublishUserName = user?.UserName; publishTimelineNode.Version = versionMax + 1; publishTimelineNode.Log = log; publishTimelineNode.Env = env; diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs index a02685d5..19660930 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs @@ -1,21 +1,11 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; using AgileConfig.Server.IService; using AgileConfig.Server.Service; -using Microsoft.Extensions.Caching.Memory; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Moq; -using AgileConfig.Server.Data.Abstraction; -using AgileConfig.Server.Data.Repository.Freesql; -using AgileConfig.Server.Common; -using MongoDB.Driver.Linq; namespace AgileConfig.Server.ServiceTests.sqlite { diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs index 197a0536..3af527f5 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs @@ -1,56 +1,40 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; using System; using System.Collections.Generic; -using System.Text; using FreeSql; using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.Data.Entity; using System.Threading.Tasks; using AgileConfig.Server.IService; -using System.Runtime.CompilerServices; using Microsoft.Extensions.Caching.Memory; using Moq; +using AgileConfig.Server.ServiceTests.sqlite; +using Microsoft.Extensions.DependencyInjection; namespace AgileConfig.Server.Service.Tests { [TestClass()] - public class ConfigServiceTests + public class ConfigServiceTests : BasicTestService { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IConfigService service = null; + IConfigService _service = null; + public override Dictionary GetConfigurationData() + { + return + new Dictionary + { + {"db:provider","sqlite" }, + {"db:conn","Data Source=agile_config.db" } + }; + } [TestInitialize] public void TestInitialize() { - string conn = "Data Source=agile_config.db"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, conn) - .UseAutoSyncStructure(true) - .Build(); - freeSqlContext = new FreeSqlContext(fsq); - - var cache = new Mock(); - var config = new Config(); - - // todo - - //service = new ConfigService(cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); + _service = _serviceProvider.GetService(); + _fsq.Delete().Where("1=1"); } - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - [TestMethod()] public async Task AddAsyncTest() { @@ -69,9 +53,9 @@ public async Task AddAsyncTest() OnlineStatus = OnlineStatus.Online }; - var result = await service.AddAsync(source, ""); + var result = await _service.AddAsync(source, ""); Assert.IsTrue(result); - var config = fsq.Select(new + var config = _fsq.Select(new { Id = id }).ToOne(); @@ -109,7 +93,7 @@ public async Task UpdateAsyncTest() OnlineStatus = OnlineStatus.Online }; - var result = await service.AddAsync(source, ""); + var result = await _service.AddAsync(source, ""); Assert.IsTrue(result); source.AppId = "1"; @@ -122,8 +106,8 @@ public async Task UpdateAsyncTest() source.Status = ConfigStatus.Enabled; source.OnlineStatus = OnlineStatus.WaitPublish; - var result1 = await service.UpdateAsync(source, ""); - var config = fsq.Select(new + var result1 = await _service.UpdateAsync(source, ""); + var config = _fsq.Select(new { Id = id }).ToOne(); @@ -161,13 +145,13 @@ public async Task DeleteAsyncTest() OnlineStatus = OnlineStatus.Online }; - var result = await service.AddAsync(source, ""); + var result = await _service.AddAsync(source, ""); Assert.IsTrue(result); - var result1 = await service.DeleteAsync(source, ""); + var result1 = await _service.DeleteAsync(source, ""); Assert.IsTrue(result1); - var config = fsq.Select(new + var config = _fsq.Select(new { Id = id }).ToOne(); @@ -193,13 +177,13 @@ public async Task DeleteAsyncTest1() OnlineStatus = OnlineStatus.Online }; - var result = await service.AddAsync(source, ""); + var result = await _service.AddAsync(source, ""); Assert.IsTrue(result); - var result1 = await service.DeleteAsync(id, ""); + var result1 = await _service.DeleteAsync(id, ""); Assert.IsTrue(result1); - var config = fsq.Select(new + var config = _fsq.Select(new { Id = id }).ToOne(); @@ -225,10 +209,10 @@ public async Task GetAsyncTest() OnlineStatus = OnlineStatus.Online }; - var result = await service.AddAsync(source, ""); + var result = await _service.AddAsync(source, ""); Assert.IsTrue(result); - var config = await service.GetAsync(id, ""); + var config = await _service.GetAsync(id, ""); Assert.IsNotNull(config); Assert.AreEqual(source.Id, config.Id); @@ -246,8 +230,9 @@ public async Task GetAsyncTest() [TestMethod()] public async Task GetAllConfigsAsyncTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); + var env = "DEV"; var id = Guid.NewGuid().ToString(); var source = new Config { @@ -260,7 +245,8 @@ public async Task GetAllConfigsAsyncTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; var id1 = Guid.NewGuid().ToString(); var source1 = new Config @@ -274,14 +260,15 @@ public async Task GetAllConfigsAsyncTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; - var result = await service.AddAsync(source, ""); + var result = await _service.AddAsync(source, env); Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); + var result1 = await _service.AddAsync(source1, env); Assert.IsTrue(result1); - var configs = await service.GetAllConfigsAsync(""); + var configs = await _service.GetAllConfigsAsync(env); Assert.IsNotNull(configs); Assert.AreEqual(1, configs.Count); } @@ -289,8 +276,8 @@ public async Task GetAllConfigsAsyncTest() [TestMethod()] public async Task GetByAppIdKeyTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); - + _fsq.Delete().Where("1=1").ExecuteAffrows(); + var env = "DEV"; var id = Guid.NewGuid().ToString(); var source = new Config { @@ -303,7 +290,8 @@ public async Task GetByAppIdKeyTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; var id1 = Guid.NewGuid().ToString(); var source1 = new Config @@ -317,7 +305,8 @@ public async Task GetByAppIdKeyTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; var id2 = Guid.NewGuid().ToString(); var source2 = new Config @@ -331,28 +320,30 @@ public async Task GetByAppIdKeyTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; - var result = await service.AddAsync(source, ""); + var result = await _service.AddAsync(source, env); Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); + var result1 = await _service.AddAsync(source1, env); Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); + var result2 = await _service.AddAsync(source2, env); Assert.IsTrue(result2); - var config = await service.GetByAppIdKeyEnv("001", "g", "k", "env"); + var config = await _service.GetByAppIdKeyEnv("001", "g", "k", env); Assert.IsNotNull(config); - var config1 = await service.GetByAppIdKeyEnv("002", "g", "k", "env"); + var config1 = await _service.GetByAppIdKeyEnv("002", "g", "k", env); Assert.IsNull(config1); } [TestMethod()] public async Task GetByAppIdTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var id = Guid.NewGuid().ToString(); + var env = "DEV"; var source = new Config { AppId = "001", @@ -364,7 +355,8 @@ public async Task GetByAppIdTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; var id1 = Guid.NewGuid().ToString(); var source1 = new Config @@ -378,7 +370,8 @@ public async Task GetByAppIdTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; var id2 = Guid.NewGuid().ToString(); var source2 = new Config @@ -392,16 +385,17 @@ public async Task GetByAppIdTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; - var result = await service.AddAsync(source, ""); + var result = await _service.AddAsync(source, env); Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); + var result1 = await _service.AddAsync(source1, env); Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); + var result2 = await _service.AddAsync(source2, env); Assert.IsTrue(result2); - var configs = await service.GetByAppIdAsync("001", ""); + var configs = await _service.GetByAppIdAsync("001", env); Assert.IsNotNull(configs); Assert.AreEqual(1, configs.Count); } @@ -409,8 +403,8 @@ public async Task GetByAppIdTest() [TestMethod()] public async Task SearchTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); - + _fsq.Delete().Where("1=1").ExecuteAffrows(); + var env = "DEV"; var id = Guid.NewGuid().ToString(); var source = new Config { @@ -423,7 +417,8 @@ public async Task SearchTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; var id1 = Guid.NewGuid().ToString(); var source1 = new Config @@ -437,7 +432,8 @@ public async Task SearchTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online + Env = env, + OnlineStatus = OnlineStatus.Online, }; var id2 = Guid.NewGuid().ToString(); var source2 = new Config @@ -451,22 +447,23 @@ public async Task SearchTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env, }; - var result = await service.AddAsync(source, ""); + var result = await _service.AddAsync(source, env); Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); + var result1 = await _service.AddAsync(source1, env); Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); + var result2 = await _service.AddAsync(source2, env); Assert.IsTrue(result2); - var configs = await service.Search("001", "", "", ""); + var configs = await _service.Search("001", "", "", env); Assert.IsNotNull(configs); Assert.AreEqual(1, configs.Count); - var configs1 = await service.Search("", "o", "", ""); + var configs1 = await _service.Search("", "o", "", env); Assert.IsNotNull(configs1); Assert.AreEqual(1, configs1.Count); - var configs2 = await service.Search("", "", "e", ""); + var configs2 = await _service.Search("", "", "e", env); Assert.IsNotNull(configs2); Assert.AreEqual(1, configs2.Count); } @@ -474,8 +471,9 @@ public async Task SearchTest() [TestMethod()] public async Task CountEnabledConfigsAsyncTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); + string env = "DEV"; var id = Guid.NewGuid().ToString(); var source = new Config { @@ -488,7 +486,8 @@ public async Task CountEnabledConfigsAsyncTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; var id1 = Guid.NewGuid().ToString(); var source1 = new Config @@ -502,7 +501,8 @@ public async Task CountEnabledConfigsAsyncTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; var id2 = Guid.NewGuid().ToString(); var source2 = new Config @@ -516,23 +516,24 @@ public async Task CountEnabledConfigsAsyncTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; - var result = await service.AddAsync(source, ""); + var result = await _service.AddAsync(source, ""); Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); + var result1 = await _service.AddAsync(source1, ""); Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); + var result2 = await _service.AddAsync(source2, ""); Assert.IsTrue(result2); - var count = await service.CountEnabledConfigsAsync(); + var count = await _service.CountEnabledConfigsAsync(); Assert.AreEqual(1, count); } [TestMethod()] public async Task AppPublishedConfigsMd5Test() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var id = Guid.NewGuid().ToString(); var source = new Config @@ -576,14 +577,14 @@ public async Task AppPublishedConfigsMd5Test() Status = ConfigStatus.Deleted, OnlineStatus = OnlineStatus.Online }; - var result = await service.AddAsync(source, ""); + var result = await _service.AddAsync(source, ""); Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); + var result1 = await _service.AddAsync(source1, ""); Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); + var result2 = await _service.AddAsync(source2, ""); Assert.IsTrue(result2); - var md5 = await service.AppPublishedConfigsMd5("001", ""); + var md5 = await _service.AppPublishedConfigsMd5("001", ""); Assert.IsNotNull(md5); } @@ -595,7 +596,7 @@ public void AppPublishedConfigsMd5CacheTest() [TestMethod()] public async Task GetPublishedConfigsByAppIdTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); var id = Guid.NewGuid().ToString(); var source = new Config @@ -639,11 +640,11 @@ public async Task GetPublishedConfigsByAppIdTest() Status = ConfigStatus.Deleted, OnlineStatus = OnlineStatus.Online }; - var result = await service.AddAsync(source, ""); + var result = await _service.AddAsync(source, ""); Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); + var result1 = await _service.AddAsync(source1, ""); Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); + var result2 = await _service.AddAsync(source2, ""); Assert.IsTrue(result2); //var configs = await service.GetPublishedConfigsByAppId("001"); @@ -682,19 +683,19 @@ public async Task AddRangeAsyncTest() Status = ConfigStatus.Deleted, OnlineStatus = OnlineStatus.Online }; - - var result = await service.AddRangeAsync(new List { + + var result = await _service.AddRangeAsync(new List { source, source1 }, ""); Assert.IsTrue(result); - var config = fsq.Select(new + var config = _fsq.Select(new { Id = id }).ToOne(); Assert.IsNotNull(config); - var config1 = fsq.Select(new + var config1 = _fsq.Select(new { Id = id1 }).ToOne(); @@ -704,9 +705,14 @@ public async Task AddRangeAsyncTest() [TestMethod()] public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() { - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); + _fsq.Delete().Where("1=1").ExecuteAffrows(); + + string env = "DEV"; var app = new App(); app.Id = "001"; @@ -714,14 +720,15 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() app.Enabled = true; app.CreateTime = DateTime.Now; app.UpdateTime = DateTime.Now; - app.Type = AppType.PRIVATE; + app.Type = AppType.PRIVATE; // app 001 私有 var app1 = new App(); app1.Id = "002"; - app1.Name = "x"; + app1.Name = "x2"; app1.Enabled = true; app1.CreateTime = DateTime.Now; app1.UpdateTime = DateTime.Now; - app.Type = AppType.Inheritance; + app1.Type = AppType.Inheritance; // APP 002 公开 + var id = Guid.NewGuid().ToString(); var source = new Config { @@ -733,7 +740,8 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.WaitPublish, + Env = env }; var id1 = Guid.NewGuid().ToString(); var source1 = new Config @@ -746,7 +754,8 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.WaitPublish, + Env = env }; var source2 = new Config { @@ -758,7 +767,8 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.WaitPublish, + Env = env }; var source3 = new Config { @@ -770,23 +780,29 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.WaitPublish, + Env = env }; var appref = new AppInheritanced(); appref.AppId = app.Id; - appref.InheritancedAppId = app1.Id; + appref.InheritancedAppId = app1.Id; // app 001 继承 app 002 appref.Sort = 1; appref.Id = Guid.NewGuid().ToString(); - fsq.Insert(app).ExecuteAffrows(); - fsq.Insert(app1).ExecuteAffrows(); - fsq.Insert(source).ExecuteAffrows(); - fsq.Insert(source1).ExecuteAffrows(); - fsq.Insert(source2).ExecuteAffrows(); - fsq.Insert(source3).ExecuteAffrows(); - fsq.Insert(appref).ExecuteAffrows(); + _fsq.Insert(app).ExecuteAffrows(); + _fsq.Insert(app1).ExecuteAffrows(); + _fsq.Insert(appref).ExecuteAffrows(); + + // 插入4个config,2个app 001,2个app 002 + _fsq.Insert(source).ExecuteAffrows(); + _fsq.Insert(source1).ExecuteAffrows(); + _fsq.Insert(source2).ExecuteAffrows(); + _fsq.Insert(source3).ExecuteAffrows(); + + await _service.Publish(app1.Id, new string[] { }, "", "", env); + await _service.Publish(app.Id, new string[] { },"", "", env); - var dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); + var dict = await _service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, env); Assert.IsNotNull(dict); Assert.AreEqual(4, dict.Keys.Count); @@ -810,7 +826,8 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.WaitPublish, + Env = env }; var source5 = new Config { @@ -822,12 +839,17 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.WaitPublish, + Env = env }; - fsq.Insert(source4).ExecuteAffrows(); - fsq.Insert(source5).ExecuteAffrows(); + // 插入2个config,1个app 001,1个app 002,keyvalue相同,app 001 优先级高 + _fsq.Insert(source4).ExecuteAffrows(); + _fsq.Insert(source5).ExecuteAffrows(); - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); + await _service.Publish(app1.Id, new string[] { }, "", "", env); + await _service.Publish(app.Id, new string[] { }, "", "", env); + + dict = await _service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, env); Assert.IsNotNull(dict); Assert.AreEqual(5, dict.Keys.Count); @@ -841,7 +863,18 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() app2.CreateTime = DateTime.Now; app2.UpdateTime = DateTime.Now; app2.Type = AppType.Inheritance; - fsq.Insert(app2).ExecuteAffrows(); + _fsq.Insert(app2).ExecuteAffrows(); + + + // 插入1个app 003 + _fsq.Delete().Where("1=1").ExecuteAffrows(); + var appref1 = new AppInheritanced(); + appref1.AppId = app.Id; + appref1.InheritancedAppId = app2.Id; // app 001 继承 app 003 + appref1.Sort = 2; + appref1.Id = Guid.NewGuid().ToString(); + _fsq.Insert(appref1).ExecuteAffrows(); + var source6 = new Config { AppId = "003", @@ -852,24 +885,25 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.WaitPublish, + Env = env }; - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Insert(source6).ExecuteAffrows(); + _fsq.Insert(source6).ExecuteAffrows(); + await _service.Publish(app2.Id, new string[] { }, "", "", env); // 发布app 003 - fsq.Insert(appref).ExecuteAffrows(); - var appref1 = new AppInheritanced(); - appref1.AppId = app.Id; - appref1.InheritancedAppId = app2.Id; - appref1.Sort = 2; - appref1.Id = Guid.NewGuid().ToString(); - fsq.Insert(appref1).ExecuteAffrows(); - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); + dict = await _service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, env); Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); + Assert.AreEqual(4, dict.Keys.Count); - config1 = dict["k2"]; - Assert.AreEqual(source6.Value, config1.Value); + Assert.IsTrue(dict.ContainsKey(source6.Key)); + Assert.IsTrue(dict.ContainsKey(source4.Key)); + Assert.IsTrue(dict.ContainsKey(source1.Key)); + Assert.IsTrue(dict.ContainsKey(source.Key)); + + Assert.IsTrue(dict[source6.Key].Value == "k4444"); + Assert.IsTrue(dict[source4.Key].Value == "v3"); + Assert.IsTrue(dict[source1.Key].Value == "v1"); + Assert.IsTrue(dict[source.Key].Value == "v"); } } } \ No newline at end of file From 43b1a7d93f1d7e7e8ac2982beaf1efdad7e72878 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 21 Jan 2024 17:26:30 +0800 Subject: [PATCH 39/45] Update ConfigService test cases for sqlserver --- .../sqlite/ConfigServiceTests.cs | 12 +- .../sqlserver/ConfigServiceTests.cs | 869 +----------------- 2 files changed, 13 insertions(+), 868 deletions(-) diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs index 3af527f5..101ae751 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs @@ -69,8 +69,8 @@ public async Task AddAsyncTest() Assert.AreEqual(source.Value, config.Value); Assert.AreEqual(source.Description, config.Description); Assert.AreEqual(source.AppId, config.AppId); - Assert.AreEqual(source.CreateTime, config.CreateTime); - Assert.AreEqual(source.UpdateTime, config.UpdateTime); + Assert.AreEqual(source.CreateTime.ToString("yyyyMMddHHmmss"), config.CreateTime.ToString("yyyyMMddHHmmss")); + Assert.AreEqual(source.UpdateTime.Value.ToString("yyyyMMddHHmmss"), config.UpdateTime.Value.ToString("yyyyMMddHHmmss")); Assert.AreEqual(source.Status, config.Status); Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); } @@ -121,8 +121,8 @@ public async Task UpdateAsyncTest() Assert.AreEqual(source.Value, config.Value); Assert.AreEqual(source.Description, config.Description); Assert.AreEqual(source.AppId, config.AppId); - Assert.AreEqual(source.CreateTime, config.CreateTime); - Assert.AreEqual(source.UpdateTime, config.UpdateTime); + Assert.AreEqual(source.CreateTime.ToString("yyyyMMddHHmmss"), config.CreateTime.ToString("yyyyMMddHHmmss")); + Assert.AreEqual(source.UpdateTime.Value.ToString("yyyyMMddHHmmss"), config.UpdateTime.Value.ToString("yyyyMMddHHmmss")); Assert.AreEqual(source.Status, config.Status); Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); } @@ -221,8 +221,8 @@ public async Task GetAsyncTest() Assert.AreEqual(source.Value, config.Value); Assert.AreEqual(source.Description, config.Description); Assert.AreEqual(source.AppId, config.AppId); - Assert.AreEqual(source.CreateTime, config.CreateTime); - Assert.AreEqual(source.UpdateTime, config.UpdateTime); + Assert.AreEqual(source.CreateTime.ToString("yyyyMMddHHmmss"), config.CreateTime.ToString("yyyyMMddHHmmss")); + Assert.AreEqual(source.UpdateTime.Value.ToString("yyyyMMddHHmmss"), config.UpdateTime.Value.ToString("yyyyMMddHHmmss")); Assert.AreEqual(source.Status, config.Status); Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); } diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/ConfigServiceTests.cs index b6d1b9ae..1cf58732 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/ConfigServiceTests.cs @@ -1,875 +1,20 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.IService; -using System.Runtime.CompilerServices; -using Microsoft.Extensions.Caching.Memory; -using Moq; namespace AgileConfig.Server.Service.Tests.sqlserver { [TestClass()] - public class ConfigServiceTests + public class ConfigServiceTests_sqlserver: ConfigServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IConfigService service = null; + string conn = "TrustServerCertificate=True;Persist Security Info = False; User ID =dev; Password =dev; Initial Catalog =agile_config_test; Server =."; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Persist Security Info = False; User ID =dev; Password =dev@123,; Initial Catalog =agile_config_test; Server =www..com"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.SqlServer, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "sqlserver"; + dict["db:conn"] = conn; - var cache = new Mock(); - var config = new Config(); - - // todo - //service = new ConfigService( cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsTrue(result); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - // Assert.AreEqual(source.CreateTime, config.CreateTime); - // Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - source.AppId = "1"; - source.Group = "1"; - source.Key = "1"; - source.Value = "1"; - source.Description = "1"; - source.CreateTime = DateTime.Now; - source.UpdateTime = DateTime.Now; - source.Status = ConfigStatus.Enabled; - source.OnlineStatus = OnlineStatus.WaitPublish; - - var result1 = await service.UpdateAsync(source, ""); - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsTrue(result1); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - // Assert.AreEqual(source.CreateTime, config.CreateTime); - // Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source, ""); - Assert.IsTrue(result1); - - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(config); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(id, ""); - Assert.IsTrue(result1); - - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(config); - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var config = await service.GetAsync(id, ""); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - // Assert.AreEqual(source.CreateTime, config.CreateTime); - // Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task GetAllConfigsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - - var configs = await service.GetAllConfigsAsync(""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task GetByAppIdKeyTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var config = await service.GetByAppIdKeyEnv("001", "g", "k", ""); - Assert.IsNotNull(config); - - var config1 = await service.GetByAppIdKeyEnv("002", "g", "k", ""); - Assert.IsNull(config1); - } - - [TestMethod()] - public async Task GetByAppIdTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var configs = await service.GetByAppIdAsync("001", ""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task SearchTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, "" ); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var configs = await service.Search("001", "", "", ""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - var configs1 = await service.Search("", "o", "", ""); - Assert.IsNotNull(configs1); - Assert.AreEqual(1, configs1.Count); - var configs2 = await service.Search("", "", "e", ""); - Assert.IsNotNull(configs2); - Assert.AreEqual(1, configs2.Count); - } - - [TestMethod()] - public async Task CountEnabledConfigsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var count = await service.CountEnabledConfigsAsync(); - Assert.AreEqual(1, count); - } - - [TestMethod()] - public async Task AppPublishedConfigsMd5Test() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var md5 = await service.AppPublishedConfigsMd5("001", ""); - Assert.IsNotNull(md5); - } - - [TestMethod()] - public void AppPublishedConfigsMd5CacheTest() - { - } - - [TestMethod()] - public async Task GetPublishedConfigsByAppIdTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - //var configs = await service.GetPublishedConfigsByAppId("001"); - //Assert.IsNotNull(configs); - //Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task AddRangeAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddRangeAsync(new List { - source, - source1 - }, ""); - Assert.IsTrue(result); - - var config = fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNotNull(config); - var config1 = fsq.Select(new - { - Id = id1 - }).ToOne(); - Assert.IsNotNull(config1); - } - - [TestMethod()] - public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var app = new App(); - app.Id = "001"; - app.Name = "x"; - app.Enabled = true; - app.CreateTime = DateTime.Now; - app.UpdateTime = DateTime.Now; - app.Type = AppType.PRIVATE; - var app1 = new App(); - app1.Id = "002"; - app1.Name = "x"; - app1.Enabled = true; - app1.CreateTime = DateTime.Now; - app1.UpdateTime = DateTime.Now; - app.Type = AppType.Inheritance; - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Key = "k1", - Value = "v1", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source2 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k2", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source3 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k21", - Value = "v2", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var appref = new AppInheritanced(); - appref.AppId = app.Id; - appref.InheritancedAppId = app1.Id; - appref.Sort = 1; - appref.Id = Guid.NewGuid().ToString(); - - fsq.Insert(app).ExecuteAffrows(); - fsq.Insert(app1).ExecuteAffrows(); - fsq.Insert(source).ExecuteAffrows(); - fsq.Insert(source1).ExecuteAffrows(); - fsq.Insert(source2).ExecuteAffrows(); - fsq.Insert(source3).ExecuteAffrows(); - fsq.Insert(appref).ExecuteAffrows(); - - var dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(4, dict.Keys.Count); - - Assert.IsTrue(dict.ContainsKey(source.Key)); - Assert.IsTrue(dict.ContainsKey(source1.Key)); - Assert.IsTrue(dict.ContainsKey(source2.Key)); - Assert.IsTrue(dict.ContainsKey(source3.Key)); - - Assert.IsTrue(dict[source.Key].Value == "v"); - Assert.IsTrue(dict[source1.Key].Value == "v1"); - Assert.IsTrue(dict[source2.Key].Value == "v"); - Assert.IsTrue(dict[source3.Key].Value == "v2"); - - var source4 = new Config - { - AppId = "001", - Id = Guid.NewGuid().ToString(), - Key = "k4", - Value = "v3", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source5 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k4", - Value = "v2", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - fsq.Insert(source4).ExecuteAffrows(); - fsq.Insert(source5).ExecuteAffrows(); - - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); - - var config1 = dict["k4"]; - Assert.AreEqual(source4.Value, config1.Value); - - var app2 = new App(); - app2.Id = "003"; - app2.Name = "x"; - app2.Enabled = true; - app2.CreateTime = DateTime.Now; - app2.UpdateTime = DateTime.Now; - app2.Type = AppType.Inheritance; - fsq.Insert(app2).ExecuteAffrows(); - var source6 = new Config - { - AppId = "003", - Id = Guid.NewGuid().ToString(), - Key = "k2", - Value = "k4444", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Insert(source6).ExecuteAffrows(); - - fsq.Insert(appref).ExecuteAffrows(); - var appref1 = new AppInheritanced(); - appref1.AppId = app.Id; - appref1.InheritancedAppId = app2.Id; - appref1.Sort = 2; - appref1.Id = Guid.NewGuid().ToString(); - fsq.Insert(appref1).ExecuteAffrows(); - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); - - config1 = dict["k2"]; - Assert.AreEqual(source6.Value, config1.Value); + return dict; } } } \ No newline at end of file From bf894db3e81deae374354696ad6b5c82562f07e3 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 21 Jan 2024 17:30:52 +0800 Subject: [PATCH 40/45] update configservice test cases for mysql --- .../PostgreSQL/ConfigServiceTests.cs | 869 +----------------- .../mysql/AppServiceTests.cs | 2 +- .../mysql/ConfigServiceTests.cs | 857 +---------------- .../mysql/ServerNodeServiceTests.cs | 2 +- .../mysql/SettingServiceTests.cs | 2 +- .../mysql/SysLogServiceTests.cs | 2 +- 6 files changed, 20 insertions(+), 1714 deletions(-) diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ConfigServiceTests.cs index 0452465f..8890ce7b 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ConfigServiceTests.cs @@ -1,875 +1,20 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.IService; -using System.Runtime.CompilerServices; -using Microsoft.Extensions.Caching.Memory; -using Moq; namespace AgileConfig.Server.Service.Tests.PostgreSQL { [TestClass()] - public class ConfigServiceTests + public class ConfigServiceTests_pg: ConfigServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IConfigService service = null; + string conn = "Host=192.168.0.125;Port=15432;Database=agileconfig;Username=postgres;Password=123456"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Host=127.0.0.1;Database=agile_config;Username=postgres;Password=dev@123"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.PostgreSQL, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "npgsql"; + dict["db:conn"] = conn; - var cache = new Mock(); - var config = new Config(); - - // todo - - //service = new ConfigService( cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsTrue(result); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - // Assert.AreEqual(source.CreateTime, config.CreateTime); - // Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - source.AppId = "1"; - source.Group = "1"; - source.Key = "1"; - source.Value = "1"; - source.Description = "1"; - source.CreateTime = DateTime.Now; - source.UpdateTime = DateTime.Now; - source.Status = ConfigStatus.Enabled; - source.OnlineStatus = OnlineStatus.WaitPublish; - - var result1 = await service.UpdateAsync(source, ""); - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsTrue(result1); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - // Assert.AreEqual(source.CreateTime, config.CreateTime); - // Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source, ""); - Assert.IsTrue(result1); - - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(config); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(id, ""); - Assert.IsTrue(result1); - - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(config); - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var config = await service.GetAsync(id, ""); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - // Assert.AreEqual(source.CreateTime, config.CreateTime); - // Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task GetAllConfigsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - - var configs = await service.GetAllConfigsAsync(""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task GetByAppIdKeyTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var config = await service.GetByAppIdKeyEnv("001", "g", "k", "env"); - Assert.IsNotNull(config); - - var config1 = await service.GetByAppIdKeyEnv("002", "g", "k", "env"); - Assert.IsNull(config1); - } - - [TestMethod()] - public async Task GetByAppIdTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var configs = await service.GetByAppIdAsync("001", ""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task SearchTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var configs = await service.Search("001", "", "", ""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - var configs1 = await service.Search("", "o", "", ""); - Assert.IsNotNull(configs1); - Assert.AreEqual(1, configs1.Count); - var configs2 = await service.Search("", "", "e", ""); - Assert.IsNotNull(configs2); - Assert.AreEqual(1, configs2.Count); - } - - [TestMethod()] - public async Task CountEnabledConfigsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var count = await service.CountEnabledConfigsAsync(); - Assert.AreEqual(1, count); - } - - [TestMethod()] - public async Task AppPublishedConfigsMd5Test() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var md5 = await service.AppPublishedConfigsMd5("001", ""); - Assert.IsNotNull(md5); - } - - [TestMethod()] - public void AppPublishedConfigsMd5CacheTest() - { - } - - [TestMethod()] - public async Task GetPublishedConfigsByAppIdTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - //var configs = await service.GetPublishedConfigsByAppId("001"); - //Assert.IsNotNull(configs); - //Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task AddRangeAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddRangeAsync(new List { - source, - source1 - }, ""); - Assert.IsTrue(result); - - var config = fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNotNull(config); - var config1 = fsq.Select(new - { - Id = id1 - }).ToOne(); - Assert.IsNotNull(config1); - } - [TestMethod()] - public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var app = new App(); - app.Id = "001"; - app.Name = "x"; - app.Enabled = true; - app.CreateTime = DateTime.Now; - app.UpdateTime = DateTime.Now; - app.Type = AppType.PRIVATE; - var app1 = new App(); - app1.Id = "002"; - app1.Name = "x"; - app1.Enabled = true; - app1.CreateTime = DateTime.Now; - app1.UpdateTime = DateTime.Now; - app.Type = AppType.Inheritance; - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Key = "k1", - Value = "v1", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source2 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k2", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source3 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k21", - Value = "v2", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var appref = new AppInheritanced(); - appref.AppId = app.Id; - appref.InheritancedAppId = app1.Id; - appref.Sort = 1; - appref.Id = Guid.NewGuid().ToString(); - - fsq.Insert(app).ExecuteAffrows(); - fsq.Insert(app1).ExecuteAffrows(); - fsq.Insert(source).ExecuteAffrows(); - fsq.Insert(source1).ExecuteAffrows(); - fsq.Insert(source2).ExecuteAffrows(); - fsq.Insert(source3).ExecuteAffrows(); - fsq.Insert(appref).ExecuteAffrows(); - - var dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id,""); - Assert.IsNotNull(dict); - Assert.AreEqual(4, dict.Keys.Count); - - Assert.IsTrue(dict.ContainsKey(source.Key)); - Assert.IsTrue(dict.ContainsKey(source1.Key)); - Assert.IsTrue(dict.ContainsKey(source2.Key)); - Assert.IsTrue(dict.ContainsKey(source3.Key)); - - Assert.IsTrue(dict[source.Key].Value == "v"); - Assert.IsTrue(dict[source1.Key].Value == "v1"); - Assert.IsTrue(dict[source2.Key].Value == "v"); - Assert.IsTrue(dict[source3.Key].Value == "v2"); - - var source4 = new Config - { - AppId = "001", - Id = Guid.NewGuid().ToString(), - Key = "k4", - Value = "v3", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source5 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k4", - Value = "v2", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - fsq.Insert(source4).ExecuteAffrows(); - fsq.Insert(source5).ExecuteAffrows(); - - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); - - var config1 = dict["k4"]; - Assert.AreEqual(source4.Value, config1.Value); - - var app2 = new App(); - app2.Id = "003"; - app2.Name = "x"; - app2.Enabled = true; - app2.CreateTime = DateTime.Now; - app2.UpdateTime = DateTime.Now; - app2.Type = AppType.Inheritance; - fsq.Insert(app2).ExecuteAffrows(); - var source6 = new Config - { - AppId = "003", - Id = Guid.NewGuid().ToString(), - Key = "k2", - Value = "k4444", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Insert(source6).ExecuteAffrows(); - - fsq.Insert(appref).ExecuteAffrows(); - var appref1 = new AppInheritanced(); - appref1.AppId = app.Id; - appref1.InheritancedAppId = app2.Id; - appref1.Sort = 2; - appref1.Id = Guid.NewGuid().ToString(); - fsq.Insert(appref1).ExecuteAffrows(); - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); - - config1 = dict["k2"]; - Assert.AreEqual(source6.Value, config1.Value); + return dict; } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs index c77cfd76..a85bd693 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/AppServiceTests.cs @@ -7,7 +7,7 @@ namespace AgileConfig.Server.ServiceTests.mysql [TestClass()] public class AppServiceTests_mysql : AppServiceTests { - string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=mimi756310;port=13306"; + string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=x;port=13306"; public override Dictionary GetConfigurationData() { diff --git a/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs index cf6b8dd7..382ab957 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs @@ -1,5 +1,4 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; using System; using System.Collections.Generic; using System.Text; @@ -11,860 +10,22 @@ using System.Runtime.CompilerServices; using Microsoft.Extensions.Caching.Memory; using Moq; +using AgileConfig.Server.Service.Tests; -namespace AgileConfig.Server.Service.Tests.mysql +namespace AgileConfig.Server.ServiceTests.mysql { [TestClass()] - public class ConfigServiceTests + public class ConfigServiceTests_mysql : ConfigServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IConfigService service = null; + string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=x;port=13306"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "Database=agile_config_test;Data Source=localhost;User Id=root;Password=dev@123;port=3306"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.MySql, conn) - .UseAutoSyncStructure(true) - .Build(); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "mysql"; + dict["db:conn"] = conn; - var cache = new Mock(); - var config = new Config(); - - // to do - - //service = new ConfigService(cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsTrue(result); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - // Assert.AreEqual(source.CreateTime, config.CreateTime); - // Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - source.AppId = "1"; - source.Group = "1"; - source.Key = "1"; - source.Value = "1"; - source.Description = "1"; - source.CreateTime = DateTime.Now; - source.UpdateTime = DateTime.Now; - source.Status = ConfigStatus.Enabled; - source.OnlineStatus = OnlineStatus.WaitPublish; - - var result1 = await service.UpdateAsync(source, ""); - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsTrue(result1); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - // Assert.AreEqual(source.CreateTime, config.CreateTime); - // Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source, ""); - Assert.IsTrue(result1); - - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(config); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(id, ""); - Assert.IsTrue(result1); - - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(config); - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var config = await service.GetAsync(id, ""); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - // Assert.AreEqual(source.CreateTime, config.CreateTime); - // Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task GetAllConfigsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - - var configs = await service.GetAllConfigsAsync(""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task GetByAppIdKeyTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var config = await service.GetByAppIdKeyEnv("001", "g", "k", "env"); - Assert.IsNotNull(config); - - var config1 = await service.GetByAppIdKeyEnv("002", "g", "k", "env"); - Assert.IsNull(config1); - } - - [TestMethod()] - public async Task GetByAppIdTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var configs = await service.GetByAppIdAsync("001", ""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task SearchTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var configs = await service.Search("001", "", "", ""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - var configs1 = await service.Search("", "o", "", ""); - Assert.IsNotNull(configs1); - Assert.AreEqual(1, configs1.Count); - var configs2 = await service.Search("", "", "e", ""); - Assert.IsNotNull(configs2); - Assert.AreEqual(1, configs2.Count); - } - - [TestMethod()] - public async Task CountEnabledConfigsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var count = await service.CountEnabledConfigsAsync(); - Assert.AreEqual(1, count); - } - - [TestMethod()] - public async Task AppPublishedConfigsMd5Test() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var md5 = await service.AppPublishedConfigsMd5("001", ""); - Assert.IsNotNull(md5); - } - - [TestMethod()] - public async Task GetPublishedConfigsByAppIdTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - //var configs = await service.GetPublishedConfigsByAppId("001"); - //Assert.IsNotNull(configs); - //Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task AddRangeAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddRangeAsync(new List { - source, - source1 - }, ""); - Assert.IsTrue(result); - - var config = fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNotNull(config); - var config1 = fsq.Select(new - { - Id = id1 - }).ToOne(); - Assert.IsNotNull(config1); - } - - [TestMethod()] - public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var app = new App(); - app.Id = "001"; - app.Name = "x"; - app.Enabled = true; - app.CreateTime = DateTime.Now; - app.UpdateTime = DateTime.Now; - app.Type = AppType.PRIVATE; - var app1 = new App(); - app1.Id = "002"; - app1.Name = "x"; - app1.Enabled = true; - app1.CreateTime = DateTime.Now; - app1.UpdateTime = DateTime.Now; - app.Type = AppType.Inheritance; - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Key = "k1", - Value = "v1", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source2 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k2", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source3 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k21", - Value = "v2", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var appref = new AppInheritanced(); - appref.AppId = app.Id; - appref.InheritancedAppId = app1.Id; - appref.Sort = 1; - appref.Id = Guid.NewGuid().ToString(); - - fsq.Insert(app).ExecuteAffrows(); - fsq.Insert(app1).ExecuteAffrows(); - fsq.Insert(source).ExecuteAffrows(); - fsq.Insert(source1).ExecuteAffrows(); - fsq.Insert(source2).ExecuteAffrows(); - fsq.Insert(source3).ExecuteAffrows(); - fsq.Insert(appref).ExecuteAffrows(); - - var dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(4, dict.Keys.Count); - - Assert.IsTrue(dict.ContainsKey(source.Key)); - Assert.IsTrue(dict.ContainsKey(source1.Key)); - Assert.IsTrue(dict.ContainsKey(source2.Key)); - Assert.IsTrue(dict.ContainsKey(source3.Key)); - - Assert.IsTrue(dict[source.Key].Value == "v"); - Assert.IsTrue(dict[source1.Key].Value == "v1"); - Assert.IsTrue(dict[source2.Key].Value == "v"); - Assert.IsTrue(dict[source3.Key].Value == "v2"); - - var source4 = new Config - { - AppId = "001", - Id = Guid.NewGuid().ToString(), - Key = "k4", - Value = "v3", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source5 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k4", - Value = "v2", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - fsq.Insert(source4).ExecuteAffrows(); - fsq.Insert(source5).ExecuteAffrows(); - - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); - - var config1 = dict["k4"]; - Assert.AreEqual(source4.Value, config1.Value); - - var app2 = new App(); - app2.Id = "003"; - app2.Name = "x"; - app2.Enabled = true; - app2.CreateTime = DateTime.Now; - app2.UpdateTime = DateTime.Now; - app2.Type = AppType.Inheritance; - fsq.Insert(app2).ExecuteAffrows(); - var source6 = new Config - { - AppId = "003", - Id = Guid.NewGuid().ToString(), - Key = "k2", - Value = "k4444", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Insert(source6).ExecuteAffrows(); - - fsq.Insert(appref).ExecuteAffrows(); - var appref1 = new AppInheritanced(); - appref1.AppId = app.Id; - appref1.InheritancedAppId = app2.Id; - appref1.Sort = 2; - appref1.Id = Guid.NewGuid().ToString(); - fsq.Insert(appref1).ExecuteAffrows(); - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); - - config1 = dict["k2"]; - Assert.AreEqual(source6.Value, config1.Value); + return dict; } } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs index 29cb55ac..c71d5410 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/ServerNodeServiceTests.cs @@ -8,7 +8,7 @@ namespace AgileConfig.Server.ServiceTests.mysql [TestClass()] public class ServerNodeServiceTests_mysql : ServerNodeServiceTests { - string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=mimi756310;port=13306"; + string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=x;port=13306"; public override Dictionary GetConfigurationData() { diff --git a/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs index f215257a..5f9a301f 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/SettingServiceTests.cs @@ -7,7 +7,7 @@ namespace AgileConfig.Server.ServiceTests.mysql [TestClass()] public class SettingServiceTests_mysql : SettingServiceTests { - string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=mimi756310;port=13306"; + string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=x;port=13306"; public override Dictionary GetConfigurationData() { diff --git a/test/AgileConfig.Server.ServiceTests/mysql/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/SysLogServiceTests.cs index dd70ec2c..365f5b35 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/SysLogServiceTests.cs @@ -7,7 +7,7 @@ namespace AgileConfig.Server.ServiceTests.mysql [TestClass()] public class SysLogServiceTests_mysql : SysLogServiceTests { - string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=mimi756310;port=13306"; + string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=x;port=13306"; public override Dictionary GetConfigurationData() { From c3f27dff4e9371e848e56686123be88ce56031a6 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 21 Jan 2024 18:01:21 +0800 Subject: [PATCH 41/45] Update ApiController test cases --- .../Controllers/api/ConfigController.cs | 5 +- .../Websocket/IWebsocketCollection.cs | 2 + .../Websocket/WebsocketCollection.cs | 5 + src/AgileConfig.Server.Common/TinyEventBus.cs | 2 +- .../EnsureTablesTests.cs | 4 +- .../mysql/ConfigServiceTests.cs | 10 - .../oracle/ConfigServiceTests.cs | 871 +----------------- test/ApiSiteTests/TestAdminController.cs | 167 ---- test/ApiSiteTests/TestApiConfigController.cs | 142 +-- test/ApiSiteTests/TestAppController.cs | 4 + .../Websocket/WebsocketCollectionTests.cs | 4 + 11 files changed, 101 insertions(+), 1115 deletions(-) delete mode 100644 test/ApiSiteTests/TestAdminController.cs diff --git a/src/AgileConfig.Server.Apisite/Controllers/api/ConfigController.cs b/src/AgileConfig.Server.Apisite/Controllers/api/ConfigController.cs index 4d7bd2fd..38a41eea 100644 --- a/src/AgileConfig.Server.Apisite/Controllers/api/ConfigController.cs +++ b/src/AgileConfig.Server.Apisite/Controllers/api/ConfigController.cs @@ -58,7 +58,8 @@ public async Task>> GetAppConfig(string appId, [F } var cacheKey = $"ConfigController_APPCONFIG_{appId}_{env}"; - _cacheMemory.TryGetValue(cacheKey, out List configs); + List configs = null; + _cacheMemory?.TryGetValue(cacheKey, out configs); if (configs != null) { return configs; @@ -83,7 +84,7 @@ public async Task>> GetAppConfig(string appId, [F //增加5s的缓存,防止同一个app同时启动造成db的压力过大 var cacheOp = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromSeconds(5)); - _cacheMemory.Set(cacheKey, vms, cacheOp); + _cacheMemory?.Set(cacheKey, vms, cacheOp); return vms; } diff --git a/src/AgileConfig.Server.Apisite/Websocket/IWebsocketCollection.cs b/src/AgileConfig.Server.Apisite/Websocket/IWebsocketCollection.cs index bddeb495..0bcead22 100644 --- a/src/AgileConfig.Server.Apisite/Websocket/IWebsocketCollection.cs +++ b/src/AgileConfig.Server.Apisite/Websocket/IWebsocketCollection.cs @@ -31,6 +31,8 @@ public interface IWebsocketCollection void SendActionToAll(WebsocketAction action); void SendToAppClients(string appId, string message); + + void Clear(); } } diff --git a/src/AgileConfig.Server.Apisite/Websocket/WebsocketCollection.cs b/src/AgileConfig.Server.Apisite/Websocket/WebsocketCollection.cs index 4f0996fc..099e464f 100644 --- a/src/AgileConfig.Server.Apisite/Websocket/WebsocketCollection.cs +++ b/src/AgileConfig.Server.Apisite/Websocket/WebsocketCollection.cs @@ -204,6 +204,11 @@ public void SendActionToAll(WebsocketAction action) } } + public void Clear() + { + _Clients?.Clear(); + } + public static IWebsocketCollection Instance { get; private set; } public int Count => _Clients.Count; diff --git a/src/AgileConfig.Server.Common/TinyEventBus.cs b/src/AgileConfig.Server.Common/TinyEventBus.cs index 725e211f..7768a47c 100644 --- a/src/AgileConfig.Server.Common/TinyEventBus.cs +++ b/src/AgileConfig.Server.Common/TinyEventBus.cs @@ -42,7 +42,7 @@ public class TinyEventBus : ITinyEventBus private ILogger _logger = null; private TinyEventBus() { - _logger = Global.LoggerFactory.CreateLogger(); + _logger = Global.LoggerFactory?.CreateLogger(); _events = new ConcurrentDictionary>>(); } diff --git a/test/AgileConfig.Server.ServiceTests/EnsureTablesTests.cs b/test/AgileConfig.Server.ServiceTests/EnsureTablesTests.cs index 78673801..ba3f39ca 100644 --- a/test/AgileConfig.Server.ServiceTests/EnsureTablesTests.cs +++ b/test/AgileConfig.Server.ServiceTests/EnsureTablesTests.cs @@ -32,7 +32,7 @@ public void ExistTableSqliteTest() public void ExistTableSqlServerTest() { //SqlServer - string conn = "Persist Security Info = False; User ID =dev; Password =dev@123,; Initial Catalog =agile_config_test; Server =www..com"; + string conn = "TrustServerCertificate=True;Persist Security Info = False; User ID =dev; Password =dev; Initial Catalog =agile_config_test; Server =."; var sqlserver_fsq = new FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.SqlServer, conn) .Build(); @@ -90,7 +90,7 @@ public void ExistTableOracleTest() public void ExistTablePostgreSqlTest() { //SqlServer - string conn = "Host=127.0.0.1;Database=agile_config;Username=postgres;Password=dev@123"; + string conn = "Host=192.168.0.125;Port=15432;Database=agileconfig;Username=postgres;Password=123456"; var postgresql_fsq = new FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.PostgreSQL, conn) .Build(); diff --git a/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs index 382ab957..13b6fe67 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs @@ -1,15 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using System; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.IService; -using System.Runtime.CompilerServices; -using Microsoft.Extensions.Caching.Memory; -using Moq; using AgileConfig.Server.Service.Tests; namespace AgileConfig.Server.ServiceTests.mysql diff --git a/test/AgileConfig.Server.ServiceTests/oracle/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/ConfigServiceTests.cs index afc25ac8..0a238a17 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/ConfigServiceTests.cs @@ -1,874 +1,21 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; -using System; +using AgileConfig.Server.Service.Tests; using System.Collections.Generic; -using System.Text; -using FreeSql; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.IService; -using System.Runtime.CompilerServices; -using Microsoft.Extensions.Caching.Memory; -using Moq; -namespace AgileConfig.Server.Service.Tests.oracle +namespace AgileConfig.Server.ServiceTests.oracle { [TestClass()] - public class ConfigServiceTests + public class ConfigServiceTests_oracle : ConfigServiceTests { - IFreeSql fsq = null; - FreeSqlContext freeSqlContext; - IConfigService service = null; + string conn = "user id=x;password=x;data source=192.168.0.123/orcl"; - [TestInitialize] - public void TestInitialize() + public override Dictionary GetConfigurationData() { - string conn = "user id=CLINIC;password=CLINIC;data source=192.168.0.91/orcl"; - fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Oracle, conn) - .UseAutoSyncStructure(true) - .Build(); - FluentApi.Config(fsq); - freeSqlContext = new FreeSqlContext(fsq); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "oracle"; + dict["db:conn"] = conn; - var cache = new Mock(); - var config = new Config(); - - // todo - - //service = new ConfigService(cache.Object, new AppService(freeSqlContext), new SettingService(freeSqlContext), new UserService(freeSqlContext)); - fsq.Delete().Where("1=1"); - - Console.WriteLine("TestInitialize"); - } - - [TestCleanup] - public void Clean() - { - freeSqlContext.Dispose(); - fsq.Dispose(); - } - - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsTrue(result); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - // Assert.AreEqual(source.CreateTime, config.CreateTime); - // Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - source.AppId = "1"; - source.Group = "1"; - source.Key = "1"; - source.Value = "1"; - source.Description = "1"; - source.CreateTime = DateTime.Now; - source.UpdateTime = DateTime.Now; - source.Status = ConfigStatus.Enabled; - source.OnlineStatus = OnlineStatus.WaitPublish; - - var result1 = await service.UpdateAsync(source, ""); - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsTrue(result1); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - // Assert.AreEqual(source.CreateTime, config.CreateTime); - // Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source, ""); - Assert.IsTrue(result1); - - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(config); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(id, ""); - Assert.IsTrue(result1); - - var config = fsq.Select(new - { - Id = id - }).ToOne(); - - Assert.IsNull(config); - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var config = await service.GetAsync(id, ""); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - // Assert.AreEqual(source.CreateTime, config.CreateTime); - // Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task GetAllConfigsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - - var configs = await service.GetAllConfigsAsync(""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task GetByAppIdKeyTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var config = await service.GetByAppIdKeyEnv("001", "g", "k", "env"); - Assert.IsNotNull(config); - - var config1 = await service.GetByAppIdKeyEnv("002", "g", "k", "env"); - Assert.IsNull(config1); - } - - [TestMethod()] - public async Task GetByAppIdTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var configs = await service.GetByAppIdAsync("001", ""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task SearchTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var configs = await service.Search("001", "", "", ""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - var configs1 = await service.Search("", "o", "", ""); - Assert.IsNotNull(configs1); - Assert.AreEqual(1, configs1.Count); - var configs2 = await service.Search("", "", "e", ""); - Assert.IsNotNull(configs2); - Assert.AreEqual(1, configs2.Count); - } - - [TestMethod()] - public async Task CountEnabledConfigsAsyncTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var count = await service.CountEnabledConfigsAsync(); - Assert.AreEqual(1, count); - } - - [TestMethod()] - public async Task AppPublishedConfigsMd5Test() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var md5 = await service.AppPublishedConfigsMd5("001", ""); - Assert.IsNotNull(md5); - } - - [TestMethod()] - public void AppPublishedConfigsMd5CacheTest() - { - } - - [TestMethod()] - public async Task GetPublishedConfigsByAppIdTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - //var configs = await service.GetPublishedConfigsByAppId("001"); - //Assert.IsNotNull(configs); - //Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task AddRangeAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddRangeAsync(new List { - source, - source1 - }, ""); - Assert.IsTrue(result); - - var config = fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNotNull(config); - var config1 = fsq.Select(new - { - Id = id1 - }).ToOne(); - Assert.IsNotNull(config1); - } - - [TestMethod()] - public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() - { - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Delete().Where("1=1").ExecuteAffrows(); - - var app = new App(); - app.Id = "001"; - app.Name = "x"; - app.Enabled = true; - app.CreateTime = DateTime.Now; - app.UpdateTime = DateTime.Now; - app.Type = AppType.PRIVATE; - var app1 = new App(); - app1.Id = "002"; - app1.Name = "x"; - app1.Enabled = true; - app1.CreateTime = DateTime.Now; - app1.UpdateTime = DateTime.Now; - app.Type = AppType.Inheritance; - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Key = "k1", - Value = "v1", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source2 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k2", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source3 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k21", - Value = "v2", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var appref = new AppInheritanced(); - appref.AppId = app.Id; - appref.InheritancedAppId = app1.Id; - appref.Sort = 1; - appref.Id = Guid.NewGuid().ToString(); - - fsq.Insert(app).ExecuteAffrows(); - fsq.Insert(app1).ExecuteAffrows(); - fsq.Insert(source).ExecuteAffrows(); - fsq.Insert(source1).ExecuteAffrows(); - fsq.Insert(source2).ExecuteAffrows(); - fsq.Insert(source3).ExecuteAffrows(); - fsq.Insert(appref).ExecuteAffrows(); - - var dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(4, dict.Keys.Count); - - Assert.IsTrue(dict.ContainsKey(source.Key)); - Assert.IsTrue(dict.ContainsKey(source1.Key)); - Assert.IsTrue(dict.ContainsKey(source2.Key)); - Assert.IsTrue(dict.ContainsKey(source3.Key)); - - Assert.IsTrue(dict[source.Key].Value == "v"); - Assert.IsTrue(dict[source1.Key].Value == "v1"); - Assert.IsTrue(dict[source2.Key].Value == "v"); - Assert.IsTrue(dict[source3.Key].Value == "v2"); - - var source4 = new Config - { - AppId = "001", - Id = Guid.NewGuid().ToString(), - Key = "k4", - Value = "v3", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source5 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k4", - Value = "v2", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - fsq.Insert(source4).ExecuteAffrows(); - fsq.Insert(source5).ExecuteAffrows(); - - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); - - var config1 = dict["k4"]; - Assert.AreEqual(source4.Value, config1.Value); - - var app2 = new App(); - app2.Id = "003"; - app2.Name = "x"; - app2.Enabled = true; - app2.CreateTime = DateTime.Now; - app2.UpdateTime = DateTime.Now; - app2.Type = AppType.Inheritance; - fsq.Insert(app2).ExecuteAffrows(); - var source6 = new Config - { - AppId = "003", - Id = Guid.NewGuid().ToString(), - Key = "k2", - Value = "k4444", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - fsq.Delete().Where("1=1").ExecuteAffrows(); - fsq.Insert(source6).ExecuteAffrows(); - - fsq.Insert(appref).ExecuteAffrows(); - var appref1 = new AppInheritanced(); - appref1.AppId = app.Id; - appref1.InheritancedAppId = app2.Id; - appref1.Sort = 2; - appref1.Id = Guid.NewGuid().ToString(); - fsq.Insert(appref1).ExecuteAffrows(); - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); - - config1 = dict["k2"]; - Assert.AreEqual(source6.Value, config1.Value); + return dict; } } } \ No newline at end of file diff --git a/test/ApiSiteTests/TestAdminController.cs b/test/ApiSiteTests/TestAdminController.cs deleted file mode 100644 index f38bdb3f..00000000 --- a/test/ApiSiteTests/TestAdminController.cs +++ /dev/null @@ -1,167 +0,0 @@ -using AgileConfig.Server.Apisite.Controllers; -using AgileConfig.Server.Apisite.Controllers.api; -using AgileConfig.Server.Apisite.Models; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.IService; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Authentication; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.AspNetCore.Mvc.ViewFeatures; - -namespace ApiSiteTests -{ - [TestClass] - public class TestAdminController - { - [TestMethod] - public async Task TestLogin() - { - //var tempData = new Mock(); - //var settingService = new Mock(); - //var syslogService = new Mock(); - //var authenticationService = new Mock(); - //authenticationService.Setup(s => s.AuthenticateAsync(It.IsAny(), It.IsAny())) - // .ReturnsAsync(AuthenticateResult.Success(new AuthenticationTicket(new System.Security.Claims.ClaimsPrincipal(), ""))); - //var sp = new Mock(); - //sp.Setup(s => s.GetService(typeof(IAuthenticationService))) - // .Returns(() => { - // return authenticationService.Object; - // }); - - //var ctrl = new AdminController(settingService.Object); - //ctrl.ControllerContext = new ControllerContext(); - //ctrl.ControllerContext.HttpContext = new DefaultHttpContext(); - //ctrl.ControllerContext.HttpContext.RequestServices = sp.Object; - //ctrl.TempData = tempData.Object; - - //authenticationService.Setup(s => s.AuthenticateAsync(It.IsAny(), It.IsAny())) - // .ReturnsAsync(AuthenticateResult.Fail("")); - //settingService.Setup(s => s.HasSuperAdminPassword()) - // .ReturnsAsync(false); - - - //settingService.Setup(s => s.HasSuperAdminPassword()) - // .ReturnsAsync(true); - - - } - - [TestMethod] - public async Task TestLogin1() - { - //var tempData = new Mock(); - //var settingService = new Mock(); - //settingService.Setup(s => s.ValidateAdminPassword("123456")).ReturnsAsync(true); - //var syslogService = new Mock(); - - //var ctrl = new AdminController(settingService.Object); - - } - - - [TestMethod] - public async Task TestInitPassword() - { - //var settingService = new Mock(); - //var syslogService = new Mock(); - - //var ctrl = new AdminController(settingService.Object); - //var model = new InitPasswordVM - //{ - // password = "", - // confirmPassword = "" - //}; - //var act = await ctrl.InitPassword(model); - //Assert.IsNotNull(act); - //var vr = act as ViewResult; - //Assert.IsNotNull(vr); - //var msg = vr.ViewData["ErrorMessage"]; - //Assert.AreEqual("벻Ϊ", msg); - //act = await ctrl.InitPassword(new InitPasswordVM - //{ - // password = "1", - // confirmPassword = "" - //}); - //Assert.IsNotNull(act); - //vr = act as ViewResult; - //Assert.IsNotNull(vr); - //msg = vr.ViewData["ErrorMessage"]; - //Assert.AreEqual("벻Ϊ", msg); - //act = await ctrl.InitPassword(new InitPasswordVM - //{ - // password = "", - // confirmPassword = "1" - //}); - //Assert.IsNotNull(act); - //vr = act as ViewResult; - //Assert.IsNotNull(vr); - //msg = vr.ViewData["ErrorMessage"]; - //Assert.AreEqual("벻Ϊ", msg); - - //model = new InitPasswordVM - //{ - // password = "a12222222222222222222222222222222122222222222222222222222222222222a12222222222222222222222222222222122222222222222222222222222222222", - // confirmPassword = "1" - //}; - //act = await ctrl.InitPassword(model); - //Assert.IsNotNull(act); - //vr = act as ViewResult; - //Assert.IsNotNull(vr); - //msg = vr.ViewData["ErrorMessage"]; - //Assert.AreEqual("ܳ50λ", msg); - - //act = await ctrl.InitPassword(new InitPasswordVM - //{ - // password = "1", - // confirmPassword = "2" - //}); - //Assert.IsNotNull(act); - //vr = act as ViewResult; - //Assert.IsNotNull(vr); - //msg = vr.ViewData["ErrorMessage"]; - //Assert.AreEqual("벻һ", msg); - - //settingService.Setup(s => s.HasSuperAdminPassword()).ReturnsAsync(true); - //act = await ctrl.InitPassword(new InitPasswordVM - //{ - // password = "1", - // confirmPassword = "1" - //}); - //Assert.IsNotNull(act); - //vr = act as ViewResult; - //Assert.IsNotNull(vr); - //msg = vr.ViewData["ErrorMessage"]; - //Assert.AreEqual("ѾùҪٴ", msg); - - //settingService.Setup(s => s.HasSuperAdmin()).ReturnsAsync(false); - //settingService.Setup(s => s.HasSuperAdmin(It.IsAny())).ReturnsAsync(false); - //act = await ctrl.InitPassword(new InitPasswordVM - //{ - // password = "1", - // confirmPassword = "1" - //}); - //Assert.IsNotNull(act); - //vr = act as ViewResult; - //Assert.IsNotNull(vr); - //msg = vr.ViewData["ErrorMessage"]; - //Assert.AreEqual("ʼʧ", msg); - - //settingService.Setup(s => s.SetSuperAdminPassword(It.IsAny())).ReturnsAsync(true); - //act = await ctrl.InitPassword(new InitPasswordVM - //{ - // password = "1", - // confirmPassword = "1" - //}); - //Assert.IsNotNull(act); - //var rr = act as RedirectResult; - //Assert.IsNotNull(rr); - //Assert.AreEqual("InitPasswordSuccess", rr.Url); - } - } -} diff --git a/test/ApiSiteTests/TestApiConfigController.cs b/test/ApiSiteTests/TestApiConfigController.cs index 8fe57f67..18ca19d2 100644 --- a/test/ApiSiteTests/TestApiConfigController.cs +++ b/test/ApiSiteTests/TestApiConfigController.cs @@ -9,90 +9,90 @@ using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; +using AgileConfig.Server.Apisite.Controllers.api.Models; -namespace ApiSiteTests +namespace ApiSiteTests; + +[TestClass] +public class TestApiConfigController { - [TestClass] - public class TestApiConfigController + [TestMethod] + public async Task TestGet() { - [TestMethod] - public async Task TestGet() + App newApp() { - App newApp() - { - return new App() { - Enabled = true - }; - } + return new App() { + Enabled = true + }; + } - var appService = new Mock(); - appService.Setup(s => s.GetAsync("001")).ReturnsAsync(newApp); + var appService = new Mock(); + appService.Setup(s => s.GetAsync(It.IsAny())).ReturnsAsync(newApp); - List newConfigs() { - var list = new List(); - list.Add(new Config { - Id = "001", - Key ="key1", - Value = "val1", - Group = "" - }); - list.Add(new Config - { - Id = "002", - Key = "key2", - Value = "val2", - Group = "group1", - AppId = "001", - Status = ConfigStatus.Enabled - }); + List newConfigs() { + var list = new List(); + list.Add(new Config { + Id = "001", + Key ="key1", + Value = "val1", + Group = "" + }); + list.Add(new Config + { + Id = "002", + Key = "key2", + Value = "val2", + Group = "group1", + AppId = "001", + Status = ConfigStatus.Enabled + }); - return list; - } - var configService = new Mock(); - //configService.Setup(s => s.GetPublishedConfigsAsync("001")) - // .ReturnsAsync(newConfigs); - configService.Setup(s => s.GetPublishedConfigsByAppIdWithInheritanced("001", "")) - .ReturnsAsync(newConfigs); + return list; + } + var configService = new Mock(); + //configService.Setup(s => s.GetPublishedConfigsAsync("001")) + // .ReturnsAsync(newConfigs); + configService.Setup(s => s.GetPublishedConfigsByAppIdWithInheritanced(It.IsAny(), It.IsAny())) + .ReturnsAsync(newConfigs); - var memoryCache = new Mock(); - var remoteNodeProxy = new Mock(); - var serverNodeService = new Mock(); - var sysLogService = new Mock(); - var appBasicAuthService = new Mock(); - var userSErvice = new Mock(); + IMemoryCache memoryCache = null; + var remoteNodeProxy = new Mock(); + var serverNodeService = new Mock(); + var sysLogService = new Mock(); + var appBasicAuthService = new Mock(); + var userSErvice = new Mock(); - var ctrl = new ConfigController( - configService.Object, - appService.Object, - userSErvice.Object, - memoryCache.Object); - var act = await ctrl.GetAppConfig("001", ""); + var ctrl = new ConfigController( + configService.Object, + appService.Object, + userSErvice.Object, + memoryCache); + var act = await ctrl.GetAppConfig("001", "DEV"); - Assert.IsNotNull(act); - Assert.IsNotNull(act.Value); - Assert.IsInstanceOfType(act.Value, typeof(List)); - Assert.AreEqual(2, act.Value.Count); + Assert.IsNotNull(act); + Assert.IsNotNull(act.Value); + Assert.IsInstanceOfType(act.Value, typeof(List)); + Assert.AreEqual(2, act.Value.Count); - App newApp1() + App newApp1() + { + return new App() { - return new App() - { - Enabled = false - }; - } - appService = new Mock(); - appService.Setup(s => s.GetAsync("001")).ReturnsAsync(newApp1); + Enabled = false + }; + } + appService = new Mock(); + appService.Setup(s => s.GetAsync(It.IsAny())).ReturnsAsync(newApp1); - ctrl = new ConfigController( - configService.Object, - appService.Object, - userSErvice.Object, - memoryCache.Object); - act = await ctrl.GetAppConfig("001", ""); + ctrl = new ConfigController( + configService.Object, + appService.Object, + userSErvice.Object, + memoryCache); + act = await ctrl.GetAppConfig("001", "DEV"); - Assert.IsNotNull(act); - Assert.IsNull(act.Value); - Assert.IsInstanceOfType(act.Result, typeof(NotFoundResult)); - } + Assert.IsNotNull(act); + Assert.IsNull(act.Value); + Assert.IsInstanceOfType(act.Result, typeof(NotFoundResult)); } } diff --git a/test/ApiSiteTests/TestAppController.cs b/test/ApiSiteTests/TestAppController.cs index 2cc4d8f0..e5a999a5 100644 --- a/test/ApiSiteTests/TestAppController.cs +++ b/test/ApiSiteTests/TestAppController.cs @@ -3,6 +3,7 @@ using AgileConfig.Server.Apisite.Models; using AgileConfig.Server.Data.Entity; using AgileConfig.Server.IService; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; @@ -25,6 +26,9 @@ public async Task TestAdd() var permissionService = new Mock(); var ctl = new AgileConfig.Server.Apisite.Controllers.AppController(appService.Object, permissionService.Object, userService.Object); + + ctl.ControllerContext.HttpContext = new DefaultHttpContext(); + Assert.ThrowsException( () => { ctl.Add(null).GetAwaiter().GetResult(); }); diff --git a/test/ApiSiteTests/Websocket/WebsocketCollectionTests.cs b/test/ApiSiteTests/Websocket/WebsocketCollectionTests.cs index 382b2ef9..164c18d1 100644 --- a/test/ApiSiteTests/Websocket/WebsocketCollectionTests.cs +++ b/test/ApiSiteTests/Websocket/WebsocketCollectionTests.cs @@ -12,6 +12,8 @@ public class WebsocketCollectionTests [TestMethod()] public void AddClientTest() { + WebsocketCollection.Instance.Clear(); + var client = new WebsocketClient(); client.Id = Guid.NewGuid().ToString(); WebsocketCollection.Instance.AddClient(client); @@ -28,6 +30,8 @@ public void AddClientTest() [TestMethod()] public void RemoveClientTest() { + WebsocketCollection.Instance.Clear(); + var client = new WebsocketClient(); client.Id = Guid.NewGuid().ToString(); WebsocketCollection.Instance.AddClient(client); From 42f546f4ad659976313727538fb95c3ac7c9b8b6 Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 21 Jan 2024 18:20:42 +0800 Subject: [PATCH 42/45] Update testcases; --- .../EnsureTablesTests.cs | 12 ++++++------ .../PostgreSQL/AppServiceTests.cs | 2 +- .../PostgreSQL/ConfigServiceTests.cs | 5 +++-- .../PostgreSQL/ServerNodeServiceTests.cs | 10 +--------- .../PostgreSQL/SettingServiceTests.cs | 2 +- .../PostgreSQL/SysLogServiceTests.cs | 2 +- .../mysql/ConfigServiceTests.cs | 2 +- .../oracle/AppServiceTests.cs | 3 +-- .../oracle/ConfigServiceTests.cs | 2 +- .../oracle/ServerNodeServiceTests.cs | 2 +- .../oracle/SettingServiceTests.cs | 2 +- .../oracle/SysLogServiceTests.cs | 2 +- .../sqlite/BasicTestService.cs | 4 ++-- .../sqlite/ConfigServiceTests.cs | 7 +++---- .../sqlserver/AppServiceTests.cs | 4 ++-- .../sqlserver/ConfigServiceTests.cs | 5 +++-- .../sqlserver/ServerNodeServiceTests.cs | 2 +- .../sqlserver/SettingServiceTests.cs | 2 +- .../sqlserver/SysLogServiceTests.cs | 2 +- 19 files changed, 32 insertions(+), 40 deletions(-) diff --git a/test/AgileConfig.Server.ServiceTests/EnsureTablesTests.cs b/test/AgileConfig.Server.ServiceTests/EnsureTablesTests.cs index ba3f39ca..61c45d55 100644 --- a/test/AgileConfig.Server.ServiceTests/EnsureTablesTests.cs +++ b/test/AgileConfig.Server.ServiceTests/EnsureTablesTests.cs @@ -6,7 +6,7 @@ using FreeSql; using AgileConfig.Server.Data.Entity; -namespace AgileConfig.Server.Data.Freesql.Tests +namespace AgileConfig.Server.ServiceTests { [TestClass()] public class EnsureTablesTests @@ -17,7 +17,7 @@ public void ExistTableSqliteTest() //sqlite string conn = "Data Source=agile_config.db"; var sqllite_fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Sqlite, conn) + .UseConnectionString(DataType.Sqlite, conn) .Build(); FluentApi.Config(sqllite_fsq); sqllite_fsq.Ado.ExecuteNonQuery("drop table agc_app"); @@ -34,7 +34,7 @@ public void ExistTableSqlServerTest() //SqlServer string conn = "TrustServerCertificate=True;Persist Security Info = False; User ID =dev; Password =dev; Initial Catalog =agile_config_test; Server =."; var sqlserver_fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.SqlServer, conn) + .UseConnectionString(DataType.SqlServer, conn) .Build(); FluentApi.Config(sqlserver_fsq); sqlserver_fsq.Ado.ExecuteNonQuery("drop table agc_app"); @@ -51,7 +51,7 @@ public void ExistTableMysqlTest() //SqlServer string conn = "Database=agile_config_test;Data Source=192.168.0.125;User Id=root;Password=x;port=13306"; var mysql_fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.MySql, conn) + .UseConnectionString(DataType.MySql, conn) .Build(); FluentApi.Config(mysql_fsq); try @@ -75,7 +75,7 @@ public void ExistTableOracleTest() //SqlServer string conn = "user id=CLINIC;password=CLINIC;data source=192.168.0.91/orcl"; var oracle_fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.Oracle, conn) + .UseConnectionString(DataType.Oracle, conn) .Build(); FluentApi.Config(oracle_fsq); oracle_fsq.Ado.ExecuteNonQuery("drop table \"agc_app\" "); @@ -92,7 +92,7 @@ public void ExistTablePostgreSqlTest() //SqlServer string conn = "Host=192.168.0.125;Port=15432;Database=agileconfig;Username=postgres;Password=123456"; var postgresql_fsq = new FreeSqlBuilder() - .UseConnectionString(FreeSql.DataType.PostgreSQL, conn) + .UseConnectionString(DataType.PostgreSQL, conn) .Build(); FluentApi.Config(postgresql_fsq); postgresql_fsq.Ado.ExecuteNonQuery("drop table \"agc_app\" "); diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/AppServiceTests.cs index 71921c27..5d9a0b98 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/AppServiceTests.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.PostgreSQL +namespace AgileConfig.Server.ServiceTests.PostgreSQL { [TestClass()] public class AppServiceTests_pg : AppServiceTests diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ConfigServiceTests.cs index 8890ce7b..910e2e24 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ConfigServiceTests.cs @@ -1,7 +1,8 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using AgileConfig.Server.ServiceTests.sqlite; +using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; -namespace AgileConfig.Server.Service.Tests.PostgreSQL +namespace AgileConfig.Server.ServiceTests.PostgreSQL { [TestClass()] public class ConfigServiceTests_pg: ConfigServiceTests diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs index 5b812c98..5774a5d7 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/ServerNodeServiceTests.cs @@ -2,17 +2,9 @@ using AgileConfig.Server.Service; using System; using System.Collections.Generic; -using System.Text; -using AgileConfig.Server.Data.Freesql; -using FreeSql; -using AgileConfig.Server.Data.Entity; -using System.Threading.Tasks; -using AgileConfig.Server.Data.Repository.Freesql; -using AgileConfig.Server.IService; -using Microsoft.Extensions.DependencyInjection; using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.PostgreSQL +namespace AgileConfig.Server.ServiceTests.PostgreSQL { [TestClass()] public class ServerNodeServiceTests_pg: ServerNodeServiceTests diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/SettingServiceTests.cs index aa99004c..d151c2b0 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/SettingServiceTests.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.PostgreSQL +namespace AgileConfig.Server.ServiceTests.PostgreSQL { [TestClass()] public class SettingServiceTests_pg : SettingServiceTests diff --git a/test/AgileConfig.Server.ServiceTests/PostgreSQL/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/PostgreSQL/SysLogServiceTests.cs index 182b423d..aa03eca1 100644 --- a/test/AgileConfig.Server.ServiceTests/PostgreSQL/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/PostgreSQL/SysLogServiceTests.cs @@ -3,7 +3,7 @@ using AgileConfig.Server.ServiceTests.sqlite; using System.Collections.Generic; -namespace AgileConfig.Server.Service.Tests.PostgreSQL +namespace AgileConfig.Server.ServiceTests.PostgreSQL { [TestClass()] public class SysLogServiceTests_pg: SysLogServiceTests diff --git a/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs index 13b6fe67..73e275b3 100644 --- a/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mysql/ConfigServiceTests.cs @@ -1,6 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; -using AgileConfig.Server.Service.Tests; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.ServiceTests.mysql { diff --git a/test/AgileConfig.Server.ServiceTests/oracle/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/AppServiceTests.cs index 9841894e..a67d5fa7 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/AppServiceTests.cs @@ -1,10 +1,9 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service; using System; using System.Collections.Generic; using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.oracle +namespace AgileConfig.Server.ServiceTests.oracle { [TestClass()] public class AppServiceTests_oracle : AppServiceTests diff --git a/test/AgileConfig.Server.ServiceTests/oracle/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/ConfigServiceTests.cs index 0a238a17..ff9b6dfb 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/ConfigServiceTests.cs @@ -1,6 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using AgileConfig.Server.Service.Tests; using System.Collections.Generic; +using AgileConfig.Server.ServiceTests.sqlite; namespace AgileConfig.Server.ServiceTests.oracle { diff --git a/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs index f4c34bef..2de09d40 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/ServerNodeServiceTests.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.oracle +namespace AgileConfig.Server.ServiceTests.oracle { [TestClass()] public class ServerNodeServiceTests_oracle: ServerNodeServiceTests diff --git a/test/AgileConfig.Server.ServiceTests/oracle/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/SettingServiceTests.cs index 93249637..89631f89 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/SettingServiceTests.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.oracle +namespace AgileConfig.Server.ServiceTests.oracle { [TestClass()] public class SettingServiceTests_oracle : SettingServiceTests diff --git a/test/AgileConfig.Server.ServiceTests/oracle/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/oracle/SysLogServiceTests.cs index 7427d931..3a21ddb3 100644 --- a/test/AgileConfig.Server.ServiceTests/oracle/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/oracle/SysLogServiceTests.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.oracle +namespace AgileConfig.Server.ServiceTests.oracle { [TestClass()] public class SysLogServiceTests_oracle : SysLogServiceTests diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/BasicTestService.cs b/test/AgileConfig.Server.ServiceTests/sqlite/BasicTestService.cs index 1f5f14e8..b50ab940 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/BasicTestService.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/BasicTestService.cs @@ -2,6 +2,7 @@ using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.Data.Repository.Freesql; +using AgileConfig.Server.Data.Repository.Selector; using AgileConfig.Server.IService; using AgileConfig.Server.Service; using Microsoft.Extensions.Caching.Memory; @@ -43,9 +44,8 @@ public BasicTestService() services.AddScoped(_ => cache.Object); services.AddSingleton(config); services.AddFreeSqlFactory(); - services.AddFreeSqlRepository(); + services.AddRepositories(); services.AddBusinessServices(); - AddEnvRepositiroies(services); _serviceProvider = services.BuildServiceProvider(); var systeminitializationService = _serviceProvider.GetService(); diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs index 101ae751..54938173 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs @@ -8,10 +8,9 @@ using AgileConfig.Server.IService; using Microsoft.Extensions.Caching.Memory; using Moq; -using AgileConfig.Server.ServiceTests.sqlite; using Microsoft.Extensions.DependencyInjection; -namespace AgileConfig.Server.Service.Tests +namespace AgileConfig.Server.ServiceTests.sqlite { [TestClass()] public class ConfigServiceTests : BasicTestService @@ -800,7 +799,7 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() _fsq.Insert(source3).ExecuteAffrows(); await _service.Publish(app1.Id, new string[] { }, "", "", env); - await _service.Publish(app.Id, new string[] { },"", "", env); + await _service.Publish(app.Id, new string[] { }, "", "", env); var dict = await _service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, env); Assert.IsNotNull(dict); @@ -864,7 +863,7 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() app2.UpdateTime = DateTime.Now; app2.Type = AppType.Inheritance; _fsq.Insert(app2).ExecuteAffrows(); - + // 插入1个app 003 _fsq.Delete().Where("1=1").ExecuteAffrows(); diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs index aaa4fdac..bf0edf86 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/AppServiceTests.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.sqlserver +namespace AgileConfig.Server.ServiceTests.sqlserver { [TestClass()] - public class AppServiceTests_sqlserver: AppServiceTests + public class AppServiceTests_sqlserver : AppServiceTests { string conn = "TrustServerCertificate=True;Persist Security Info = False; User ID =dev; Password =dev; Initial Catalog =agile_config_test; Server =."; diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/ConfigServiceTests.cs index 1cf58732..4904ef67 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/ConfigServiceTests.cs @@ -1,7 +1,8 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; +using AgileConfig.Server.ServiceTests.sqlite; +using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; -namespace AgileConfig.Server.Service.Tests.sqlserver +namespace AgileConfig.Server.ServiceTests.sqlserver { [TestClass()] public class ConfigServiceTests_sqlserver: ConfigServiceTests diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs index f6e4494d..839c349c 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/ServerNodeServiceTests.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.sqlserver +namespace AgileConfig.Server.ServiceTests.sqlserver { [TestClass()] public class ServerNodeServiceTests_sqlserver: ServerNodeServiceTests diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/SettingServiceTests.cs index 772e2f5b..99ca894a 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/SettingServiceTests.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.sqlserver +namespace AgileConfig.Server.ServiceTests.sqlserver { [TestClass()] public class SettingServiceTests_sqlserver : SettingServiceTests diff --git a/test/AgileConfig.Server.ServiceTests/sqlserver/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlserver/SysLogServiceTests.cs index 9f4398e3..1d6b465c 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlserver/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlserver/SysLogServiceTests.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using AgileConfig.Server.ServiceTests.sqlite; -namespace AgileConfig.Server.Service.Tests.sqlserver +namespace AgileConfig.Server.ServiceTests.sqlserver { [TestClass()] public class SysLogServiceTests_sqlserver : SysLogServiceTests From d5a7dc89bd3d433f3b8f8f0078c358b2f2e04a1b Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 21 Jan 2024 19:31:50 +0800 Subject: [PATCH 43/45] Fix mongodb syslog sorted issue --- src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs index 066e411d..3749a7a2 100644 --- a/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs +++ b/src/AgileConfig.Server.Data.Mongodb/MongodbRepository.cs @@ -177,7 +177,7 @@ public async Task> QueryPageAsync(Expression> return new List(); var query = _access.MongoQueryable.Where(exp); var sort = Sort(defaultSortField); - query = string.Equals(defaultSortField, "DESC", StringComparison.OrdinalIgnoreCase) + query = string.Equals(defaultSortType, "DESC", StringComparison.OrdinalIgnoreCase) ? query.OrderByDescending(sort) : query.OrderBy(sort); return await query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync(); From a7b96fe1c47a0040c832d820ec5290c9603d5b0e Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 21 Jan 2024 20:27:28 +0800 Subject: [PATCH 44/45] =?UTF-8?q?=E9=87=8D=E6=9E=84=20test=20cases,=20?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E4=BA=86=20freesql=20=E8=B7=9F=20mongodb=20?= =?UTF-8?q?=E7=9A=84=E6=B5=8B=E8=AF=95=E7=94=A8=E4=BE=8B=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mongodb/AppServiceTests.cs | 32 + .../mongodb/ConfigServiceTests.cs | 935 +----------------- .../mongodb/ServerNodeServiceTests.cs | 34 + .../mongodb/SettingServiceTests.cs | 25 + .../mongodb/SysLogServiceTests.cs | 209 +--- .../sqlite/AppServiceTests.cs | 47 +- .../sqlite/BasicTestService.cs | 57 +- .../sqlite/ConfigServiceTests.cs | 119 +-- .../sqlite/ServerNodeServiceTests.cs | 31 +- .../sqlite/SettingServiceTests.cs | 24 +- .../sqlite/SysLogServiceTests.cs | 40 +- 11 files changed, 249 insertions(+), 1304 deletions(-) create mode 100644 test/AgileConfig.Server.ServiceTests/mongodb/AppServiceTests.cs create mode 100644 test/AgileConfig.Server.ServiceTests/mongodb/ServerNodeServiceTests.cs create mode 100644 test/AgileConfig.Server.ServiceTests/mongodb/SettingServiceTests.cs diff --git a/test/AgileConfig.Server.ServiceTests/mongodb/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mongodb/AppServiceTests.cs new file mode 100644 index 00000000..47a5711c --- /dev/null +++ b/test/AgileConfig.Server.ServiceTests/mongodb/AppServiceTests.cs @@ -0,0 +1,32 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Collections.Generic; +using AgileConfig.Server.ServiceTests.sqlite; +using AgileConfig.Server.Data.Repository.Mongodb; + +namespace AgileConfig.Server.ServiceTests.mongodb +{ + [TestClass()] + public class AppServiceTests_mongo : AppServiceTests + { + public override void ClearData() + { + var repository = new AppRepository(conn); + var entities = repository.AllAsync().Result; + foreach (var entity in entities) + { + repository.DeleteAsync(entity).Wait(); + } + } + + string conn = "mongodb://192.168.0.125:27017/agile_config_1"; + + public override Dictionary GetConfigurationData() + { + var dict = base.GetConfigurationData(); + dict["db:provider"] = "mongodb"; + dict["db:conn"] = conn; + + return dict; + } + } +} \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mongodb/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mongodb/ConfigServiceTests.cs index b0f7f02e..c3a929f1 100644 --- a/test/AgileConfig.Server.ServiceTests/mongodb/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mongodb/ConfigServiceTests.cs @@ -1,929 +1,32 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using AgileConfig.Server.Data.Abstraction; -using AgileConfig.Server.Data.Abstraction.DbProvider; -using AgileConfig.Server.Data.Entity; -using AgileConfig.Server.Data.Freesql; -using AgileConfig.Server.Data.Mongodb; -using AgileConfig.Server.Data.Repository.Mongodb; -using AgileConfig.Server.Data.Repository.Selector; -using AgileConfig.Server.IService; -using AgileConfig.Server.Service; -using Microsoft.Extensions.Caching.Memory; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.Data.Repository.Mongodb; +using AgileConfig.Server.ServiceTests.sqlite; using Microsoft.VisualStudio.TestTools.UnitTesting; -using Moq; - -namespace AgileConfig.Server.ServiceTests.mongodb; +using System.Collections.Generic; -[TestClass] -public class ConfigServiceTests : Basic +namespace AgileConfig.Server.ServiceTests.mongodb { - IConfigService service = null; - - - [TestInitialize] - public void TestInitialize() - { - service = GetService(); - } - - - [TestCleanup] - public void Clean() - { - } - - [TestMethod()] - public async Task AddAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var config = await ConfigRepository.GetAsync(id); - - - Assert.IsTrue(result); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), - config.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), - config.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task UpdateAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - source.AppId = "1"; - source.Group = "1"; - source.Key = "1"; - source.Value = "1"; - source.Description = "1"; - source.CreateTime = DateTime.Now; - source.UpdateTime = DateTime.Now; - source.Status = ConfigStatus.Enabled; - source.OnlineStatus = OnlineStatus.WaitPublish; - - var result1 = await service.UpdateAsync(source, ""); - var config = await ConfigRepository.GetAsync(id); - - Assert.IsTrue(result1); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - Assert.AreEqual(source.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), - config.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), - config.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task UpdateAsyncListTest() + [TestClass()] + public class ConfigServiceTests_mongo : ConfigServiceTests { - var ids = Enumerable.Range(0, 10).ToDictionary(x => x, _ => Guid.NewGuid().ToString()); - var list = Enumerable.Range(0, 10).Select(x => new Config + public override void ClearData() { - AppId = "001", - Id = ids[x], - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }).ToList(); - - var result = await service.AddRangeAsync(list, ""); - Assert.IsTrue(result); - - foreach (var item in list) - { - var index = list.IndexOf(item); - item.AppId = "1" + index; - item.Group = "1" + index; - item.Key = "1" + index; - item.Value = "1" + index; - item.Description = "1"; - item.CreateTime = DateTime.Now; - item.UpdateTime = DateTime.Now; - item.Status = ConfigStatus.Enabled; - item.OnlineStatus = OnlineStatus.WaitPublish; + var repository = new ConfigRepository(conn); + var entities = repository.AllAsync().Result; + foreach (var entity in entities) + { + repository.DeleteAsync(entity).Wait(); + } } - var result1 = await service.UpdateAsync(list, ""); - var idsValue = ids.Select(x => x.Value).ToList(); - var dbConfigs = await ConfigRepository.QueryAsync(x => idsValue.Contains(x.Id)); + string conn = "mongodb://192.168.0.125:27017/agile_config_1"; - Assert.IsTrue(result1); - Assert.IsNotNull(dbConfigs); - Assert.IsTrue(dbConfigs.Count > 0); - - foreach (var item in list) + public override Dictionary GetConfigurationData() { - var current = dbConfigs.FirstOrDefault(x => x.Id == item.Id); - Assert.IsNotNull(current); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "mongodb"; + dict["db:conn"] = conn; - Assert.AreEqual(item.Id, current.Id); - Assert.AreEqual(item.Group, current.Group); - Assert.AreEqual(item.Key, current.Key); - Assert.AreEqual(item.Value, current.Value); - Assert.AreEqual(item.Description, current.Description); - Assert.AreEqual(item.AppId, current.AppId); - Assert.AreEqual(item.CreateTime.ToString("yyyy/MM/dd HH:mm:ss"), - current.CreateTime.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(item.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss"), - current.UpdateTime?.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(item.Status, current.Status); - Assert.AreEqual(item.OnlineStatus, current.OnlineStatus); + return dict; } } - - [TestMethod()] - public async Task DeleteAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(source, ""); - Assert.IsTrue(result1); - - var config = await ConfigRepository.GetAsync(id); - - Assert.IsNull(config); - } - - [TestMethod()] - public async Task DeleteAsyncTest1() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var result1 = await service.DeleteAsync(id, ""); - Assert.IsTrue(result1); - - var config = await ConfigRepository.GetAsync(id); - - Assert.IsNull(config); - } - - [TestMethod()] - public async Task GetAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - - var config = await service.GetAsync(id, ""); - Assert.IsNotNull(config); - - Assert.AreEqual(source.Id, config.Id); - Assert.AreEqual(source.Group, config.Group); - Assert.AreEqual(source.Key, config.Key); - Assert.AreEqual(source.Value, config.Value); - Assert.AreEqual(source.Description, config.Description); - Assert.AreEqual(source.AppId, config.AppId); - Assert.AreEqual(source.CreateTime, config.CreateTime); - Assert.AreEqual(source.UpdateTime, config.UpdateTime); - Assert.AreEqual(source.Status, config.Status); - Assert.AreEqual(source.OnlineStatus, config.OnlineStatus); - } - - [TestMethod()] - public async Task GetAllConfigsAsyncTest() - { - var all = await ConfigRepository.AllAsync(); - await ConfigRepository.DeleteAsync(all); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - - var configs = await service.GetAllConfigsAsync(""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task GetByAppIdKeyTest() - { - var all = await ConfigRepository.AllAsync(); - await ConfigRepository.DeleteAsync(all); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var config = await service.GetByAppIdKeyEnv("001", "g", "k", "env"); - Assert.IsNotNull(config); - - var config1 = await service.GetByAppIdKeyEnv("002", "g", "k", "env"); - Assert.IsNull(config1); - } - - [TestMethod()] - public async Task GetByAppIdTest() - { - var all = await ConfigRepository.AllAsync(); - await ConfigRepository.DeleteAsync(all); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var configs = await service.GetByAppIdAsync("001", ""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task SearchTest() - { - var all = await ConfigRepository.AllAsync(); - await ConfigRepository.DeleteAsync(all); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var configs = await service.Search("001", "", "", ""); - Assert.IsNotNull(configs); - Assert.AreEqual(1, configs.Count); - var configs1 = await service.Search("", "o", "", ""); - Assert.IsNotNull(configs1); - Assert.AreEqual(1, configs1.Count); - var configs2 = await service.Search("", "", "e", ""); - Assert.IsNotNull(configs2); - Assert.AreEqual(1, configs2.Count); - } - - [TestMethod()] - public async Task CountEnabledConfigsAsyncTest() - { - var all = await ConfigRepository.AllAsync(); - await ConfigRepository.DeleteAsync(all); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var count = await service.CountEnabledConfigsAsync(); - Assert.AreEqual(1, count); - } - - [TestMethod()] - public async Task AppPublishedConfigsMd5Test() - { - var all = await ConfigRepository.AllAsync(); - await ConfigRepository.DeleteAsync(all); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - var md5 = await service.AppPublishedConfigsMd5("001", ""); - Assert.IsNotNull(md5); - } - - [TestMethod()] - public void AppPublishedConfigsMd5CacheTest() - { - } - - [TestMethod()] - public async Task GetPublishedConfigsByAppIdTest() - { - var all = await ConfigRepository.AllAsync(); - await ConfigRepository.DeleteAsync(all); - - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var id2 = Guid.NewGuid().ToString(); - var source2 = new Config - { - AppId = "002", - Id = id2, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - var result = await service.AddAsync(source, ""); - Assert.IsTrue(result); - var result1 = await service.AddAsync(source1, ""); - Assert.IsTrue(result1); - var result2 = await service.AddAsync(source2, ""); - Assert.IsTrue(result2); - - //var configs = await service.GetPublishedConfigsByAppId("001"); - //Assert.IsNotNull(configs); - //Assert.AreEqual(1, configs.Count); - } - - [TestMethod()] - public async Task AddRangeAsyncTest() - { - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Group = "group", - Key = "key", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Group = "g", - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online - }; - - var result = await service.AddRangeAsync(new List - { - source, - source1 - }, ""); - Assert.IsTrue(result); - - var config = await ConfigRepository.GetAsync(id); - Assert.IsNotNull(config); - var config1 = await ConfigRepository.GetAsync(id); - Assert.IsNotNull(config1); - } - - [TestMethod()] - public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() - { - var appAll = await AppRepository.AllAsync(); - await AppRepository.DeleteAsync(appAll); - - var all = await ConfigRepository.AllAsync(); - await ConfigRepository.DeleteAsync(all); - - var appInheritancedAll = await AppInheritancedRepository.AllAsync(); - await AppInheritancedRepository.DeleteAsync(appInheritancedAll); - - var app = new App(); - app.Id = "001"; - app.Name = "x"; - app.Enabled = true; - app.CreateTime = DateTime.Now; - app.UpdateTime = DateTime.Now; - app.Type = AppType.PRIVATE; - var app1 = new App(); - app1.Id = "002"; - app1.Name = "x"; - app1.Enabled = true; - app1.CreateTime = DateTime.Now; - app1.UpdateTime = DateTime.Now; - app.Type = AppType.Inheritance; - var id = Guid.NewGuid().ToString(); - var source = new Config - { - AppId = "001", - Id = id, - Key = "k", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var id1 = Guid.NewGuid().ToString(); - var source1 = new Config - { - AppId = "001", - Id = id1, - Key = "k1", - Value = "v1", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source2 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k2", - Value = "v", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source3 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k21", - Value = "v2", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var appref = new AppInheritanced(); - appref.AppId = app.Id; - appref.InheritancedAppId = app1.Id; - appref.Sort = 1; - appref.Id = Guid.NewGuid().ToString(); - - await AppRepository.InsertAsync(app); - await AppRepository.InsertAsync(app1); - await ConfigRepository.InsertAsync(source); - await ConfigRepository.InsertAsync(source1); - await ConfigRepository.InsertAsync(source2); - await ConfigRepository.InsertAsync(source3); - await AppInheritancedRepository.InsertAsync(appref); - - - var dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(4, dict.Keys.Count); - - Assert.IsTrue(dict.ContainsKey(source.Key)); - Assert.IsTrue(dict.ContainsKey(source1.Key)); - Assert.IsTrue(dict.ContainsKey(source2.Key)); - Assert.IsTrue(dict.ContainsKey(source3.Key)); - - Assert.IsTrue(dict[source.Key].Value == "v"); - Assert.IsTrue(dict[source1.Key].Value == "v1"); - Assert.IsTrue(dict[source2.Key].Value == "v"); - Assert.IsTrue(dict[source3.Key].Value == "v2"); - - var source4 = new Config - { - AppId = "001", - Id = Guid.NewGuid().ToString(), - Key = "k4", - Value = "v3", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - var source5 = new Config - { - AppId = "002", - Id = Guid.NewGuid().ToString(), - Key = "k4", - Value = "v2", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - - await ConfigRepository.InsertAsync(source4); - await ConfigRepository.InsertAsync(source5); - - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); - - var config1 = dict["k4"]; - Assert.AreEqual(source4.Value, config1.Value); - - var app2 = new App(); - app2.Id = "003"; - app2.Name = "x"; - app2.Enabled = true; - app2.CreateTime = DateTime.Now; - app2.UpdateTime = DateTime.Now; - app2.Type = AppType.Inheritance; - await AppRepository.InsertAsync(app2); - var source6 = new Config - { - AppId = "003", - Id = Guid.NewGuid().ToString(), - Key = "k2", - Value = "k4444", - Description = "d", - CreateTime = DateTime.Now, - UpdateTime = DateTime.Now, - Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online - }; - - - var appInheritancedAll2 = await AppInheritancedRepository.AllAsync(); - await AppInheritancedRepository.DeleteAsync(appInheritancedAll2); - await ConfigRepository.InsertAsync(source6); - await AppInheritancedRepository.InsertAsync(appref); - - - var appref1 = new AppInheritanced(); - appref1.AppId = app.Id; - appref1.InheritancedAppId = app2.Id; - appref1.Sort = 2; - appref1.Id = Guid.NewGuid().ToString(); - await AppInheritancedRepository.InsertAsync(appref1); - dict = await service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, ""); - Assert.IsNotNull(dict); - Assert.AreEqual(5, dict.Keys.Count); - - config1 = dict["k2"]; - Assert.AreEqual(source6.Value, config1.Value); - } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mongodb/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mongodb/ServerNodeServiceTests.cs new file mode 100644 index 00000000..3681b027 --- /dev/null +++ b/test/AgileConfig.Server.ServiceTests/mongodb/ServerNodeServiceTests.cs @@ -0,0 +1,34 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using AgileConfig.Server.Service; +using System; +using System.Collections.Generic; +using AgileConfig.Server.ServiceTests.sqlite; +using AgileConfig.Server.Data.Repository.Mongodb; + +namespace AgileConfig.Server.ServiceTests.mongodb +{ + [TestClass()] + public class ServerNodeServiceTests_mongo: ServerNodeServiceTests + { + public override void ClearData() + { + var repository = new ServerNodeRepository(conn); + var entities = repository.AllAsync().Result; + foreach (var log in entities) + { + repository.DeleteAsync(log).Wait(); + } + } + + string conn = "mongodb://192.168.0.125:27017/agile_config_1"; + + public override Dictionary GetConfigurationData() + { + var dict = base.GetConfigurationData(); + dict["db:provider"] = "mongodb"; + dict["db:conn"] = conn; + + return dict; + } + } +} \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mongodb/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mongodb/SettingServiceTests.cs new file mode 100644 index 00000000..e8cabf2e --- /dev/null +++ b/test/AgileConfig.Server.ServiceTests/mongodb/SettingServiceTests.cs @@ -0,0 +1,25 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Collections.Generic; +using AgileConfig.Server.ServiceTests.sqlite; + +namespace AgileConfig.Server.ServiceTests.mongodb +{ + [TestClass()] + public class SettingServiceTests_mongo : SettingServiceTests + { + public override void ClearData() + { + } + + string conn = "mongodb://192.168.0.125:27017/agile_config_1"; + + public override Dictionary GetConfigurationData() + { + var dict = base.GetConfigurationData(); + dict["db:provider"] = "mongodb"; + dict["db:conn"] = conn; + + return dict; + } + } +} \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/mongodb/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mongodb/SysLogServiceTests.cs index 9872d267..665e2881 100644 --- a/test/AgileConfig.Server.ServiceTests/mongodb/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mongodb/SysLogServiceTests.cs @@ -3,215 +3,34 @@ using System.Threading.Tasks; using AgileConfig.Server.Data.Abstraction; using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Repository.Mongodb; using AgileConfig.Server.IService; +using AgileConfig.Server.ServiceTests.sqlite; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AgileConfig.Server.ServiceTests.mongodb; [TestClass()] -public class SysLogServiceTests : Basic +public class SysLogServiceTests_mongo : SysLogServiceTests { - ISysLogService service = null; - - [TestInitialize] - public void TestInitialize() + public override void ClearData() { - service = GetService(); - } - - - [TestCleanup] - public void Clean() - { - } - - [TestMethod()] - public async Task AddSysLogAsyncTest() - { - var source = new SysLog + var repository = new SysLogRepository(conn); + var syslogs = repository.AllAsync().Result; + foreach (var log in syslogs) { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - - var result = await service.AddSysLogAsync(source); - Assert.IsTrue(result); - - var log = await SysLogRepository.GetAsync(source.Id); - - Assert.IsNotNull(log); - - Assert.AreEqual(source.Id, log.Id); - Assert.AreEqual(source.AppId, log.AppId); - Assert.AreEqual(source.LogType, log.LogType); - Assert.AreEqual(source.LogTime, log.LogTime); - Assert.AreEqual(source.LogText, log.LogText); - } - - [TestMethod()] - public async Task AddSysLogTransactionAsyncTest() - { - var uowAccessor = GetService>(); - var uow = uowAccessor(""); - - var id = Guid.NewGuid().ToString(); - var source = new SysLog - { - Id = id, - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - - - try - { - SysLogRepository.Uow = uow; - uow?.Begin(); - await SysLogRepository.InsertAsync(source); - throw new Exception(); + repository.DeleteAsync(log).Wait(); } - catch (Exception e) - { - Console.WriteLine(e); - uow?.Rollback(); - } - finally - { - uow?.Dispose(); - } - - var log = await SysLogRepository.GetAsync(id); - - Assert.IsNull(log); - - - var uowAccessor2 = GetService>(); - var uow2 = uowAccessor2(""); - SysLogRepository.Uow = uow2; - uow2.Begin(); - await SysLogRepository.InsertAsync(source); - await uow2.SaveChangesAsync(); - var log2 = await SysLogRepository.GetAsync(id); - uow2.Dispose(); - - Assert.AreEqual(source.Id, log2.Id); - Assert.AreEqual(source.AppId, log2.AppId); - Assert.AreEqual(source.LogType, log2.LogType); - Assert.AreEqual(source.LogTime?.ToString("yyyy/MM/dd HH:mm:ss"), log2.LogTime?.ToString("yyyy/MM/dd HH:mm:ss")); - Assert.AreEqual(source.LogText, log2.LogText); - } - - - [TestMethod()] - public async Task AddRangeAsyncTest() - { - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List - { - source, source1 - }); - Assert.IsTrue(result); - - var log = await SysLogRepository.GetAsync(source.Id); - Assert.IsNotNull(log); - Assert.AreEqual(source.Id, log.Id); - Assert.AreEqual(source.AppId, log.AppId); - Assert.AreEqual(source.LogType, log.LogType); - Assert.AreEqual(source.LogTime, log.LogTime); - Assert.AreEqual(source.LogText, log.LogText); - - var log1 = await SysLogRepository.GetAsync(source.Id); - Assert.IsNotNull(log1); - Assert.AreEqual(source1.Id, log1.Id); - Assert.AreEqual(source1.AppId, log1.AppId); - Assert.AreEqual(source1.LogType, log1.LogType); - Assert.AreEqual(source1.LogTime, log1.LogTime); - Assert.AreEqual(source1.LogText, log1.LogText); } + string conn = "mongodb://192.168.0.125:27017/agile_config_1"; - [TestMethod()] - public async Task CountTest() - { - var all = await SysLogRepository.AllAsync(); - await SysLogRepository.DeleteAsync(all); - - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List - { - source, source1 - }); - Assert.IsTrue(result); - - var count = await service.Count("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1)); - Assert.AreEqual(1, count); - - var count1 = await service.Count("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1)); - Assert.AreEqual(0, count1); - } - - [TestMethod()] - public async Task SearchPageTest() + public override Dictionary GetConfigurationData() { - var all = await SysLogRepository.AllAsync(); - await SysLogRepository.DeleteAsync(all); - - var source = new SysLog - { - AppId = "001", - LogType = SysLogType.Normal, - LogTime = DateTime.Now, - LogText = "123" - }; - var source1 = new SysLog - { - AppId = "002", - LogType = SysLogType.Warn, - LogTime = DateTime.Now, - LogText = "124" - }; - var result = await service.AddRangeAsync(new List - { - source, source1 - }); - Assert.IsTrue(result); - - var page = await service.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1), - 1, 1); - Assert.AreEqual(1, page.Count); + var dict = base.GetConfigurationData(); + dict["db:provider"] = "mongodb"; + dict["db:conn"] = conn; - var page1 = await service.SearchPage("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), - 0, 0); - Assert.AreEqual(0, page1.Count); + return dict; } } \ No newline at end of file diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs index 19660930..05fb7bfc 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/AppServiceTests.cs @@ -6,6 +6,7 @@ using AgileConfig.Server.IService; using AgileConfig.Server.Service; using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.Data.Abstraction; namespace AgileConfig.Server.ServiceTests.sqlite { @@ -27,7 +28,7 @@ public override Dictionary GetConfigurationData() public void TestInitialize() { _appservice = _serviceProvider.GetService(); - _fsq.Delete().Where("1=1"); + ClearData(); } @@ -45,10 +46,7 @@ public async Task AddAsyncTest() Enabled = true }; var result = await _appservice.AddAsync(source); - var app = _fsq.Select(new - { - Id = id - }).ToOne(); + var app = await _appservice.GetAsync(source.Id); Assert.IsTrue(result); Assert.IsNotNull(app); @@ -79,13 +77,6 @@ public async Task DeleteAsyncTest() var delResult = await _appservice.DeleteAsync(source); Assert.IsTrue(delResult); - - var app = _fsq.Select(new - { - Id = id - }).ToOne(); - Assert.IsNull(app); - } [TestMethod()] @@ -107,10 +98,8 @@ public async Task DeleteAsyncTest1() var delResult = await _appservice.DeleteAsync(id); Assert.IsTrue(delResult); - var app = _fsq.Select(new - { - Id = id - }).ToOne(); + var app = await _appservice.GetAsync(source.Id); + Assert.IsNull(app); } @@ -137,15 +126,16 @@ public async Task GetAsyncTest() Assert.AreEqual(source.Id, app.Id); Assert.AreEqual(source.Name, app.Name); Assert.AreEqual(source.Secret, app.Secret); - Assert.AreEqual(source.CreateTime.ToString("yyyyMMddhhmmss"), app.CreateTime.ToString("yyyyMMddhhmmss")); - Assert.AreEqual(source.UpdateTime.Value.ToString("yyyyMMddhhmmss"), app.UpdateTime.Value.ToString("yyyyMMddhhmmss")); + Assert.AreEqual(source.CreateTime.ToString("yyyyMMddhhmm"), app.CreateTime.ToString("yyyyMMddhhmm")); + Assert.AreEqual(source.UpdateTime.Value.ToString("yyyyMMddhhmm"), app.UpdateTime.Value.ToString("yyyyMMddhhmm")); Assert.AreEqual(source.Enabled, app.Enabled); } [TestMethod()] public async Task GetAllAppsAsyncTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + ClearData(); + var id = Guid.NewGuid().ToString(); var source = new App { @@ -203,10 +193,7 @@ public async Task UpdateAsyncTest() var result1 = await _appservice.UpdateAsync(source); Assert.IsTrue(result1); - var app = _fsq.Select(new - { - Id = id - }).ToOne(); + var app = await _appservice.GetAsync(source.Id); Assert.AreEqual(source.Id, app.Id); Assert.AreEqual(source.Name, app.Name); @@ -219,7 +206,8 @@ public async Task UpdateAsyncTest() [TestMethod()] public async Task CountEnabledAppsAsyncTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); + var id = Guid.NewGuid().ToString(); var source = new App { @@ -252,7 +240,8 @@ public async Task CountEnabledAppsAsyncTest() [TestMethod()] public async Task GetAllInheritancedAppsAsyncTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); + var id = Guid.NewGuid().ToString(); var source = new App { @@ -308,8 +297,7 @@ public async Task GetAllInheritancedAppsAsyncTest() [TestMethod()] public async Task GetInheritancedAppsAsyncTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); var id = Guid.NewGuid().ToString(); var source = new App @@ -357,8 +345,9 @@ public async Task GetInheritancedAppsAsyncTest() var result = await _appservice.AddAsync(source); await _appservice.AddAsync(source1); await _appservice.AddAsync(source2); - _fsq.Insert(appInher).ExecuteAffrows(); - _fsq.Insert(appInher1).ExecuteAffrows(); + + await _serviceProvider.GetService().InsertAsync(appInher); + await _serviceProvider.GetService().InsertAsync(appInher1); Assert.IsTrue(result); diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/BasicTestService.cs b/test/AgileConfig.Server.ServiceTests/sqlite/BasicTestService.cs index b50ab940..b41e8058 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/BasicTestService.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/BasicTestService.cs @@ -1,5 +1,6 @@ using AgileConfig.Server.Common; using AgileConfig.Server.Data.Abstraction; +using AgileConfig.Server.Data.Entity; using AgileConfig.Server.Data.Freesql; using AgileConfig.Server.Data.Repository.Freesql; using AgileConfig.Server.Data.Repository.Selector; @@ -17,7 +18,6 @@ namespace AgileConfig.Server.ServiceTests.sqlite public class BasicTestService { protected ServiceProvider _serviceProvider; - protected IFreeSql _fsq = null; public virtual Dictionary GetConfigurationData() { @@ -29,6 +29,22 @@ public virtual Dictionary GetConfigurationData() }; } + public virtual void ClearData() + { + var factory = new EnvFreeSqlFactory(); + var fsq = factory.Create(""); + + fsq.Delete().Where("1=1").ExecuteAffrows(); + fsq.Delete().Where("1=1").ExecuteAffrows(); + fsq.Delete().Where("1=1").ExecuteAffrows(); + fsq.Delete().Where("1=1").ExecuteAffrows(); + fsq.Delete().Where("1=1").ExecuteAffrows(); + fsq.Delete().Where("1=1").ExecuteAffrows(); + fsq.Delete().Where("1=1").ExecuteAffrows(); + //fsq.Delete().Where("1=1").ExecuteAffrows(); + fsq.Delete().Where("1=1").ExecuteAffrows(); + } + public BasicTestService() { var config = new ConfigurationBuilder() @@ -36,9 +52,6 @@ public BasicTestService() .Build(); Global.Config = config; - var factory = new EnvFreeSqlFactory(); - _fsq = factory.Create(""); - var cache = new Mock(); IServiceCollection services = new ServiceCollection(); services.AddScoped(_ => cache.Object); @@ -54,41 +67,5 @@ public BasicTestService() Console.WriteLine("Run BasicTestService"); } - - private static void AddEnvRepositiroies(IServiceCollection sc) - { - sc.AddScoped>(sp => env => - { - var factory = sp.GetService(); - var fsq = factory.Create(env); - return new FreeSqlUow(fsq); - }); - - sc.AddScoped>(sp => env => - { - var factory = sp.GetService(); - return new ConfigPublishedRepository(factory.Create(env)); - }); - - sc.AddScoped>(sp => env => - { - var factory = sp.GetService(); - - return new ConfigRepository(factory.Create(env)); - }); - - sc.AddScoped>(sp => env => - { - var factory = sp.GetService(); - return new PublishDetailRepository(factory.Create(env)); - }); - - sc.AddScoped>(sp => env => - { - var factory = sp.GetService(); - return new PublishTimelineRepository(factory.Create(env)); - }); - } - } } diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs index 54938173..a9bbd474 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/ConfigServiceTests.cs @@ -9,6 +9,7 @@ using Microsoft.Extensions.Caching.Memory; using Moq; using Microsoft.Extensions.DependencyInjection; +using AgileConfig.Server.Data.Abstraction; namespace AgileConfig.Server.ServiceTests.sqlite { @@ -30,7 +31,7 @@ public override Dictionary GetConfigurationData() public void TestInitialize() { _service = _serviceProvider.GetService(); - _fsq.Delete().Where("1=1"); + this.ClearData(); } @@ -54,10 +55,7 @@ public async Task AddAsyncTest() var result = await _service.AddAsync(source, ""); Assert.IsTrue(result); - var config = _fsq.Select(new - { - Id = id - }).ToOne(); + var config = await _service.GetAsync(source.Id, ""); Assert.IsTrue(result); Assert.IsNotNull(config); @@ -106,10 +104,7 @@ public async Task UpdateAsyncTest() source.OnlineStatus = OnlineStatus.WaitPublish; var result1 = await _service.UpdateAsync(source, ""); - var config = _fsq.Select(new - { - Id = id - }).ToOne(); + var config = await _service.GetAsync(source.Id, ""); Assert.IsTrue(result1); Assert.IsNotNull(config); @@ -150,10 +145,7 @@ public async Task DeleteAsyncTest() var result1 = await _service.DeleteAsync(source, ""); Assert.IsTrue(result1); - var config = _fsq.Select(new - { - Id = id - }).ToOne(); + var config = await _service.GetAsync(source.Id, ""); Assert.IsNull(config); } @@ -182,10 +174,7 @@ public async Task DeleteAsyncTest1() var result1 = await _service.DeleteAsync(id, ""); Assert.IsTrue(result1); - var config = _fsq.Select(new - { - Id = id - }).ToOne(); + var config = await _service.GetAsync(source.Id, ""); Assert.IsNull(config); } @@ -229,7 +218,7 @@ public async Task GetAsyncTest() [TestMethod()] public async Task GetAllConfigsAsyncTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); var env = "DEV"; var id = Guid.NewGuid().ToString(); @@ -275,7 +264,8 @@ public async Task GetAllConfigsAsyncTest() [TestMethod()] public async Task GetByAppIdKeyTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); + var env = "DEV"; var id = Guid.NewGuid().ToString(); var source = new Config @@ -339,8 +329,7 @@ public async Task GetByAppIdKeyTest() [TestMethod()] public async Task GetByAppIdTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); - + this.ClearData(); var id = Guid.NewGuid().ToString(); var env = "DEV"; var source = new Config @@ -402,7 +391,7 @@ public async Task GetByAppIdTest() [TestMethod()] public async Task SearchTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); var env = "DEV"; var id = Guid.NewGuid().ToString(); var source = new Config @@ -470,7 +459,7 @@ public async Task SearchTest() [TestMethod()] public async Task CountEnabledConfigsAsyncTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); string env = "DEV"; var id = Guid.NewGuid().ToString(); @@ -485,7 +474,7 @@ public async Task CountEnabledConfigsAsyncTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online, + OnlineStatus = OnlineStatus.WaitPublish, Env = env }; var id1 = Guid.NewGuid().ToString(); @@ -500,7 +489,7 @@ public async Task CountEnabledConfigsAsyncTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online, + OnlineStatus = OnlineStatus.WaitPublish, Env = env }; var id2 = Guid.NewGuid().ToString(); @@ -515,16 +504,19 @@ public async Task CountEnabledConfigsAsyncTest() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online, + OnlineStatus = OnlineStatus.WaitPublish, Env = env }; - var result = await _service.AddAsync(source, ""); + var result = await _service.AddAsync(source, env); Assert.IsTrue(result); - var result1 = await _service.AddAsync(source1, ""); + var result1 = await _service.AddAsync(source1, env); Assert.IsTrue(result1); - var result2 = await _service.AddAsync(source2, ""); + var result2 = await _service.AddAsync(source2, env); Assert.IsTrue(result2); + await _service.Publish("001", new string[] { }, "", "", env); + await _service.Publish("002", new string[] { }, "", "", env); + var count = await _service.CountEnabledConfigsAsync(); Assert.AreEqual(1, count); } @@ -532,8 +524,9 @@ public async Task CountEnabledConfigsAsyncTest() [TestMethod()] public async Task AppPublishedConfigsMd5Test() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); + string env = "DEV"; var id = Guid.NewGuid().ToString(); var source = new Config { @@ -546,7 +539,8 @@ public async Task AppPublishedConfigsMd5Test() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Enabled, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; var id1 = Guid.NewGuid().ToString(); var source1 = new Config @@ -560,7 +554,9 @@ public async Task AppPublishedConfigsMd5Test() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env + }; var id2 = Guid.NewGuid().ToString(); var source2 = new Config @@ -574,16 +570,17 @@ public async Task AppPublishedConfigsMd5Test() CreateTime = DateTime.Now, UpdateTime = DateTime.Now, Status = ConfigStatus.Deleted, - OnlineStatus = OnlineStatus.Online + OnlineStatus = OnlineStatus.Online, + Env = env }; - var result = await _service.AddAsync(source, ""); + var result = await _service.AddAsync(source, env); Assert.IsTrue(result); - var result1 = await _service.AddAsync(source1, ""); + var result1 = await _service.AddAsync(source1, env); Assert.IsTrue(result1); - var result2 = await _service.AddAsync(source2, ""); + var result2 = await _service.AddAsync(source2, env); Assert.IsTrue(result2); - var md5 = await _service.AppPublishedConfigsMd5("001", ""); + var md5 = await _service.AppPublishedConfigsMd5("001", env); Assert.IsNotNull(md5); } @@ -595,7 +592,7 @@ public void AppPublishedConfigsMd5CacheTest() [TestMethod()] public async Task GetPublishedConfigsByAppIdTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); var id = Guid.NewGuid().ToString(); var source = new Config @@ -646,9 +643,6 @@ public async Task GetPublishedConfigsByAppIdTest() var result2 = await _service.AddAsync(source2, ""); Assert.IsTrue(result2); - //var configs = await service.GetPublishedConfigsByAppId("001"); - //Assert.IsNotNull(configs); - //Assert.AreEqual(1, configs.Count); } [TestMethod()] @@ -689,27 +683,16 @@ public async Task AddRangeAsyncTest() }, ""); Assert.IsTrue(result); - var config = _fsq.Select(new - { - Id = id - }).ToOne(); + var config = await _service.GetAsync(id, ""); Assert.IsNotNull(config); - var config1 = _fsq.Select(new - { - Id = id1 - }).ToOne(); + var config1 = await _service.GetAsync(id1, ""); Assert.IsNotNull(config1); } [TestMethod()] public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); - _fsq.Delete().Where("1=1").ExecuteAffrows(); - _fsq.Delete().Where("1=1").ExecuteAffrows(); - _fsq.Delete().Where("1=1").ExecuteAffrows(); - _fsq.Delete().Where("1=1").ExecuteAffrows(); - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); string env = "DEV"; @@ -788,15 +771,15 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() appref.Sort = 1; appref.Id = Guid.NewGuid().ToString(); - _fsq.Insert(app).ExecuteAffrows(); - _fsq.Insert(app1).ExecuteAffrows(); - _fsq.Insert(appref).ExecuteAffrows(); + await _serviceProvider.GetService().AddAsync(app); + await _serviceProvider.GetService().AddAsync(app1); + await _serviceProvider.GetService().InsertAsync(appref); // 插入4个config,2个app 001,2个app 002 - _fsq.Insert(source).ExecuteAffrows(); - _fsq.Insert(source1).ExecuteAffrows(); - _fsq.Insert(source2).ExecuteAffrows(); - _fsq.Insert(source3).ExecuteAffrows(); + await _service.AddAsync(source, env); + await _service.AddAsync(source1, env); + await _service.AddAsync(source2, env); + await _service.AddAsync(source3, env); await _service.Publish(app1.Id, new string[] { }, "", "", env); await _service.Publish(app.Id, new string[] { }, "", "", env); @@ -842,8 +825,8 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() Env = env }; // 插入2个config,1个app 001,1个app 002,keyvalue相同,app 001 优先级高 - _fsq.Insert(source4).ExecuteAffrows(); - _fsq.Insert(source5).ExecuteAffrows(); + await _service.AddAsync(source4, env); + await _service.AddAsync(source5, env); await _service.Publish(app1.Id, new string[] { }, "", "", env); await _service.Publish(app.Id, new string[] { }, "", "", env); @@ -862,17 +845,17 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() app2.CreateTime = DateTime.Now; app2.UpdateTime = DateTime.Now; app2.Type = AppType.Inheritance; - _fsq.Insert(app2).ExecuteAffrows(); + await _serviceProvider.GetService().AddAsync(app2); // 插入1个app 003 - _fsq.Delete().Where("1=1").ExecuteAffrows(); + await _serviceProvider.GetService().DeleteAsync(appref); var appref1 = new AppInheritanced(); appref1.AppId = app.Id; appref1.InheritancedAppId = app2.Id; // app 001 继承 app 003 appref1.Sort = 2; appref1.Id = Guid.NewGuid().ToString(); - _fsq.Insert(appref1).ExecuteAffrows(); + await _serviceProvider.GetService().InsertAsync(appref1); var source6 = new Config { @@ -887,7 +870,7 @@ public async Task GetPublishedConfigsByAppIdWithInheritanced_DictionaryTest() OnlineStatus = OnlineStatus.WaitPublish, Env = env }; - _fsq.Insert(source6).ExecuteAffrows(); + await _service.AddAsync(source6, env); await _service.Publish(app2.Id, new string[] { }, "", "", env); // 发布app 003 dict = await _service.GetPublishedConfigsByAppIdWithInheritanced_Dictionary(app.Id, env); diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs index dec1baa8..315daa49 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/ServerNodeServiceTests.cs @@ -27,13 +27,13 @@ public override Dictionary GetConfigurationData() public void TestInitialize() { _serverNodeService = _serviceProvider.GetService(); - _fsq.Delete().Where("1=1"); + this.ClearData(); } [TestMethod()] public async Task AddAsyncTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); var source = new ServerNode(); source.Id = "1"; @@ -45,10 +45,7 @@ public async Task AddAsyncTest() var result = await _serverNodeService.AddAsync(source); Assert.IsTrue(result); - var node = _fsq.Select(new - { - Address = "1" - }).ToOne(); + var node = await _serverNodeService.GetAsync("1"); Assert.IsNotNull(node); Assert.AreEqual(source.Id, node.Id); @@ -61,7 +58,7 @@ public async Task AddAsyncTest() [TestMethod()] public async Task DeleteAsyncTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); var source = new ServerNode(); source.Id = "1"; @@ -76,17 +73,15 @@ public async Task DeleteAsyncTest() var result1 = await _serverNodeService.DeleteAsync(source); Assert.IsTrue(result1); - var node = _fsq.Select(new - { - Address = "1" - }).ToOne(); + var node = await _serverNodeService.GetAsync("1"); + Assert.IsNull(node); } [TestMethod()] public async Task DeleteAsyncTest1() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); var source = new ServerNode(); source.Id = "1"; @@ -101,17 +96,15 @@ public async Task DeleteAsyncTest1() var result1 = await _serverNodeService.DeleteAsync(source.Id); Assert.IsTrue(result1); - var node = _fsq.Select(new - { - Address = "1" - }).ToOne(); + var node = await _serverNodeService.GetAsync("1"); + Assert.IsNull(node); } [TestMethod()] public async Task GetAllNodesAsyncTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); var source = new ServerNode(); source.Id = "1"; @@ -132,7 +125,7 @@ public async Task GetAllNodesAsyncTest() [TestMethod()] public async Task GetAsyncTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); var source = new ServerNode(); source.Id = "1"; @@ -156,7 +149,7 @@ public async Task GetAsyncTest() [TestMethod()] public async Task UpdateAsyncTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); var source = new ServerNode(); source.Id = "1"; diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/SettingServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/SettingServiceTests.cs index be5b515d..52eb9dfa 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/SettingServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/SettingServiceTests.cs @@ -26,7 +26,7 @@ public override Dictionary GetConfigurationData() public void TestInitialize() { _settingService = _serviceProvider.GetService(); - _fsq.Delete().Where("1=1"); + this.ClearData(); } @@ -41,10 +41,7 @@ public async Task AddAsyncTest() var result = await _settingService.AddAsync(source); Assert.IsTrue(result); - var setting = _fsq.Select(new - { - Id = id - }).ToOne(); + var setting = await _settingService.GetAsync(source.Id); Assert.IsNotNull(setting); @@ -66,10 +63,7 @@ public async Task DeleteAsyncTest() result = await _settingService.DeleteAsync(source); Assert.IsTrue(result); - var setting = _fsq.Select(new - { - Id = id - }).ToOne(); + var setting = await _settingService.GetAsync(source.Id); Assert.IsNull(setting); } @@ -88,10 +82,7 @@ public async Task DeleteAsyncTest1() result = await _settingService.DeleteAsync(id); Assert.IsTrue(result); - var setting = _fsq.Select(new - { - Id = id - }).ToOne(); + var setting = await _settingService.GetAsync(source.Id); Assert.IsNull(setting); } @@ -118,8 +109,9 @@ public async Task GetAsyncTest() [TestMethod()] public async Task GetAllSettingsAsyncTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); - var id = Guid.NewGuid().ToString(); + this.ClearData(); + + var id = Guid.NewGuid().ToString(); var source = new Setting(); source.Id = id; source.Value = "123"; @@ -137,8 +129,6 @@ public async Task GetAllSettingsAsyncTest() var settings = await _settingService.GetAllSettingsAsync(); Assert.IsNotNull(settings); - - Assert.AreEqual(2, settings.Count); } [TestMethod()] diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs index ade1033b..877798c6 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs @@ -7,6 +7,7 @@ using AgileConfig.Server.IService; using Microsoft.Extensions.DependencyInjection; using MongoDB.Driver.Linq; +using AgileConfig.Server.Data.Abstraction; namespace AgileConfig.Server.ServiceTests.sqlite { @@ -28,8 +29,8 @@ public override Dictionary GetConfigurationData() public void TestInitialize() { _syslogservice = _serviceProvider.GetService(); - _fsq.Delete().Where("1=1"); - } + this.ClearData(); + } [TestMethod()] @@ -46,10 +47,7 @@ public async Task AddSysLogAsyncTest() var result = await _syslogservice.AddSysLogAsync(source); Assert.IsTrue(result); - var log = _fsq.Select(new - { - source.Id - }).ToOne(); + var log = await _serviceProvider.GetService().GetAsync(source.Id); Assert.IsNotNull(log); @@ -83,10 +81,8 @@ public async Task AddRangeAsyncTest() }); Assert.IsTrue(result); - var log = _fsq.Select(new - { - source.Id - }).ToOne(); + var log = await _serviceProvider.GetService().GetAsync(source.Id); + Assert.IsNotNull(log); Assert.AreEqual(source.Id, log.Id); Assert.AreEqual(source.AppId, log.AppId); @@ -94,10 +90,8 @@ public async Task AddRangeAsyncTest() Assert.AreEqual(source.LogTime.Value.ToString("yyyyMMddHHmmss"), log.LogTime.Value.ToString("yyyyMMddHHmmss")); Assert.AreEqual(source.LogText, log.LogText); - var log1 = _fsq.Select(new - { - source1.Id - }).ToOne(); + var log1 = await _serviceProvider.GetService().GetAsync(source1.Id); + Assert.IsNotNull(log1); Assert.AreEqual(source1.Id, log1.Id); Assert.AreEqual(source1.AppId, log1.AppId); @@ -110,8 +104,8 @@ public async Task AddRangeAsyncTest() [TestMethod()] public async Task CountTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); - + this.ClearData(); + var source = new SysLog { AppId = "001", @@ -141,7 +135,7 @@ public async Task CountTest() [TestMethod()] public async Task SearchPageTest() { - _fsq.Delete().Where("1=1").ExecuteAffrows(); + this.ClearData(); var source = new SysLog { @@ -157,11 +151,17 @@ public async Task SearchPageTest() LogTime = DateTime.Now, LogText = "124" }; - var result = await _syslogservice.AddRangeAsync(new List { - source, source1 - }); + var result = await _syslogservice.AddSysLogAsync(source); + Assert.IsTrue(result); + result = await _syslogservice.AddSysLogAsync(source1); Assert.IsTrue(result); + var log = await _serviceProvider.GetService().GetAsync(source.Id); + Assert.IsNotNull(log); + + var log1 = await _serviceProvider.GetService().GetAsync(source1.Id); + Assert.IsNotNull(log1); + var page = await _syslogservice.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1), 1, 0); Assert.AreEqual(1, page.Count); From 6da6f614f4e56f80b8d913531825d4227e80c50f Mon Sep 17 00:00:00 2001 From: "agile.zhou" Date: Sun, 21 Jan 2024 20:46:04 +0800 Subject: [PATCH 45/45] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E7=94=A8=E4=BE=8B?= =?UTF-8?q?=E9=80=82=E9=85=8D=20mongodb=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../appsettings.Development.json | 8 ++--- .../mongodb/ConfigServiceTests.cs | 31 ++++++++++++++++++- .../sqlite/SysLogServiceTests.cs | 4 +-- 3 files changed, 36 insertions(+), 7 deletions(-) diff --git a/src/AgileConfig.Server.Apisite/appsettings.Development.json b/src/AgileConfig.Server.Apisite/appsettings.Development.json index 6271b2e5..29e675c4 100644 --- a/src/AgileConfig.Server.Apisite/appsettings.Development.json +++ b/src/AgileConfig.Server.Apisite/appsettings.Development.json @@ -16,8 +16,8 @@ "cluster": false, // 集群模式:服务启动后自动加入节点列表,服务启动的时候会获取容器的ip,端口默认5000,适合 docker compose 环境使用 "preview_mode": false, "db": { - //"provider": "sqlite", //sqlite,mysql,sqlserver,npgsql,oracle,mongodb - //"conn": "Data Source=agile_config.db", + "provider": "sqlite", //sqlite,mysql,sqlserver,npgsql,oracle,mongodb + "conn": "Data Source=agile_config.db", //"provider": "sqlserver", //"conn": "Encrypt=True;TrustServerCertificate=True;Persist Security Info = False; User ID =dev; Password =dev@123; Initial Catalog =agile_config; Server =192.168.18.82" //"provider": "npgsql", @@ -26,8 +26,8 @@ //"conn": "user id=x;password=x;data source=192.168.0.123/orcl" //"provider": "mysql", //"conn": "Database=agile_config;Data Source=192.168.0.125;User Id=root;Password=x;port=13306;Allow User Variables=true;", - "provider": "mongodb", - "conn": "mongodb://192.168.0.125:27017/agile_config_1", + //"provider": "mongodb", + //"conn": "mongodb://192.168.0.125:27017/agile_config_1", "env": { "TEST": { "provider": "sqlite", //sqlite,mysql,sqlserver,npgsql,oracle diff --git a/test/AgileConfig.Server.ServiceTests/mongodb/ConfigServiceTests.cs b/test/AgileConfig.Server.ServiceTests/mongodb/ConfigServiceTests.cs index c3a929f1..7280118f 100644 --- a/test/AgileConfig.Server.ServiceTests/mongodb/ConfigServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/mongodb/ConfigServiceTests.cs @@ -1,4 +1,5 @@ -using AgileConfig.Server.Data.Repository.Mongodb; +using AgileConfig.Server.Data.Entity; +using AgileConfig.Server.Data.Repository.Mongodb; using AgileConfig.Server.ServiceTests.sqlite; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; @@ -16,6 +17,34 @@ public override void ClearData() { repository.DeleteAsync(entity).Wait(); } + + var configPublishedRepository = new ConfigPublishedRepository(conn); + var configPublisheds = configPublishedRepository.AllAsync().Result; + foreach (var entity in configPublisheds) + { + configPublishedRepository.DeleteAsync(entity).Wait(); + } + + var detailRepository = new PublishDetailRepository(conn); + var details = detailRepository.AllAsync().Result; + foreach (var entity in details) + { + detailRepository.DeleteAsync(entity).Wait(); + } + + var app_repository = new AppRepository(conn); + var apps = app_repository.AllAsync().Result; + foreach (var entity in apps) + { + app_repository.DeleteAsync(entity).Wait(); + } + + var appref_repository = new AppInheritancedRepository(conn); + var apprefs = appref_repository.AllAsync().Result; + foreach (var entity in apprefs) + { + appref_repository.DeleteAsync(entity).Wait(); + } } string conn = "mongodb://192.168.0.125:27017/agile_config_1"; diff --git a/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs b/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs index 877798c6..07986793 100644 --- a/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs +++ b/test/AgileConfig.Server.ServiceTests/sqlite/SysLogServiceTests.cs @@ -162,10 +162,10 @@ public async Task SearchPageTest() var log1 = await _serviceProvider.GetService().GetAsync(source1.Id); Assert.IsNotNull(log1); - var page = await _syslogservice.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1), 1, 0); + var page = await _syslogservice.SearchPage("001", SysLogType.Normal, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(1), 1, 1); Assert.AreEqual(1, page.Count); - var page1 = await _syslogservice.SearchPage("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), 1, 0); + var page1 = await _syslogservice.SearchPage("002", SysLogType.Warn, DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), 1, 1); Assert.AreEqual(0, page1.Count); } }