From 051ca6cb3f9d2960c1efedbb6b9a3b28f3b49e84 Mon Sep 17 00:00:00 2001 From: duia <532977252@qq.com> Date: Tue, 9 Apr 2024 15:06:44 +0800 Subject: [PATCH] feat:remove sdks --- Masa.Framework.sln | 472 ----------- ....Configuration.ConfigurationApi.Dcc.csproj | 2 +- .../AlertClient.cs | 17 - .../Masa.Contrib.StackSdks.Alert/Constants.cs | 6 - .../Masa.Contrib.StackSdks.Alert.csproj | 15 - .../Service/AlarmHistoryService.cs | 27 - .../Service/AlarmRuleService.cs | 45 - .../ServiceCollectionExtensions.cs | 56 -- .../Masa.Contrib.StackSdks.Alert/_Imports.cs | 12 - .../Masa.Contrib.StackSdks.Auth/AuthClient.cs | 33 - .../Masa.Contrib.StackSdks.Auth/Constants.cs | 12 - .../Masa.Contrib.StackSdks.Auth.csproj | 27 - .../AuthClientMultilevelCacheProvider.cs | 24 - .../Masa.Contrib.StackSdks.Auth/README.md | 46 -- .../README.zh-CN.md | 45 - .../Service/CustomLoginService.cs | 20 - .../Service/LoginService.cs | 133 --- .../Service/PermissionService.cs | 74 -- .../Service/ProjectService.cs | 25 - .../Service/SubjectService.cs | 21 - .../Service/TeamService.cs | 47 -- .../Service/ThirdPartyIdpService.cs | 34 - .../Service/UserService.cs | 415 ---------- .../ServiceCollectionExtensions.cs | 91 -- .../Masa.Contrib.StackSdks.Auth/SsoClient.cs | 15 - .../Masa.Contrib.StackSdks.Auth/_Imports.cs | 24 - .../AuthenticationService.cs | 34 - .../Masa.Contrib.StackSdks.Caller/Constant.cs | 9 - .../Generater/DefaultTokenGenerater.cs | 34 - .../Generater/ITokenGenerater.cs | 9 - .../Jwt/ClientRefreshTokenOptions.cs | 11 - .../Jwt/JwtTokenValidator.cs | 113 --- .../Jwt/JwtTokenValidatorOptions.cs | 17 - .../Masa.Contrib.StackSdks.Caller.csproj | 21 - .../MasaCallerClientBuilderExtensions.cs | 33 - .../ServiceCollectionExtensions.cs | 30 - .../StackHttpClientCaller.cs | 17 - .../TokenProvider.cs | 13 - .../Masa.Contrib.StackSdks.Caller/_Imports.cs | 22 - .../Constants.cs | 11 - .../HttpProtocol.cs | 11 - .../Masa.Contrib.StackSdks.Config.csproj | 21 - .../MasaStackApp.cs | 17 - .../MasaStackConfig.cs | 82 -- .../MasaStackConfigExtensions.cs | 136 --- .../MasaStackConfigOptions.cs | 29 - .../MasaStackConfigUtils.cs | 49 -- .../MasaStackProject.cs | 20 - .../MultiEnvironmentMasaStackConfig.cs | 46 -- .../ServiceCollectionExtensions.cs | 119 --- .../StringExtensions.cs | 13 - .../Masa.Contrib.StackSdks.Config/_Imports.cs | 17 - .../Masa.Contrib.StackSdks.Dcc/DccClient.cs | 14 - .../Internal/Constants.cs | 9 - .../Masa.Contrib.StackSdks.Dcc.csproj | 14 - .../Masa.Contrib.StackSdks.Dcc/README.md | 54 -- .../README.zh-CN.md | 54 -- .../Service/LabelService.cs | 21 - .../ServiceCollectionExtensions.cs | 49 -- .../Masa.Contrib.StackSdks.Dcc/_Imports.cs | 12 - .../ApplicationBuilderExtensions.cs | 14 - .../DccConfigurationIsolationRepository.cs | 90 -- .../EnvironmentCallerMiddleware.cs | 42 - .../EnvironmentMiddleware.cs | 24 - .../EnvironmentModel.cs | 9 - .../EsIsolationConfigProvider.cs | 63 -- .../IsolationConfigurationApi.cs | 42 - .../Masa.Contrib.StackSdks.Isolation.csproj | 19 - .../MasaConfigurationBuilderExtensions.cs | 74 -- .../MasaConfigurationIsolationProvider.cs | 54 -- .../MasaConfigurationIsolationSource.cs | 16 - .../ServiceCollectionExtensions.cs | 229 ----- .../_Imports.cs | 36 - .../Masa.Contrib.StackSdks.Mc/Constants.cs | 10 - .../Extensions/DictionaryExtensions.cs | 125 --- .../Extensions/ExtraPropertiesExtensions.cs | 61 -- .../Infrastructure/Helper/TypeHelper.cs | 170 ---- .../Masa.Contrib.StackSdks.Mc.csproj | 19 - .../Masa.Contrib.StackSdks.Mc/McClient.cs | 26 - .../Service/ChannelService.cs | 33 - .../Service/MessageTaskService.cs | 87 -- .../Service/MessageTemplateService.cs | 27 - .../Service/ReceiverGroupService.cs | 27 - .../Service/WebsiteMessageService.cs | 85 -- .../ServiceCollectionExtensions.cs | 58 -- .../Masa.Contrib.StackSdks.Mc/_Imports.cs | 18 - .../ApplicationBuilderExtensions.cs | 23 - .../DefaultDisabledEventDeterminer.cs | 24 - .../DefaultDisabledRequestDeterminer.cs | 19 - .../DisabledEventMiddleware.cs | 33 - .../DisabledRequestMiddleware.cs | 29 - .../Masa.Contrib.StackSdks.Middleware.csproj | 28 - .../README.md | 35 - .../README.zh-CN.md | 35 - .../ServiceCollectionExtensions.cs | 24 - .../_Imports.cs | 17 - .../Masa.Contrib.StackSdks.Pm/Constants.cs | 9 - .../Masa.Contrib.StackSdks.Pm.csproj | 15 - .../Masa.Contrib.StackSdks.Pm/PmClient.cs | 25 - .../Masa.Contrib.StackSdks.Pm/README.md | 38 - .../Masa.Contrib.StackSdks.Pm/README.zh-CN.md | 38 - .../Service/AppService.cs | 62 -- .../Service/ClusterService.cs | 46 -- .../Service/EnvironmentService.cs | 30 - .../Service/ProjectService.cs | 70 -- .../ServiceCollectionExtensions.cs | 55 -- .../Masa.Contrib.StackSdks.Pm/_Imports.cs | 11 - .../Constants.cs | 10 - ...ttpClientAuthorizationDelegatingHandler.cs | 24 - .../Logger/SchedulerLogger.cs | 48 -- .../Masa.Contrib.StackSdks.Scheduler.csproj | 20 - .../README.md | 41 - .../README.zh-CN.md | 41 - .../SchedulerClient.cs | 17 - .../SchedulerJob.cs | 34 - .../ServiceCollectionExtensions.cs | 57 -- .../Services/SchedulerJobService.cs | 96 --- .../Services/SchedulerTaskService.cs | 43 - .../_Imports.cs | 21 - .../ApmClickhouseServiceExtensions.cs | 77 -- .../Cliclhouse/ClickhouseApmService.cs | 646 --------------- .../Config/Constants.cs | 31 - .../Interfaces/IAPMService.cs | 62 -- ...ontrib.StackSdks.Tsc.Apm.Clickhouse.csproj | 15 - .../Models/APMEnums.cs | 10 - .../Models/Request/ApmEndpointRequestDto.cs | 9 - .../Request/ApmTraceLatencyRequestDto.cs | 19 - .../Models/Request/BaseApmRequestDto.cs | 35 - .../Models/Response/EndpointChartDto.cs | 28 - .../EndpointLatencyDistributionDto.cs | 11 - .../Models/Response/EndpointListDto.cs | 21 - .../Models/Response/ServiceListDto.cs | 66 -- .../_Imports.cs | 20 - .../Extensions/IDbConnectionExtensitions.cs | 537 ------------ .../MasaTscCliclhouseExtensitions.cs | 274 ------ .../LogService.cs | 28 - ...sa.Contrib.StackSdks.Tsc.Clickhouse.csproj | 21 - .../Model/MASAStackClickhouseConnection.cs | 56 -- .../PublishProfiles/FolderProfile.pubxml | 13 - .../TraceService.cs | 39 - .../_Imports.cs | 21 - .../Constants/ElasticConstant.cs | 40 - .../Constants/LogTraceSetting.cs | 25 - .../Constants/MappingConstant.cs | 16 - .../Converters/LogResponseDtoConverter.cs | 35 - .../Converters/TraceResponseDtoConverter.cs | 35 - .../Extenistions/IElasticClientExtenstion.cs | 504 ----------- .../Extenistions/JsonElementExtensions.cs | 75 -- .../Extenistions/ServiceExtenistion.cs | 139 ---- .../LogService.cs | 31 - ...Contrib.StackSdks.Tsc.Elasticsearch.csproj | 19 - .../Model/ElasticseachLogResponseDto.cs | 10 - .../Model/ElasticseacherMappingResponse.cs | 17 - .../Scroll/ElasticsearchScrollRequestDto.cs | 11 - .../Scroll/ElasticsearchScrollResponseDto.cs | 9 - .../Trace/ElasticseachTraceResponseDto.cs | 13 - .../TraceService.cs | 41 - .../_Imports.cs | 22 - .../Extensions/ServiceExtensions.cs | 74 -- .../Extensions/StreamExtensions.cs | 57 -- .../Logging/ServiceExtensions.cs | 19 - ...Contrib.StackSdks.Tsc.OpenTelemetry.csproj | 22 - .../Instrumentation/Http/HttpResponseMeter.cs | 31 - .../Instrumentation/Http/IHttpMetric.cs | 39 - .../Metric/ServiceExtensions.cs | 25 - .../Middleware/HttpResponseMiddleware.cs | 37 - .../Options/MasaObservableOptions.cs | 19 - .../Options/OpenTelemetryAttributeName.cs | 166 ---- .../ResourceBuilderExtenstions.cs | 30 - .../Traceing/ActivityExtensions.cs | 128 --- ...NetCoreInstrumentationOptionsExtensions.cs | 95 --- .../AspNetCoreInstrumentationHandler.cs | 19 - .../Traceing/Handler/ExceptionHandler.cs | 18 - .../Handler/HttpClientInstrumentHandler.cs | 29 - .../Traceing/Handler/HttpMetricProviders.cs | 106 --- .../OpenTelemetryInstrumentationOptions.cs | 99 --- .../Traceing/ServiceExtensions.cs | 57 -- .../_Imports.cs | 37 - .../Extensions/CallerProviderExtensions.cs | 19 - .../Extensions/ServiceExtensions.cs | 37 - .../Masa.Contrib.StackSdks.Tsc.csproj | 14 - .../Masa.Contrib.StackSdks.Tsc/README.md | 56 -- .../README.zh-CN.md | 56 -- .../Service/LogService.cs | 37 - .../Service/MetricService.cs | 46 -- .../Masa.Contrib.StackSdks.Tsc/TscClient.cs | 18 - .../Masa.Contrib.StackSdks.Tsc/_Imports.cs | 16 - .../AlarmRuleServiceTest.cs | 46 -- .../AlertClientTest.cs | 32 - .../Masa.Contrib.StackSdks.Alert.Tests.csproj | 28 - .../Usings.cs | 4 - .../_Imports.cs | 11 - .../AuthClientTest.cs | 35 - .../CustomLoginServiceTest.cs | 21 - .../LoginServiceTest.cs | 49 -- .../Masa.Contrib.StackSdks.Auth.Tests.csproj | 30 - .../PermissionServiceTest.cs | 107 --- .../ProjectServiceTest.cs | 28 - .../SsoClientTest.cs | 19 - .../SubjectServiceTest.cs | 26 - .../TeamServiceTest.cs | 54 -- .../ThirdPartyIdpServiceTest.cs | 46 -- .../UserServiceTest.cs | 780 ------------------ .../_Imports.cs | 18 - ...Masa.Contrib.StackSdks.Config.Tests.csproj | 37 - .../MasaStackConfigTest.cs | 187 ----- .../_Imports.cs | 8 - .../appsettings.json | 16 - .../DccClientTest.cs | 52 -- .../LabelServiceTest.cs | 44 - .../Masa.Contrib.StackSdks.Dcc.Tests.csproj | 43 - .../_Imports.cs | 12 - .../appsettings.json | 14 - .../ChannelServiceTest.cs | 48 -- .../Masa.Contrib.StackSdks.Mc.Tests.csproj | 28 - .../McClientTest.cs | 32 - .../MessageTaskServiceTest.cs | 109 --- .../MessageTemplateServiceTest.cs | 36 - .../ReceiverGroupServiceTest.cs | 36 - .../WebsiteMessageServiceTest.cs | 110 --- .../_Imports.cs | 13 - .../Application/Handler.cs | 27 - .../Application/TestAllowCommand.cs | 10 - .../Application/TestCommand.cs | 8 - .../Application/TestQuery.cs | 9 - .../EventMiddlewareTest.cs | 91 -- ....Contrib.StackSdks.Middleware.Tests.csproj | 42 - .../RequestMiddlewareTest.cs | 88 -- .../_Imports.cs | 22 - .../appsettings.json | 15 - .../AppServiceTest.cs | 219 ----- .../ClusterServiceTest.cs | 149 ---- .../EnvironmentServiceTest.cs | 77 -- .../Masa.Contrib.StackSdks.Pm.Tests.csproj | 28 - .../PmClientTest.cs | 69 -- .../ProjectServiceTest.cs | 247 ------ .../_Imports.cs | 13 - ...a.Contrib.StackSdks.Scheduler.Tests.csproj | 28 - .../SchedulerClientTest.cs | 51 -- .../SchedulerJobServiceTest.cs | 301 ------- .../SchedulerTaskServiceTest.cs | 66 -- .../_Imports.cs | 11 - .../ClickhouseApmServiceTests.cs | 143 ---- .../Data/otel_trace_data.json | 266 ------ ....StackSdks.Tsc.Apm.Clickhouse.Tests.csproj | 28 - .../TestUtils.cs | 10 - .../_Imports.cs | 11 - .../Common.cs | 93 --- .../Consts.cs | 10 - .../Data/otel_log.txt | 57 -- .../Data/otel_log_data.txt | 5 - .../Data/otel_trace.txt | 69 -- .../Data/otel_trace_data.txt | 5 - .../LogServiceTests.cs | 91 -- ...trib.StackSdks.Tsc.Clickhouse.Tests.csproj | 55 -- .../TraceServiceTests.cs | 82 -- .../_Imports.cs | 13 - .../Converts/LogConverterTests.cs | 27 - .../Converts/TraceConverterTests.cs | 30 - .../Extensions/DictionaryExtenistionsTests.cs | 25 - .../Extensions/JsonElementExtensionsTests.cs | 50 -- .../Extensions/ServiceExtenistionTests.cs | 137 --- ...b.StackSdks.Tsc.Elasticsearch.Tests.csproj | 36 - .../Service/LogServiceTests.cs | 261 ------ .../Service/TraceServiceTests.cs | 140 ---- .../StaticConfig.cs | 40 - .../_Imports.cs | 17 - .../testData.json | 16 - .../Extensions/ServiceExtensionsTests.cs | 48 -- .../Extensions/SteamTests.cs | 51 -- .../Logging/LoggingTests.cs | 38 - ...b.StackSdks.Tsc.OpenTelemetry.Tests.csproj | 47 -- .../Metric/MetricTests.cs | 26 - .../ObservableHelper.cs | 20 - .../Trace/ActivityTest.cs | 94 --- .../Trace/TraceTests.cs | 34 - .../_Imports.cs | 21 - .../appsettings.json | 10 - .../CallerProviderExtensionsTests.cs | 21 - .../Masa.Contrib.StackSdks.Tsc.Tests.csproj | 28 - .../Service/LogServiceTests.cs | 94 --- .../Service/MetricServiceTests.cs | 86 -- .../_Imports.cs | 19 - 283 files changed, 1 insertion(+), 16045 deletions(-) delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/AlertClient.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Constants.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Masa.Contrib.StackSdks.Alert.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Service/AlarmHistoryService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Service/AlarmRuleService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/ServiceCollectionExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/AuthClient.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Constants.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Masa.Contrib.StackSdks.Auth.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Model/AuthClientMultilevelCacheProvider.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/README.md delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/README.zh-CN.md delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/CustomLoginService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/LoginService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/PermissionService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/ProjectService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/SubjectService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/TeamService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/ThirdPartyIdpService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/UserService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/ServiceCollectionExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/SsoClient.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/AuthenticationService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Constant.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Generater/DefaultTokenGenerater.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Generater/ITokenGenerater.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Jwt/ClientRefreshTokenOptions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Jwt/JwtTokenValidator.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Jwt/JwtTokenValidatorOptions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Masa.Contrib.StackSdks.Caller.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/MasaCallerClientBuilderExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/ServiceCollectionExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/StackHttpClientCaller.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/TokenProvider.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/Constants.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/HttpProtocol.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/Masa.Contrib.StackSdks.Config.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackApp.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfig.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfigExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfigOptions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfigUtils.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackProject.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MultiEnvironmentMasaStackConfig.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/ServiceCollectionExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/StringExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/DccClient.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/Internal/Constants.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/Masa.Contrib.StackSdks.Dcc.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/README.md delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/README.zh-CN.md delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/Service/LabelService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/ServiceCollectionExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/ApplicationBuilderExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/DccConfigurationIsolationRepository.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EnvironmentCallerMiddleware.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EnvironmentMiddleware.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EnvironmentModel.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EsIsolationConfigProvider.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/IsolationConfigurationApi.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/Masa.Contrib.StackSdks.Isolation.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/MasaConfigurationBuilderExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/MasaConfigurationIsolationProvider.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/MasaConfigurationIsolationSource.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/ServiceCollectionExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Constants.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Infrastructure/Extensions/DictionaryExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Infrastructure/Extensions/ExtraPropertiesExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Infrastructure/Helper/TypeHelper.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Masa.Contrib.StackSdks.Mc.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/McClient.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/ChannelService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/MessageTaskService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/MessageTemplateService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/ReceiverGroupService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/WebsiteMessageService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/ServiceCollectionExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/ApplicationBuilderExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DefaultDisabledEventDeterminer.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DefaultDisabledRequestDeterminer.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DisabledEventMiddleware.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DisabledRequestMiddleware.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/Masa.Contrib.StackSdks.Middleware.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/README.md delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/README.zh-CN.md delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/ServiceCollectionExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Constants.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Masa.Contrib.StackSdks.Pm.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/PmClient.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/README.md delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/README.zh-CN.md delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/AppService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/ClusterService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/EnvironmentService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/ProjectService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/ServiceCollectionExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Constants.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/HttpClientAuthorizationDelegatingHandler.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Logger/SchedulerLogger.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Masa.Contrib.StackSdks.Scheduler.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/README.md delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/README.zh-CN.md delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/SchedulerClient.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/SchedulerJob.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/ServiceCollectionExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Services/SchedulerJobService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Services/SchedulerTaskService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/ApmClickhouseServiceExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Cliclhouse/ClickhouseApmService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Config/Constants.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Interfaces/IAPMService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/APMEnums.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Request/ApmEndpointRequestDto.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Request/ApmTraceLatencyRequestDto.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Request/BaseApmRequestDto.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/EndpointChartDto.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/EndpointLatencyDistributionDto.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/EndpointListDto.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/ServiceListDto.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Extensions/IDbConnectionExtensitions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Extensions/MasaTscCliclhouseExtensitions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/LogService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Masa.Contrib.StackSdks.Tsc.Clickhouse.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Model/MASAStackClickhouseConnection.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Properties/PublishProfiles/FolderProfile.pubxml delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/TraceService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Constants/ElasticConstant.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Constants/LogTraceSetting.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Constants/MappingConstant.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Converters/LogResponseDtoConverter.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Converters/TraceResponseDtoConverter.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Extenistions/IElasticClientExtenstion.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Extenistions/JsonElementExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Extenistions/ServiceExtenistion.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/LogService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Masa.Contrib.StackSdks.Tsc.Elasticsearch.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/ElasticseachLogResponseDto.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/ElasticseacherMappingResponse.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/Scroll/ElasticsearchScrollRequestDto.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/Scroll/ElasticsearchScrollResponseDto.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/Trace/ElasticseachTraceResponseDto.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/TraceService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Extensions/ServiceExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Extensions/StreamExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Logging/ServiceExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Metric/Instrumentation/Http/HttpResponseMeter.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Metric/Instrumentation/Http/IHttpMetric.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Metric/ServiceExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Middleware/HttpResponseMiddleware.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Options/MasaObservableOptions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Options/OpenTelemetryAttributeName.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/ResourceBuilder/ResourceBuilderExtenstions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/ActivityExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/AspNetCoreInstrumentationOptionsExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/AspNetCoreInstrumentationHandler.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/ExceptionHandler.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/HttpClientInstrumentHandler.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/HttpMetricProviders.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/OpenTelemetryInstrumentationOptions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/ServiceExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Extensions/CallerProviderExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Extensions/ServiceExtensions.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Masa.Contrib.StackSdks.Tsc.csproj delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/README.md delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/README.zh-CN.md delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Service/LogService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Service/MetricService.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/TscClient.cs delete mode 100644 src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/AlarmRuleServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/AlertClientTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/Masa.Contrib.StackSdks.Alert.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/Usings.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/AuthClientTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/CustomLoginServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/LoginServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/Masa.Contrib.StackSdks.Auth.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/PermissionServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/ProjectServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/SsoClientTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/SubjectServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/TeamServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/ThirdPartyIdpServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/UserServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/Masa.Contrib.StackSdks.Config.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/MasaStackConfigTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/appsettings.json delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/DccClientTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/LabelServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/Masa.Contrib.StackSdks.Dcc.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/appsettings.json delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/ChannelServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/Masa.Contrib.StackSdks.Mc.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/McClientTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/MessageTaskServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/MessageTemplateServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/ReceiverGroupServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/WebsiteMessageServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/Handler.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/TestAllowCommand.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/TestCommand.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/TestQuery.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/EventMiddlewareTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Masa.Contrib.StackSdks.Middleware.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/RequestMiddlewareTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/appsettings.json delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/AppServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/ClusterServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/EnvironmentServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/Masa.Contrib.StackSdks.Pm.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/PmClientTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/ProjectServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/Masa.Contrib.StackSdks.Scheduler.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/SchedulerClientTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/SchedulerJobServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/SchedulerTaskServiceTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/ClickhouseApmServiceTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/Data/otel_trace_data.json delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/TestUtils.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Common.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Consts.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_log.txt delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_log_data.txt delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_trace.txt delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_trace_data.txt delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/LogServiceTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/TraceServiceTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Converts/LogConverterTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Converts/TraceConverterTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Extensions/DictionaryExtenistionsTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Extensions/JsonElementExtensionsTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Extensions/ServiceExtenistionTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Service/LogServiceTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Service/TraceServiceTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/StaticConfig.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/testData.json delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Extensions/ServiceExtensionsTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Extensions/SteamTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Logging/LoggingTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Metric/MetricTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/ObservableHelper.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Trace/ActivityTest.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Trace/TraceTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/_Imports.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/appsettings.json delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Extensions/CallerProviderExtensionsTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Masa.Contrib.StackSdks.Tsc.Tests.csproj delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Service/LogServiceTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Service/MetricServiceTests.cs delete mode 100644 src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/_Imports.cs diff --git a/Masa.Framework.sln b/Masa.Framework.sln index bae963363..866922a49 100644 --- a/Masa.Framework.sln +++ b/Masa.Framework.sln @@ -45,8 +45,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SearchEngine", "SearchEngin EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Service", "Service", "{76F1DBC4-1826-4EC6-92BA-FF7843D993CD}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "StackSdks", "StackSdks", "{8A9DBB76-6618-4982-87D7-6CBD8375EB15}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Mapping", "Mapping", "{0DC9DE6E-E6D8-466A-8325-93822428CB87}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.Data.Mapping", "src\BuildingBlocks\Data\Mapping\Masa.BuildingBlocks.Data.Mapping\Masa.BuildingBlocks.Data.Mapping.csproj", "{523EB315-1A01-4F13-9EDE-266FE8111AB6}" @@ -101,20 +99,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.Isolati EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.ReadWriteSplitting.Cqrs", "src\BuildingBlocks\ReadWriteSplitting\Masa.BuildingBlocks.ReadWriteSplitting.Cqrs\Masa.BuildingBlocks.ReadWriteSplitting.Cqrs.csproj", "{400854AA-AE3F-40EC-B5BF-C9F1257490AA}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Auth", "Auth", "{8A89304F-709C-4A3A-9FA6-D88761B8231B}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Auth", "src\BuildingBlocks\StackSdks\Auth\Masa.BuildingBlocks.StackSdks.Auth\Masa.BuildingBlocks.StackSdks.Auth.csproj", "{C37FB18D-FBA1-49DF-96CD-24D6F65B66E1}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Auth.Contracts", "src\BuildingBlocks\StackSdks\Auth\Masa.BuildingBlocks.StackSdks.Auth.Contracts\Masa.BuildingBlocks.StackSdks.Auth.Contracts.csproj", "{C6006F72-B9F9-4E57-B2A9-63B2D0EA5EF0}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Tsc", "src\BuildingBlocks\StackSdks\Masa.BuildingBlocks.StackSdk.Tsc\Masa.BuildingBlocks.StackSdks.Tsc.csproj", "{89D032A8-14FB-4C2F-A112-CB7FAFCA2B62}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Mc", "src\BuildingBlocks\StackSdks\Masa.BuildingBlocks.StackSdks.Mc\Masa.BuildingBlocks.StackSdks.Mc.csproj", "{1F263FE5-649F-441D-AA55-B6012439E27F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Pm", "src\BuildingBlocks\StackSdks\Masa.BuildingBlocks.StackSdks.Pm\Masa.BuildingBlocks.StackSdks.Pm.csproj", "{F0A72797-A0E3-48BF-9E2E-34FD5ADD3441}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Scheduler", "src\BuildingBlocks\StackSdks\Masa.BuildingBlocks.StackSdks.Scheduler\Masa.BuildingBlocks.StackSdks.Scheduler.csproj", "{D2D5E0AD-AEE6-495F-96EA-5B9B1F17CE8F}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Caching", "Caching", "{AF921AB1-64D1-4478-AB49-192F3EE416FC}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Configuration", "Configuration", "{56917740-626B-42D5-8BB8-6895F79FB7D2}" @@ -193,8 +177,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SearchEngine", "SearchEngin EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Service", "Service", "{B7709311-A885-49E1-9078-B6CC8406B916}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "StackSdks", "StackSdks", "{383995FF-B661-4E15-A830-640FC5BA8A1F}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Storage", "Storage", "{62E888C1-9FCD-413D-91CB-1F2DD3D356E3}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "OpenIdConnect", "OpenIdConnect", "{41769FBF-91A8-48D1-B3BB-CAE4C814E7CD}" @@ -399,32 +381,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{2959DC55 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Scenes", "Scenes", "{E8681596-D4BF-484A-A428-06D749FD4C5D}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Auth", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Auth\Masa.Contrib.StackSdks.Auth.csproj", "{F0D73CEC-6CB7-4BF1-B6DD-29D785BF9A5B}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Dcc", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Dcc\Masa.Contrib.StackSdks.Dcc.csproj", "{A4D8F3F8-F0ED-49F9-8C50-3F3311A98B2F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Mc", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Mc\Masa.Contrib.StackSdks.Mc.csproj", "{9BD06CA5-0169-418B-A8C8-60584EEDCEFE}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Pm", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Pm\Masa.Contrib.StackSdks.Pm.csproj", "{22EC5EB8-52C1-4BC2-BDD3-09D5DC6BFA3F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Scheduler", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Scheduler\Masa.Contrib.StackSdks.Scheduler.csproj", "{8E7F9812-2DF1-483C-93AB-F8BBC18D9761}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Tsc", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Tsc\Masa.Contrib.StackSdks.Tsc.csproj", "{D4D2DA65-D16D-4236-ABD0-492681944D00}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{EC7A08E9-3355-486B-BA30-41A1F8CAC5F5}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Auth.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Auth.Tests\Masa.Contrib.StackSdks.Auth.Tests.csproj", "{5DD4C255-EF06-4ECE-A0C3-1CF0EDB5193C}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Dcc.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Dcc.Tests\Masa.Contrib.StackSdks.Dcc.Tests.csproj", "{74149D50-9DED-45D7-9C52-5F74BEE6B80D}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Mc.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Mc.Tests\Masa.Contrib.StackSdks.Mc.Tests.csproj", "{975AAE87-E410-4FFF-8A9E-6FD7E020A3C9}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Pm.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Pm.Tests\Masa.Contrib.StackSdks.Pm.Tests.csproj", "{373F9664-5B59-4068-B1E2-61CDD3B2F760}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Scheduler.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Scheduler.Tests\Masa.Contrib.StackSdks.Scheduler.Tests.csproj", "{950FE681-764C-4B75-BB95-938A9F17B2D9}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Tsc.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Tsc.Test\Masa.Contrib.StackSdks.Tsc.Tests.csproj", "{F110D91A-F1A9-4627-85C8-501F814FED26}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Storage.ObjectStorage.Aliyun", "src\Contrib\Storage\ObjectStorage\Masa.Contrib.Storage.ObjectStorage.Aliyun\Masa.Contrib.Storage.ObjectStorage.Aliyun.csproj", "{16B18299-3640-4FA8-A4E6-74B1EB741301}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ObjectStorage", "ObjectStorage", "{1B2FF31A-187A-4D36-AD81-1ABD9BCF9044}" @@ -559,12 +515,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.RulesEngine.Mi EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Development.DaprStarter.AspNetCore", "src\Contrib\Development\Masa.Contrib.Development.DaprStarter.AspNetCore\Masa.Contrib.Development.DaprStarter.AspNetCore.csproj", "{E47D82C7-7A1C-4BEF-ACA8-43971FD6C6BA}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Dcc", "Dcc", "{5E0E61DA-06FF-4F08-9C76-0A8856C90EF5}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Dcc", "src\BuildingBlocks\StackSdks\Dcc\Masa.BuildingBlocks.StackSdks.Dcc\Masa.BuildingBlocks.StackSdks.Dcc.csproj", "{356C5F47-025F-4ED6-8E8A-8745E181C455}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Dcc.Contracts", "src\BuildingBlocks\StackSdks\Dcc\Masa.BuildingBlocks.StackSdks.Dcc.Contracts\Masa.BuildingBlocks.StackSdks.Dcc.Contracts.csproj", "{C2E9EDAE-2558-4899-A486-917AE7A5D24F}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{8CDAF37E-3DB1-4573-B5AA-376C93A8D299}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Development.DaprStarter.Tests", "src\Contrib\Development\Tests\Masa.Contrib.Development.DaprStarter.Tests\Masa.Contrib.Development.DaprStarter.Tests.csproj", "{49B51B95-3DC5-45BD-B91A-3056FF5014B5}" @@ -597,12 +547,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Dispatcher.Eve EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.Globalization.I18n", "src\BuildingBlocks\Globalization\Masa.BuildingBlocks.Globalization.I18n\Masa.BuildingBlocks.Globalization.I18n.csproj", "{6088C3D3-E17E-41BC-A21F-F222F5123DF1}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Tsc.Contracts", "src\BuildingBlocks\StackSdks\Masa.BuildingBlocks.StackSdks.Tsc.Contracts\Masa.BuildingBlocks.StackSdks.Tsc.Contracts.csproj", "{12FD44BF-B1CD-4B8A-9C7F-318ED6FE48FD}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Tsc.Elasticsearch", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Tsc.Elasticsearch\Masa.Contrib.StackSdks.Tsc.Elasticsearch.csproj", "{A04C3ECC-51BB-43A9-9C38-2305AB31F60D}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests\Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests.csproj", "{21317D81-BED0-46F0-8FBC-A9B7F1C7F2FD}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Ddd.Domain.Tests", "src\Contrib\Ddd\Domain\Tests\Masa.Contrib.Ddd.Domain.Tests\Masa.Contrib.Ddd.Domain.Tests.csproj", "{2D87B9C4-E2FA-47DB-B6B9-BAFF8E0B7558}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Ddd.Domain.Repository.EFCore.IntegrationTests", "src\Contrib\Ddd\Domain\Tests\Masa.Contrib.Ddd.Domain.Repository.EFCore.IntegrationTests\Masa.Contrib.Ddd.Domain.Repository.EFCore.IntegrationTests.csproj", "{AE12559A-5C8F-4590-9B18-B935155B15C5}" @@ -621,12 +565,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Utils.Extensions.Expre EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.Globalization.I18n.Tests", "src\BuildingBlocks\Globalization\Masa.BuildingBlocks.Globalization.I18n.Tests\Masa.BuildingBlocks.Globalization.I18n.Tests.csproj", "{8BF4E6EC-4BF7-43B6-B11B-9047759E4FAE}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Config", "src\BuildingBlocks\StackSdks\Masa.BuildingBlocks.StackSdks.Config\Masa.BuildingBlocks.StackSdks.Config.csproj", "{AF718133-0A37-4F1A-96DF-61C3D9836B7F}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Config", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Config\Masa.Contrib.StackSdks.Config.csproj", "{F3C2B14A-C350-4E30-9EB5-5BFCCC4EEB5B}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Config.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Config.Tests\Masa.Contrib.StackSdks.Config.Tests.csproj", "{5130EF56-9225-453C-A9AF-EB80A8A19E18}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Service.Caller.HttpClient.Tests", "src\Contrib\Service\Caller\Tests\Masa.Contrib.Service.Caller.HttpClient.Tests\Masa.Contrib.Service.Caller.HttpClient.Tests.csproj", "{2BD60D01-E28C-4887-BD48-49C950650E91}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{F6BD4124-2DCA-453E-B73C-D9DB6323CCDC}" @@ -635,12 +573,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Service.Caller EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.Data.Tests", "src\BuildingBlocks\Data\Tests\Masa.BuildingBlocks.Data.Tests\Masa.BuildingBlocks.Data.Tests.csproj", "{4F1E9488-FAC5-4966-90E6-F1DFE35F8370}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Middleware", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Middleware\Masa.Contrib.StackSdks.Middleware.csproj", "{32E0798A-5FBB-4EF3-9D25-2E7FFC64149C}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Middleware", "src\BuildingBlocks\StackSdks\Masa.BuildingBlocks.StackSdks.Middleware\Masa.BuildingBlocks.StackSdks.Middleware.csproj", "{89A12439-90DF-428D-8AB0-3E91540676C4}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Middleware.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Middleware.Tests\Masa.Contrib.StackSdks.Middleware.Tests.csproj", "{D54C1134-1805-4DD7-84A6-BF680784443C}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Service.Caller.DaprClient.Tests.Scenes.MasaConfiguration", "src\Contrib\Service\Caller\Tests\Scenes\Masa.Contrib.Service.Caller.DaprClient.Tests.Scenes.MasaConfiguration\Masa.Contrib.Service.Caller.DaprClient.Tests.Scenes.MasaConfiguration.csproj", "{CBF61DB2-035B-4084-9872-0350C4DDA9EE}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Serialization", "Serialization", "{5BBCCDEC-C77C-4A68-9911-C69B38666E18}" @@ -675,52 +607,24 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Extensions.Bac EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Extensions.BackgroundJobs.Hangfire.Tests", "src\Contrib\Extensions\Tests\Masa.Contrib.Extensions.BackgroundJobs.Hangfire.Tests\Masa.Contrib.Extensions.BackgroundJobs.Hangfire.Tests.csproj", "{BC848CB9-1065-4FC5-8CB4-8EE733E18E50}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Caller", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Caller\Masa.Contrib.StackSdks.Caller.csproj", "{B57859AD-720E-41D2-9C15-85F49AC73D18}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Alert", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Alert\Masa.Contrib.StackSdks.Alert.csproj", "{30A143AF-4E9D-457E-BDAE-DFBC5A262F4A}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Scenes", "Scenes", "{CD5365A1-1781-4088-A9A2-EC58F3581D3B}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests.Isolation", "src\Contrib\Storage\ObjectStorage\Tests\Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests.Isolation\Masa.Contrib.Storage.ObjectStorage.Aliyun.Tests.Isolation.csproj", "{2A691CCB-E2A0-408D-BC2D-7D2157B3E85A}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Alert", "src\BuildingBlocks\StackSdks\Masa.BuildingBlocks.StackSdks.Alert\Masa.BuildingBlocks.StackSdks.Alert.csproj", "{EEACDE24-9D4A-4F65-B13A-644E89A7918D}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{3C12BE69-247B-4448-9700-0ACEE8440A34}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Alert.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Alert.Tests\Masa.Contrib.StackSdks.Alert.Tests.csproj", "{1221F32F-7310-49FF-94DD-2BCF570E03F2}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Data.UoW.EFCore.Tests", "src\Contrib\Data\UoW\Tests\Masa.Contrib.Data.UoW.EFCore.Tests\Masa.Contrib.Data.UoW.EFCore.Tests.csproj", "{9208B446-A7E0-4B5A-A42D-37E63B76E875}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Scenes", "Scenes", "{02591EE4-1033-4575-984F-7AB290E7C6FA}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.Data.EFCore.Tests.Scenes.Isolation", "src\Contrib\Data\Orm\EFCore\Scenes\Masa.Contrib.Data.EFCore.Tests.Scenes.Isolation\Masa.Contrib.Data.EFCore.Tests.Scenes.Isolation.csproj", "{A5B30EEA-2DE1-4233-8584-936CB862191B}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Isolation", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Isolation\Masa.Contrib.StackSdks.Isolation.csproj", "{6E853D47-6C4F-4102-85A2-31EB172FB864}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.BuildingBlocks.StackSdks.Isolation", "src\BuildingBlocks\StackSdks\Masa.BuildingBlocks.StackSdks.Isolation\Masa.BuildingBlocks.StackSdks.Isolation.csproj", "{4B175C6B-F5BE-4B65-BFCC-A949CA5BC6A3}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Tsc.OpenTelemetry", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Tsc.OpenTelemetry\Masa.Contrib.StackSdks.Tsc.OpenTelemetry.csproj", "{2B861EF5-124F-4D13-8291-F223B6588C35}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests\Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests.csproj", "{62D22ED4-76A6-41EE-9121-992608E3590D}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tsc", "tsc", "{E4AD67C8-9255-4013-A3C4-962694399770}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tsc", "tsc", "{6042AE23-A07E-4F6F-B1C3-F17617AEB722}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "DynamicsCRM", "DynamicsCRM", "{64B54122-44F1-4379-9422-953EF706A3A6}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Utils.DynamicsCrm.Core", "src\Utils\DynamicsCrm\Masa.Utils.DynamicsCrm.Core\Masa.Utils.DynamicsCrm.Core.csproj", "{83310F46-E1C7-4438-B32A-9F6F7EA13FCF}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Utils.DynamicsCrm.EntityFrameworkCore", "src\Utils\DynamicsCrm\Masa.Utils.DynamicsCrm.EntityFrameworkCore\Masa.Utils.DynamicsCrm.EntityFrameworkCore.csproj", "{8A51A2A9-FBF4-40DC-AD89-AD3B9D3A50DC}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Tsc.Clickhouse", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Tsc.Clickhouse\Masa.Contrib.StackSdks.Tsc.Clickhouse.csproj", "{43389D12-17E1-4F07-9A42-5CFCC24D08B2}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests\Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests.csproj", "{289BF8C8-968F-4105-A65E-C1C6FD8857F2}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse", "src\Contrib\StackSdks\Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse\Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.csproj", "{9B4F7AC1-97FD-400A-9810-7F7672FBAF65}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests", "src\Contrib\StackSdks\Tests\Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests\Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests.csproj", "{7E11AD82-5E5C-43E9-B7C3-77A127B628E8}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -913,54 +817,6 @@ Global {400854AA-AE3F-40EC-B5BF-C9F1257490AA}.Release|Any CPU.Build.0 = Release|Any CPU {400854AA-AE3F-40EC-B5BF-C9F1257490AA}.Release|x64.ActiveCfg = Release|Any CPU {400854AA-AE3F-40EC-B5BF-C9F1257490AA}.Release|x64.Build.0 = Release|Any CPU - {C37FB18D-FBA1-49DF-96CD-24D6F65B66E1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C37FB18D-FBA1-49DF-96CD-24D6F65B66E1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C37FB18D-FBA1-49DF-96CD-24D6F65B66E1}.Debug|x64.ActiveCfg = Debug|Any CPU - {C37FB18D-FBA1-49DF-96CD-24D6F65B66E1}.Debug|x64.Build.0 = Debug|Any CPU - {C37FB18D-FBA1-49DF-96CD-24D6F65B66E1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C37FB18D-FBA1-49DF-96CD-24D6F65B66E1}.Release|Any CPU.Build.0 = Release|Any CPU - {C37FB18D-FBA1-49DF-96CD-24D6F65B66E1}.Release|x64.ActiveCfg = Release|Any CPU - {C37FB18D-FBA1-49DF-96CD-24D6F65B66E1}.Release|x64.Build.0 = Release|Any CPU - {C6006F72-B9F9-4E57-B2A9-63B2D0EA5EF0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C6006F72-B9F9-4E57-B2A9-63B2D0EA5EF0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C6006F72-B9F9-4E57-B2A9-63B2D0EA5EF0}.Debug|x64.ActiveCfg = Debug|Any CPU - {C6006F72-B9F9-4E57-B2A9-63B2D0EA5EF0}.Debug|x64.Build.0 = Debug|Any CPU - {C6006F72-B9F9-4E57-B2A9-63B2D0EA5EF0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C6006F72-B9F9-4E57-B2A9-63B2D0EA5EF0}.Release|Any CPU.Build.0 = Release|Any CPU - {C6006F72-B9F9-4E57-B2A9-63B2D0EA5EF0}.Release|x64.ActiveCfg = Release|Any CPU - {C6006F72-B9F9-4E57-B2A9-63B2D0EA5EF0}.Release|x64.Build.0 = Release|Any CPU - {89D032A8-14FB-4C2F-A112-CB7FAFCA2B62}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {89D032A8-14FB-4C2F-A112-CB7FAFCA2B62}.Debug|Any CPU.Build.0 = Debug|Any CPU - {89D032A8-14FB-4C2F-A112-CB7FAFCA2B62}.Debug|x64.ActiveCfg = Debug|Any CPU - {89D032A8-14FB-4C2F-A112-CB7FAFCA2B62}.Debug|x64.Build.0 = Debug|Any CPU - {89D032A8-14FB-4C2F-A112-CB7FAFCA2B62}.Release|Any CPU.ActiveCfg = Release|Any CPU - {89D032A8-14FB-4C2F-A112-CB7FAFCA2B62}.Release|Any CPU.Build.0 = Release|Any CPU - {89D032A8-14FB-4C2F-A112-CB7FAFCA2B62}.Release|x64.ActiveCfg = Release|Any CPU - {89D032A8-14FB-4C2F-A112-CB7FAFCA2B62}.Release|x64.Build.0 = Release|Any CPU - {1F263FE5-649F-441D-AA55-B6012439E27F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1F263FE5-649F-441D-AA55-B6012439E27F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1F263FE5-649F-441D-AA55-B6012439E27F}.Debug|x64.ActiveCfg = Debug|Any CPU - {1F263FE5-649F-441D-AA55-B6012439E27F}.Debug|x64.Build.0 = Debug|Any CPU - {1F263FE5-649F-441D-AA55-B6012439E27F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1F263FE5-649F-441D-AA55-B6012439E27F}.Release|Any CPU.Build.0 = Release|Any CPU - {1F263FE5-649F-441D-AA55-B6012439E27F}.Release|x64.ActiveCfg = Release|Any CPU - {1F263FE5-649F-441D-AA55-B6012439E27F}.Release|x64.Build.0 = Release|Any CPU - {F0A72797-A0E3-48BF-9E2E-34FD5ADD3441}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F0A72797-A0E3-48BF-9E2E-34FD5ADD3441}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F0A72797-A0E3-48BF-9E2E-34FD5ADD3441}.Debug|x64.ActiveCfg = Debug|Any CPU - {F0A72797-A0E3-48BF-9E2E-34FD5ADD3441}.Debug|x64.Build.0 = Debug|Any CPU - {F0A72797-A0E3-48BF-9E2E-34FD5ADD3441}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F0A72797-A0E3-48BF-9E2E-34FD5ADD3441}.Release|Any CPU.Build.0 = Release|Any CPU - {F0A72797-A0E3-48BF-9E2E-34FD5ADD3441}.Release|x64.ActiveCfg = Release|Any CPU - {F0A72797-A0E3-48BF-9E2E-34FD5ADD3441}.Release|x64.Build.0 = Release|Any CPU - {D2D5E0AD-AEE6-495F-96EA-5B9B1F17CE8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D2D5E0AD-AEE6-495F-96EA-5B9B1F17CE8F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D2D5E0AD-AEE6-495F-96EA-5B9B1F17CE8F}.Debug|x64.ActiveCfg = Debug|Any CPU - {D2D5E0AD-AEE6-495F-96EA-5B9B1F17CE8F}.Debug|x64.Build.0 = Debug|Any CPU - {D2D5E0AD-AEE6-495F-96EA-5B9B1F17CE8F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D2D5E0AD-AEE6-495F-96EA-5B9B1F17CE8F}.Release|Any CPU.Build.0 = Release|Any CPU - {D2D5E0AD-AEE6-495F-96EA-5B9B1F17CE8F}.Release|x64.ActiveCfg = Release|Any CPU - {D2D5E0AD-AEE6-495F-96EA-5B9B1F17CE8F}.Release|x64.Build.0 = Release|Any CPU {015C4181-A8D9-4FA5-89B9-38A37FA9D31D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {015C4181-A8D9-4FA5-89B9-38A37FA9D31D}.Debug|Any CPU.Build.0 = Debug|Any CPU {015C4181-A8D9-4FA5-89B9-38A37FA9D31D}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -1633,102 +1489,6 @@ Global {22BE7D35-34C4-49FA-B20E-B69289C10B5E}.Release|Any CPU.Build.0 = Release|Any CPU {22BE7D35-34C4-49FA-B20E-B69289C10B5E}.Release|x64.ActiveCfg = Release|Any CPU {22BE7D35-34C4-49FA-B20E-B69289C10B5E}.Release|x64.Build.0 = Release|Any CPU - {F0D73CEC-6CB7-4BF1-B6DD-29D785BF9A5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F0D73CEC-6CB7-4BF1-B6DD-29D785BF9A5B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F0D73CEC-6CB7-4BF1-B6DD-29D785BF9A5B}.Debug|x64.ActiveCfg = Debug|Any CPU - {F0D73CEC-6CB7-4BF1-B6DD-29D785BF9A5B}.Debug|x64.Build.0 = Debug|Any CPU - {F0D73CEC-6CB7-4BF1-B6DD-29D785BF9A5B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F0D73CEC-6CB7-4BF1-B6DD-29D785BF9A5B}.Release|Any CPU.Build.0 = Release|Any CPU - {F0D73CEC-6CB7-4BF1-B6DD-29D785BF9A5B}.Release|x64.ActiveCfg = Release|Any CPU - {F0D73CEC-6CB7-4BF1-B6DD-29D785BF9A5B}.Release|x64.Build.0 = Release|Any CPU - {A4D8F3F8-F0ED-49F9-8C50-3F3311A98B2F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A4D8F3F8-F0ED-49F9-8C50-3F3311A98B2F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A4D8F3F8-F0ED-49F9-8C50-3F3311A98B2F}.Debug|x64.ActiveCfg = Debug|Any CPU - {A4D8F3F8-F0ED-49F9-8C50-3F3311A98B2F}.Debug|x64.Build.0 = Debug|Any CPU - {A4D8F3F8-F0ED-49F9-8C50-3F3311A98B2F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A4D8F3F8-F0ED-49F9-8C50-3F3311A98B2F}.Release|Any CPU.Build.0 = Release|Any CPU - {A4D8F3F8-F0ED-49F9-8C50-3F3311A98B2F}.Release|x64.ActiveCfg = Release|Any CPU - {A4D8F3F8-F0ED-49F9-8C50-3F3311A98B2F}.Release|x64.Build.0 = Release|Any CPU - {9BD06CA5-0169-418B-A8C8-60584EEDCEFE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9BD06CA5-0169-418B-A8C8-60584EEDCEFE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9BD06CA5-0169-418B-A8C8-60584EEDCEFE}.Debug|x64.ActiveCfg = Debug|Any CPU - {9BD06CA5-0169-418B-A8C8-60584EEDCEFE}.Debug|x64.Build.0 = Debug|Any CPU - {9BD06CA5-0169-418B-A8C8-60584EEDCEFE}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9BD06CA5-0169-418B-A8C8-60584EEDCEFE}.Release|Any CPU.Build.0 = Release|Any CPU - {9BD06CA5-0169-418B-A8C8-60584EEDCEFE}.Release|x64.ActiveCfg = Release|Any CPU - {9BD06CA5-0169-418B-A8C8-60584EEDCEFE}.Release|x64.Build.0 = Release|Any CPU - {22EC5EB8-52C1-4BC2-BDD3-09D5DC6BFA3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {22EC5EB8-52C1-4BC2-BDD3-09D5DC6BFA3F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {22EC5EB8-52C1-4BC2-BDD3-09D5DC6BFA3F}.Debug|x64.ActiveCfg = Debug|Any CPU - {22EC5EB8-52C1-4BC2-BDD3-09D5DC6BFA3F}.Debug|x64.Build.0 = Debug|Any CPU - {22EC5EB8-52C1-4BC2-BDD3-09D5DC6BFA3F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {22EC5EB8-52C1-4BC2-BDD3-09D5DC6BFA3F}.Release|Any CPU.Build.0 = Release|Any CPU - {22EC5EB8-52C1-4BC2-BDD3-09D5DC6BFA3F}.Release|x64.ActiveCfg = Release|Any CPU - {22EC5EB8-52C1-4BC2-BDD3-09D5DC6BFA3F}.Release|x64.Build.0 = Release|Any CPU - {8E7F9812-2DF1-483C-93AB-F8BBC18D9761}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8E7F9812-2DF1-483C-93AB-F8BBC18D9761}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8E7F9812-2DF1-483C-93AB-F8BBC18D9761}.Debug|x64.ActiveCfg = Debug|Any CPU - {8E7F9812-2DF1-483C-93AB-F8BBC18D9761}.Debug|x64.Build.0 = Debug|Any CPU - {8E7F9812-2DF1-483C-93AB-F8BBC18D9761}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8E7F9812-2DF1-483C-93AB-F8BBC18D9761}.Release|Any CPU.Build.0 = Release|Any CPU - {8E7F9812-2DF1-483C-93AB-F8BBC18D9761}.Release|x64.ActiveCfg = Release|Any CPU - {8E7F9812-2DF1-483C-93AB-F8BBC18D9761}.Release|x64.Build.0 = Release|Any CPU - {D4D2DA65-D16D-4236-ABD0-492681944D00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D4D2DA65-D16D-4236-ABD0-492681944D00}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D4D2DA65-D16D-4236-ABD0-492681944D00}.Debug|x64.ActiveCfg = Debug|Any CPU - {D4D2DA65-D16D-4236-ABD0-492681944D00}.Debug|x64.Build.0 = Debug|Any CPU - {D4D2DA65-D16D-4236-ABD0-492681944D00}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D4D2DA65-D16D-4236-ABD0-492681944D00}.Release|Any CPU.Build.0 = Release|Any CPU - {D4D2DA65-D16D-4236-ABD0-492681944D00}.Release|x64.ActiveCfg = Release|Any CPU - {D4D2DA65-D16D-4236-ABD0-492681944D00}.Release|x64.Build.0 = Release|Any CPU - {5DD4C255-EF06-4ECE-A0C3-1CF0EDB5193C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5DD4C255-EF06-4ECE-A0C3-1CF0EDB5193C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5DD4C255-EF06-4ECE-A0C3-1CF0EDB5193C}.Debug|x64.ActiveCfg = Debug|Any CPU - {5DD4C255-EF06-4ECE-A0C3-1CF0EDB5193C}.Debug|x64.Build.0 = Debug|Any CPU - {5DD4C255-EF06-4ECE-A0C3-1CF0EDB5193C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5DD4C255-EF06-4ECE-A0C3-1CF0EDB5193C}.Release|Any CPU.Build.0 = Release|Any CPU - {5DD4C255-EF06-4ECE-A0C3-1CF0EDB5193C}.Release|x64.ActiveCfg = Release|Any CPU - {5DD4C255-EF06-4ECE-A0C3-1CF0EDB5193C}.Release|x64.Build.0 = Release|Any CPU - {74149D50-9DED-45D7-9C52-5F74BEE6B80D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {74149D50-9DED-45D7-9C52-5F74BEE6B80D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {74149D50-9DED-45D7-9C52-5F74BEE6B80D}.Debug|x64.ActiveCfg = Debug|Any CPU - {74149D50-9DED-45D7-9C52-5F74BEE6B80D}.Debug|x64.Build.0 = Debug|Any CPU - {74149D50-9DED-45D7-9C52-5F74BEE6B80D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {74149D50-9DED-45D7-9C52-5F74BEE6B80D}.Release|Any CPU.Build.0 = Release|Any CPU - {74149D50-9DED-45D7-9C52-5F74BEE6B80D}.Release|x64.ActiveCfg = Release|Any CPU - {74149D50-9DED-45D7-9C52-5F74BEE6B80D}.Release|x64.Build.0 = Release|Any CPU - {975AAE87-E410-4FFF-8A9E-6FD7E020A3C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {975AAE87-E410-4FFF-8A9E-6FD7E020A3C9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {975AAE87-E410-4FFF-8A9E-6FD7E020A3C9}.Debug|x64.ActiveCfg = Debug|Any CPU - {975AAE87-E410-4FFF-8A9E-6FD7E020A3C9}.Debug|x64.Build.0 = Debug|Any CPU - {975AAE87-E410-4FFF-8A9E-6FD7E020A3C9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {975AAE87-E410-4FFF-8A9E-6FD7E020A3C9}.Release|Any CPU.Build.0 = Release|Any CPU - {975AAE87-E410-4FFF-8A9E-6FD7E020A3C9}.Release|x64.ActiveCfg = Release|Any CPU - {975AAE87-E410-4FFF-8A9E-6FD7E020A3C9}.Release|x64.Build.0 = Release|Any CPU - {373F9664-5B59-4068-B1E2-61CDD3B2F760}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {373F9664-5B59-4068-B1E2-61CDD3B2F760}.Debug|Any CPU.Build.0 = Debug|Any CPU - {373F9664-5B59-4068-B1E2-61CDD3B2F760}.Debug|x64.ActiveCfg = Debug|Any CPU - {373F9664-5B59-4068-B1E2-61CDD3B2F760}.Debug|x64.Build.0 = Debug|Any CPU - {373F9664-5B59-4068-B1E2-61CDD3B2F760}.Release|Any CPU.ActiveCfg = Release|Any CPU - {373F9664-5B59-4068-B1E2-61CDD3B2F760}.Release|Any CPU.Build.0 = Release|Any CPU - {373F9664-5B59-4068-B1E2-61CDD3B2F760}.Release|x64.ActiveCfg = Release|Any CPU - {373F9664-5B59-4068-B1E2-61CDD3B2F760}.Release|x64.Build.0 = Release|Any CPU - {950FE681-764C-4B75-BB95-938A9F17B2D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {950FE681-764C-4B75-BB95-938A9F17B2D9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {950FE681-764C-4B75-BB95-938A9F17B2D9}.Debug|x64.ActiveCfg = Debug|Any CPU - {950FE681-764C-4B75-BB95-938A9F17B2D9}.Debug|x64.Build.0 = Debug|Any CPU - {950FE681-764C-4B75-BB95-938A9F17B2D9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {950FE681-764C-4B75-BB95-938A9F17B2D9}.Release|Any CPU.Build.0 = Release|Any CPU - {950FE681-764C-4B75-BB95-938A9F17B2D9}.Release|x64.ActiveCfg = Release|Any CPU - {950FE681-764C-4B75-BB95-938A9F17B2D9}.Release|x64.Build.0 = Release|Any CPU - {F110D91A-F1A9-4627-85C8-501F814FED26}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F110D91A-F1A9-4627-85C8-501F814FED26}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F110D91A-F1A9-4627-85C8-501F814FED26}.Debug|x64.ActiveCfg = Debug|Any CPU - {F110D91A-F1A9-4627-85C8-501F814FED26}.Debug|x64.Build.0 = Debug|Any CPU - {F110D91A-F1A9-4627-85C8-501F814FED26}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F110D91A-F1A9-4627-85C8-501F814FED26}.Release|Any CPU.Build.0 = Release|Any CPU - {F110D91A-F1A9-4627-85C8-501F814FED26}.Release|x64.ActiveCfg = Release|Any CPU - {F110D91A-F1A9-4627-85C8-501F814FED26}.Release|x64.Build.0 = Release|Any CPU {16B18299-3640-4FA8-A4E6-74B1EB741301}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {16B18299-3640-4FA8-A4E6-74B1EB741301}.Debug|Any CPU.Build.0 = Debug|Any CPU {16B18299-3640-4FA8-A4E6-74B1EB741301}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -2113,22 +1873,6 @@ Global {E47D82C7-7A1C-4BEF-ACA8-43971FD6C6BA}.Release|Any CPU.Build.0 = Release|Any CPU {E47D82C7-7A1C-4BEF-ACA8-43971FD6C6BA}.Release|x64.ActiveCfg = Release|Any CPU {E47D82C7-7A1C-4BEF-ACA8-43971FD6C6BA}.Release|x64.Build.0 = Release|Any CPU - {356C5F47-025F-4ED6-8E8A-8745E181C455}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {356C5F47-025F-4ED6-8E8A-8745E181C455}.Debug|Any CPU.Build.0 = Debug|Any CPU - {356C5F47-025F-4ED6-8E8A-8745E181C455}.Debug|x64.ActiveCfg = Debug|Any CPU - {356C5F47-025F-4ED6-8E8A-8745E181C455}.Debug|x64.Build.0 = Debug|Any CPU - {356C5F47-025F-4ED6-8E8A-8745E181C455}.Release|Any CPU.ActiveCfg = Release|Any CPU - {356C5F47-025F-4ED6-8E8A-8745E181C455}.Release|Any CPU.Build.0 = Release|Any CPU - {356C5F47-025F-4ED6-8E8A-8745E181C455}.Release|x64.ActiveCfg = Release|Any CPU - {356C5F47-025F-4ED6-8E8A-8745E181C455}.Release|x64.Build.0 = Release|Any CPU - {C2E9EDAE-2558-4899-A486-917AE7A5D24F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C2E9EDAE-2558-4899-A486-917AE7A5D24F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C2E9EDAE-2558-4899-A486-917AE7A5D24F}.Debug|x64.ActiveCfg = Debug|Any CPU - {C2E9EDAE-2558-4899-A486-917AE7A5D24F}.Debug|x64.Build.0 = Debug|Any CPU - {C2E9EDAE-2558-4899-A486-917AE7A5D24F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C2E9EDAE-2558-4899-A486-917AE7A5D24F}.Release|Any CPU.Build.0 = Release|Any CPU - {C2E9EDAE-2558-4899-A486-917AE7A5D24F}.Release|x64.ActiveCfg = Release|Any CPU - {C2E9EDAE-2558-4899-A486-917AE7A5D24F}.Release|x64.Build.0 = Release|Any CPU {49B51B95-3DC5-45BD-B91A-3056FF5014B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {49B51B95-3DC5-45BD-B91A-3056FF5014B5}.Debug|Any CPU.Build.0 = Debug|Any CPU {49B51B95-3DC5-45BD-B91A-3056FF5014B5}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -2225,30 +1969,6 @@ Global {6088C3D3-E17E-41BC-A21F-F222F5123DF1}.Release|Any CPU.Build.0 = Release|Any CPU {6088C3D3-E17E-41BC-A21F-F222F5123DF1}.Release|x64.ActiveCfg = Release|Any CPU {6088C3D3-E17E-41BC-A21F-F222F5123DF1}.Release|x64.Build.0 = Release|Any CPU - {12FD44BF-B1CD-4B8A-9C7F-318ED6FE48FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {12FD44BF-B1CD-4B8A-9C7F-318ED6FE48FD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {12FD44BF-B1CD-4B8A-9C7F-318ED6FE48FD}.Debug|x64.ActiveCfg = Debug|Any CPU - {12FD44BF-B1CD-4B8A-9C7F-318ED6FE48FD}.Debug|x64.Build.0 = Debug|Any CPU - {12FD44BF-B1CD-4B8A-9C7F-318ED6FE48FD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {12FD44BF-B1CD-4B8A-9C7F-318ED6FE48FD}.Release|Any CPU.Build.0 = Release|Any CPU - {12FD44BF-B1CD-4B8A-9C7F-318ED6FE48FD}.Release|x64.ActiveCfg = Release|Any CPU - {12FD44BF-B1CD-4B8A-9C7F-318ED6FE48FD}.Release|x64.Build.0 = Release|Any CPU - {A04C3ECC-51BB-43A9-9C38-2305AB31F60D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A04C3ECC-51BB-43A9-9C38-2305AB31F60D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A04C3ECC-51BB-43A9-9C38-2305AB31F60D}.Debug|x64.ActiveCfg = Debug|Any CPU - {A04C3ECC-51BB-43A9-9C38-2305AB31F60D}.Debug|x64.Build.0 = Debug|Any CPU - {A04C3ECC-51BB-43A9-9C38-2305AB31F60D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A04C3ECC-51BB-43A9-9C38-2305AB31F60D}.Release|Any CPU.Build.0 = Release|Any CPU - {A04C3ECC-51BB-43A9-9C38-2305AB31F60D}.Release|x64.ActiveCfg = Release|Any CPU - {A04C3ECC-51BB-43A9-9C38-2305AB31F60D}.Release|x64.Build.0 = Release|Any CPU - {21317D81-BED0-46F0-8FBC-A9B7F1C7F2FD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {21317D81-BED0-46F0-8FBC-A9B7F1C7F2FD}.Debug|Any CPU.Build.0 = Debug|Any CPU - {21317D81-BED0-46F0-8FBC-A9B7F1C7F2FD}.Debug|x64.ActiveCfg = Debug|Any CPU - {21317D81-BED0-46F0-8FBC-A9B7F1C7F2FD}.Debug|x64.Build.0 = Debug|Any CPU - {21317D81-BED0-46F0-8FBC-A9B7F1C7F2FD}.Release|Any CPU.ActiveCfg = Release|Any CPU - {21317D81-BED0-46F0-8FBC-A9B7F1C7F2FD}.Release|Any CPU.Build.0 = Release|Any CPU - {21317D81-BED0-46F0-8FBC-A9B7F1C7F2FD}.Release|x64.ActiveCfg = Release|Any CPU - {21317D81-BED0-46F0-8FBC-A9B7F1C7F2FD}.Release|x64.Build.0 = Release|Any CPU {2D87B9C4-E2FA-47DB-B6B9-BAFF8E0B7558}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2D87B9C4-E2FA-47DB-B6B9-BAFF8E0B7558}.Debug|Any CPU.Build.0 = Debug|Any CPU {2D87B9C4-E2FA-47DB-B6B9-BAFF8E0B7558}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -2305,30 +2025,6 @@ Global {8BF4E6EC-4BF7-43B6-B11B-9047759E4FAE}.Release|Any CPU.Build.0 = Release|Any CPU {8BF4E6EC-4BF7-43B6-B11B-9047759E4FAE}.Release|x64.ActiveCfg = Release|Any CPU {8BF4E6EC-4BF7-43B6-B11B-9047759E4FAE}.Release|x64.Build.0 = Release|Any CPU - {AF718133-0A37-4F1A-96DF-61C3D9836B7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {AF718133-0A37-4F1A-96DF-61C3D9836B7F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {AF718133-0A37-4F1A-96DF-61C3D9836B7F}.Debug|x64.ActiveCfg = Debug|Any CPU - {AF718133-0A37-4F1A-96DF-61C3D9836B7F}.Debug|x64.Build.0 = Debug|Any CPU - {AF718133-0A37-4F1A-96DF-61C3D9836B7F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AF718133-0A37-4F1A-96DF-61C3D9836B7F}.Release|Any CPU.Build.0 = Release|Any CPU - {AF718133-0A37-4F1A-96DF-61C3D9836B7F}.Release|x64.ActiveCfg = Release|Any CPU - {AF718133-0A37-4F1A-96DF-61C3D9836B7F}.Release|x64.Build.0 = Release|Any CPU - {F3C2B14A-C350-4E30-9EB5-5BFCCC4EEB5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F3C2B14A-C350-4E30-9EB5-5BFCCC4EEB5B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F3C2B14A-C350-4E30-9EB5-5BFCCC4EEB5B}.Debug|x64.ActiveCfg = Debug|Any CPU - {F3C2B14A-C350-4E30-9EB5-5BFCCC4EEB5B}.Debug|x64.Build.0 = Debug|Any CPU - {F3C2B14A-C350-4E30-9EB5-5BFCCC4EEB5B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F3C2B14A-C350-4E30-9EB5-5BFCCC4EEB5B}.Release|Any CPU.Build.0 = Release|Any CPU - {F3C2B14A-C350-4E30-9EB5-5BFCCC4EEB5B}.Release|x64.ActiveCfg = Release|Any CPU - {F3C2B14A-C350-4E30-9EB5-5BFCCC4EEB5B}.Release|x64.Build.0 = Release|Any CPU - {5130EF56-9225-453C-A9AF-EB80A8A19E18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5130EF56-9225-453C-A9AF-EB80A8A19E18}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5130EF56-9225-453C-A9AF-EB80A8A19E18}.Debug|x64.ActiveCfg = Debug|Any CPU - {5130EF56-9225-453C-A9AF-EB80A8A19E18}.Debug|x64.Build.0 = Debug|Any CPU - {5130EF56-9225-453C-A9AF-EB80A8A19E18}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5130EF56-9225-453C-A9AF-EB80A8A19E18}.Release|Any CPU.Build.0 = Release|Any CPU - {5130EF56-9225-453C-A9AF-EB80A8A19E18}.Release|x64.ActiveCfg = Release|Any CPU - {5130EF56-9225-453C-A9AF-EB80A8A19E18}.Release|x64.Build.0 = Release|Any CPU {2BD60D01-E28C-4887-BD48-49C950650E91}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2BD60D01-E28C-4887-BD48-49C950650E91}.Debug|Any CPU.Build.0 = Debug|Any CPU {2BD60D01-E28C-4887-BD48-49C950650E91}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -2353,30 +2049,6 @@ Global {4F1E9488-FAC5-4966-90E6-F1DFE35F8370}.Release|Any CPU.Build.0 = Release|Any CPU {4F1E9488-FAC5-4966-90E6-F1DFE35F8370}.Release|x64.ActiveCfg = Release|Any CPU {4F1E9488-FAC5-4966-90E6-F1DFE35F8370}.Release|x64.Build.0 = Release|Any CPU - {32E0798A-5FBB-4EF3-9D25-2E7FFC64149C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {32E0798A-5FBB-4EF3-9D25-2E7FFC64149C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {32E0798A-5FBB-4EF3-9D25-2E7FFC64149C}.Debug|x64.ActiveCfg = Debug|Any CPU - {32E0798A-5FBB-4EF3-9D25-2E7FFC64149C}.Debug|x64.Build.0 = Debug|Any CPU - {32E0798A-5FBB-4EF3-9D25-2E7FFC64149C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {32E0798A-5FBB-4EF3-9D25-2E7FFC64149C}.Release|Any CPU.Build.0 = Release|Any CPU - {32E0798A-5FBB-4EF3-9D25-2E7FFC64149C}.Release|x64.ActiveCfg = Release|Any CPU - {32E0798A-5FBB-4EF3-9D25-2E7FFC64149C}.Release|x64.Build.0 = Release|Any CPU - {89A12439-90DF-428D-8AB0-3E91540676C4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {89A12439-90DF-428D-8AB0-3E91540676C4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {89A12439-90DF-428D-8AB0-3E91540676C4}.Debug|x64.ActiveCfg = Debug|Any CPU - {89A12439-90DF-428D-8AB0-3E91540676C4}.Debug|x64.Build.0 = Debug|Any CPU - {89A12439-90DF-428D-8AB0-3E91540676C4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {89A12439-90DF-428D-8AB0-3E91540676C4}.Release|Any CPU.Build.0 = Release|Any CPU - {89A12439-90DF-428D-8AB0-3E91540676C4}.Release|x64.ActiveCfg = Release|Any CPU - {89A12439-90DF-428D-8AB0-3E91540676C4}.Release|x64.Build.0 = Release|Any CPU - {D54C1134-1805-4DD7-84A6-BF680784443C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D54C1134-1805-4DD7-84A6-BF680784443C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D54C1134-1805-4DD7-84A6-BF680784443C}.Debug|x64.ActiveCfg = Debug|Any CPU - {D54C1134-1805-4DD7-84A6-BF680784443C}.Debug|x64.Build.0 = Debug|Any CPU - {D54C1134-1805-4DD7-84A6-BF680784443C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D54C1134-1805-4DD7-84A6-BF680784443C}.Release|Any CPU.Build.0 = Release|Any CPU - {D54C1134-1805-4DD7-84A6-BF680784443C}.Release|x64.ActiveCfg = Release|Any CPU - {D54C1134-1805-4DD7-84A6-BF680784443C}.Release|x64.Build.0 = Release|Any CPU {CBF61DB2-035B-4084-9872-0350C4DDA9EE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CBF61DB2-035B-4084-9872-0350C4DDA9EE}.Debug|Any CPU.Build.0 = Debug|Any CPU {CBF61DB2-035B-4084-9872-0350C4DDA9EE}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -2473,22 +2145,6 @@ Global {BC848CB9-1065-4FC5-8CB4-8EE733E18E50}.Release|Any CPU.Build.0 = Release|Any CPU {BC848CB9-1065-4FC5-8CB4-8EE733E18E50}.Release|x64.ActiveCfg = Release|Any CPU {BC848CB9-1065-4FC5-8CB4-8EE733E18E50}.Release|x64.Build.0 = Release|Any CPU - {B57859AD-720E-41D2-9C15-85F49AC73D18}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B57859AD-720E-41D2-9C15-85F49AC73D18}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B57859AD-720E-41D2-9C15-85F49AC73D18}.Debug|x64.ActiveCfg = Debug|Any CPU - {B57859AD-720E-41D2-9C15-85F49AC73D18}.Debug|x64.Build.0 = Debug|Any CPU - {B57859AD-720E-41D2-9C15-85F49AC73D18}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B57859AD-720E-41D2-9C15-85F49AC73D18}.Release|Any CPU.Build.0 = Release|Any CPU - {B57859AD-720E-41D2-9C15-85F49AC73D18}.Release|x64.ActiveCfg = Release|Any CPU - {B57859AD-720E-41D2-9C15-85F49AC73D18}.Release|x64.Build.0 = Release|Any CPU - {30A143AF-4E9D-457E-BDAE-DFBC5A262F4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {30A143AF-4E9D-457E-BDAE-DFBC5A262F4A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {30A143AF-4E9D-457E-BDAE-DFBC5A262F4A}.Debug|x64.ActiveCfg = Debug|Any CPU - {30A143AF-4E9D-457E-BDAE-DFBC5A262F4A}.Debug|x64.Build.0 = Debug|Any CPU - {30A143AF-4E9D-457E-BDAE-DFBC5A262F4A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {30A143AF-4E9D-457E-BDAE-DFBC5A262F4A}.Release|Any CPU.Build.0 = Release|Any CPU - {30A143AF-4E9D-457E-BDAE-DFBC5A262F4A}.Release|x64.ActiveCfg = Release|Any CPU - {30A143AF-4E9D-457E-BDAE-DFBC5A262F4A}.Release|x64.Build.0 = Release|Any CPU {2A691CCB-E2A0-408D-BC2D-7D2157B3E85A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2A691CCB-E2A0-408D-BC2D-7D2157B3E85A}.Debug|Any CPU.Build.0 = Debug|Any CPU {2A691CCB-E2A0-408D-BC2D-7D2157B3E85A}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -2497,22 +2153,6 @@ Global {2A691CCB-E2A0-408D-BC2D-7D2157B3E85A}.Release|Any CPU.Build.0 = Release|Any CPU {2A691CCB-E2A0-408D-BC2D-7D2157B3E85A}.Release|x64.ActiveCfg = Release|Any CPU {2A691CCB-E2A0-408D-BC2D-7D2157B3E85A}.Release|x64.Build.0 = Release|Any CPU - {EEACDE24-9D4A-4F65-B13A-644E89A7918D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {EEACDE24-9D4A-4F65-B13A-644E89A7918D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EEACDE24-9D4A-4F65-B13A-644E89A7918D}.Debug|x64.ActiveCfg = Debug|Any CPU - {EEACDE24-9D4A-4F65-B13A-644E89A7918D}.Debug|x64.Build.0 = Debug|Any CPU - {EEACDE24-9D4A-4F65-B13A-644E89A7918D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {EEACDE24-9D4A-4F65-B13A-644E89A7918D}.Release|Any CPU.Build.0 = Release|Any CPU - {EEACDE24-9D4A-4F65-B13A-644E89A7918D}.Release|x64.ActiveCfg = Release|Any CPU - {EEACDE24-9D4A-4F65-B13A-644E89A7918D}.Release|x64.Build.0 = Release|Any CPU - {1221F32F-7310-49FF-94DD-2BCF570E03F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1221F32F-7310-49FF-94DD-2BCF570E03F2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1221F32F-7310-49FF-94DD-2BCF570E03F2}.Debug|x64.ActiveCfg = Debug|Any CPU - {1221F32F-7310-49FF-94DD-2BCF570E03F2}.Debug|x64.Build.0 = Debug|Any CPU - {1221F32F-7310-49FF-94DD-2BCF570E03F2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1221F32F-7310-49FF-94DD-2BCF570E03F2}.Release|Any CPU.Build.0 = Release|Any CPU - {1221F32F-7310-49FF-94DD-2BCF570E03F2}.Release|x64.ActiveCfg = Release|Any CPU - {1221F32F-7310-49FF-94DD-2BCF570E03F2}.Release|x64.Build.0 = Release|Any CPU {9208B446-A7E0-4B5A-A42D-37E63B76E875}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9208B446-A7E0-4B5A-A42D-37E63B76E875}.Debug|Any CPU.Build.0 = Debug|Any CPU {9208B446-A7E0-4B5A-A42D-37E63B76E875}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -2529,38 +2169,6 @@ Global {A5B30EEA-2DE1-4233-8584-936CB862191B}.Release|Any CPU.Build.0 = Release|Any CPU {A5B30EEA-2DE1-4233-8584-936CB862191B}.Release|x64.ActiveCfg = Release|Any CPU {A5B30EEA-2DE1-4233-8584-936CB862191B}.Release|x64.Build.0 = Release|Any CPU - {6E853D47-6C4F-4102-85A2-31EB172FB864}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6E853D47-6C4F-4102-85A2-31EB172FB864}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6E853D47-6C4F-4102-85A2-31EB172FB864}.Debug|x64.ActiveCfg = Debug|Any CPU - {6E853D47-6C4F-4102-85A2-31EB172FB864}.Debug|x64.Build.0 = Debug|Any CPU - {6E853D47-6C4F-4102-85A2-31EB172FB864}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6E853D47-6C4F-4102-85A2-31EB172FB864}.Release|Any CPU.Build.0 = Release|Any CPU - {6E853D47-6C4F-4102-85A2-31EB172FB864}.Release|x64.ActiveCfg = Release|Any CPU - {6E853D47-6C4F-4102-85A2-31EB172FB864}.Release|x64.Build.0 = Release|Any CPU - {4B175C6B-F5BE-4B65-BFCC-A949CA5BC6A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {4B175C6B-F5BE-4B65-BFCC-A949CA5BC6A3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4B175C6B-F5BE-4B65-BFCC-A949CA5BC6A3}.Debug|x64.ActiveCfg = Debug|Any CPU - {4B175C6B-F5BE-4B65-BFCC-A949CA5BC6A3}.Debug|x64.Build.0 = Debug|Any CPU - {4B175C6B-F5BE-4B65-BFCC-A949CA5BC6A3}.Release|Any CPU.ActiveCfg = Release|Any CPU - {4B175C6B-F5BE-4B65-BFCC-A949CA5BC6A3}.Release|Any CPU.Build.0 = Release|Any CPU - {4B175C6B-F5BE-4B65-BFCC-A949CA5BC6A3}.Release|x64.ActiveCfg = Release|Any CPU - {4B175C6B-F5BE-4B65-BFCC-A949CA5BC6A3}.Release|x64.Build.0 = Release|Any CPU - {2B861EF5-124F-4D13-8291-F223B6588C35}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2B861EF5-124F-4D13-8291-F223B6588C35}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2B861EF5-124F-4D13-8291-F223B6588C35}.Debug|x64.ActiveCfg = Debug|Any CPU - {2B861EF5-124F-4D13-8291-F223B6588C35}.Debug|x64.Build.0 = Debug|Any CPU - {2B861EF5-124F-4D13-8291-F223B6588C35}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2B861EF5-124F-4D13-8291-F223B6588C35}.Release|Any CPU.Build.0 = Release|Any CPU - {2B861EF5-124F-4D13-8291-F223B6588C35}.Release|x64.ActiveCfg = Release|Any CPU - {2B861EF5-124F-4D13-8291-F223B6588C35}.Release|x64.Build.0 = Release|Any CPU - {62D22ED4-76A6-41EE-9121-992608E3590D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {62D22ED4-76A6-41EE-9121-992608E3590D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {62D22ED4-76A6-41EE-9121-992608E3590D}.Debug|x64.ActiveCfg = Debug|Any CPU - {62D22ED4-76A6-41EE-9121-992608E3590D}.Debug|x64.Build.0 = Debug|Any CPU - {62D22ED4-76A6-41EE-9121-992608E3590D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {62D22ED4-76A6-41EE-9121-992608E3590D}.Release|Any CPU.Build.0 = Release|Any CPU - {62D22ED4-76A6-41EE-9121-992608E3590D}.Release|x64.ActiveCfg = Release|Any CPU - {62D22ED4-76A6-41EE-9121-992608E3590D}.Release|x64.Build.0 = Release|Any CPU {83310F46-E1C7-4438-B32A-9F6F7EA13FCF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {83310F46-E1C7-4438-B32A-9F6F7EA13FCF}.Debug|Any CPU.Build.0 = Debug|Any CPU {83310F46-E1C7-4438-B32A-9F6F7EA13FCF}.Debug|x64.ActiveCfg = Debug|Any CPU @@ -2577,38 +2185,6 @@ Global {8A51A2A9-FBF4-40DC-AD89-AD3B9D3A50DC}.Release|Any CPU.Build.0 = Release|Any CPU {8A51A2A9-FBF4-40DC-AD89-AD3B9D3A50DC}.Release|x64.ActiveCfg = Release|Any CPU {8A51A2A9-FBF4-40DC-AD89-AD3B9D3A50DC}.Release|x64.Build.0 = Release|Any CPU - {43389D12-17E1-4F07-9A42-5CFCC24D08B2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {43389D12-17E1-4F07-9A42-5CFCC24D08B2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {43389D12-17E1-4F07-9A42-5CFCC24D08B2}.Debug|x64.ActiveCfg = Debug|Any CPU - {43389D12-17E1-4F07-9A42-5CFCC24D08B2}.Debug|x64.Build.0 = Debug|Any CPU - {43389D12-17E1-4F07-9A42-5CFCC24D08B2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {43389D12-17E1-4F07-9A42-5CFCC24D08B2}.Release|Any CPU.Build.0 = Release|Any CPU - {43389D12-17E1-4F07-9A42-5CFCC24D08B2}.Release|x64.ActiveCfg = Release|Any CPU - {43389D12-17E1-4F07-9A42-5CFCC24D08B2}.Release|x64.Build.0 = Release|Any CPU - {289BF8C8-968F-4105-A65E-C1C6FD8857F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {289BF8C8-968F-4105-A65E-C1C6FD8857F2}.Debug|Any CPU.Build.0 = Debug|Any CPU - {289BF8C8-968F-4105-A65E-C1C6FD8857F2}.Debug|x64.ActiveCfg = Debug|Any CPU - {289BF8C8-968F-4105-A65E-C1C6FD8857F2}.Debug|x64.Build.0 = Debug|Any CPU - {289BF8C8-968F-4105-A65E-C1C6FD8857F2}.Release|Any CPU.ActiveCfg = Release|Any CPU - {289BF8C8-968F-4105-A65E-C1C6FD8857F2}.Release|Any CPU.Build.0 = Release|Any CPU - {289BF8C8-968F-4105-A65E-C1C6FD8857F2}.Release|x64.ActiveCfg = Release|Any CPU - {289BF8C8-968F-4105-A65E-C1C6FD8857F2}.Release|x64.Build.0 = Release|Any CPU - {9B4F7AC1-97FD-400A-9810-7F7672FBAF65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9B4F7AC1-97FD-400A-9810-7F7672FBAF65}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9B4F7AC1-97FD-400A-9810-7F7672FBAF65}.Debug|x64.ActiveCfg = Debug|Any CPU - {9B4F7AC1-97FD-400A-9810-7F7672FBAF65}.Debug|x64.Build.0 = Debug|Any CPU - {9B4F7AC1-97FD-400A-9810-7F7672FBAF65}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9B4F7AC1-97FD-400A-9810-7F7672FBAF65}.Release|Any CPU.Build.0 = Release|Any CPU - {9B4F7AC1-97FD-400A-9810-7F7672FBAF65}.Release|x64.ActiveCfg = Release|Any CPU - {9B4F7AC1-97FD-400A-9810-7F7672FBAF65}.Release|x64.Build.0 = Release|Any CPU - {7E11AD82-5E5C-43E9-B7C3-77A127B628E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7E11AD82-5E5C-43E9-B7C3-77A127B628E8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7E11AD82-5E5C-43E9-B7C3-77A127B628E8}.Debug|x64.ActiveCfg = Debug|Any CPU - {7E11AD82-5E5C-43E9-B7C3-77A127B628E8}.Debug|x64.Build.0 = Debug|Any CPU - {7E11AD82-5E5C-43E9-B7C3-77A127B628E8}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7E11AD82-5E5C-43E9-B7C3-77A127B628E8}.Release|Any CPU.Build.0 = Release|Any CPU - {7E11AD82-5E5C-43E9-B7C3-77A127B628E8}.Release|x64.ActiveCfg = Release|Any CPU - {7E11AD82-5E5C-43E9-B7C3-77A127B628E8}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -2627,7 +2203,6 @@ Global {FB0F5EB7-AA72-4D54-BD8D-43B173E54E19} = {DC578D74-98F0-4F19-A230-CFA8DAEE0AF1} {1EE02441-263C-458E-A774-9D522BFFBB3F} = {DC578D74-98F0-4F19-A230-CFA8DAEE0AF1} {76F1DBC4-1826-4EC6-92BA-FF7843D993CD} = {DC578D74-98F0-4F19-A230-CFA8DAEE0AF1} - {8A9DBB76-6618-4982-87D7-6CBD8375EB15} = {DC578D74-98F0-4F19-A230-CFA8DAEE0AF1} {0DC9DE6E-E6D8-466A-8325-93822428CB87} = {D2DF986D-5EA6-40ED-93F3-2CF3A035F26B} {523EB315-1A01-4F13-9EDE-266FE8111AB6} = {0DC9DE6E-E6D8-466A-8325-93822428CB87} {0E72ABDD-C7CF-40EF-8E78-ED4B8B85E4C5} = {0DC9DE6E-E6D8-466A-8325-93822428CB87} @@ -2655,13 +2230,6 @@ Global {D2009F94-EA9C-44F0-B210-C373F9FE3641} = {8A17DE9A-258E-49E1-9EB2-B8B3F374A470} {6586614A-39D8-412E-814C-3314F8A7909A} = {2D179841-A866-4ED4-8B42-97CCE4D6496D} {400854AA-AE3F-40EC-B5BF-C9F1257490AA} = {FB0F5EB7-AA72-4D54-BD8D-43B173E54E19} - {8A89304F-709C-4A3A-9FA6-D88761B8231B} = {8A9DBB76-6618-4982-87D7-6CBD8375EB15} - {C37FB18D-FBA1-49DF-96CD-24D6F65B66E1} = {8A89304F-709C-4A3A-9FA6-D88761B8231B} - {C6006F72-B9F9-4E57-B2A9-63B2D0EA5EF0} = {8A89304F-709C-4A3A-9FA6-D88761B8231B} - {89D032A8-14FB-4C2F-A112-CB7FAFCA2B62} = {8A9DBB76-6618-4982-87D7-6CBD8375EB15} - {1F263FE5-649F-441D-AA55-B6012439E27F} = {8A9DBB76-6618-4982-87D7-6CBD8375EB15} - {F0A72797-A0E3-48BF-9E2E-34FD5ADD3441} = {8A9DBB76-6618-4982-87D7-6CBD8375EB15} - {D2D5E0AD-AEE6-495F-96EA-5B9B1F17CE8F} = {8A9DBB76-6618-4982-87D7-6CBD8375EB15} {AF921AB1-64D1-4478-AB49-192F3EE416FC} = {5944A182-13B8-4DA6-AEE2-0A01E64A9648} {56917740-626B-42D5-8BB8-6895F79FB7D2} = {5944A182-13B8-4DA6-AEE2-0A01E64A9648} {706DA866-6226-430F-AB4D-98FEE7B0DDB0} = {5944A182-13B8-4DA6-AEE2-0A01E64A9648} @@ -2701,7 +2269,6 @@ Global {FD6300FB-5601-4516-BF1C-936690ECE026} = {950DA7D0-48C1-42BA-8E8F-F72C0DCE41C4} {830DDDD7-74A5-431B-92E4-C9641D0A10E4} = {950DA7D0-48C1-42BA-8E8F-F72C0DCE41C4} {B7709311-A885-49E1-9078-B6CC8406B916} = {950DA7D0-48C1-42BA-8E8F-F72C0DCE41C4} - {383995FF-B661-4E15-A830-640FC5BA8A1F} = {950DA7D0-48C1-42BA-8E8F-F72C0DCE41C4} {62E888C1-9FCD-413D-91CB-1F2DD3D356E3} = {950DA7D0-48C1-42BA-8E8F-F72C0DCE41C4} {41769FBF-91A8-48D1-B3BB-CAE4C814E7CD} = {3198630F-C09B-40AE-B9A1-E79249296E48} {B92E29C1-4C44-4C5D-B3B2-22AAF07A62A0} = {41769FBF-91A8-48D1-B3BB-CAE4C814E7CD} @@ -2804,19 +2371,6 @@ Global {22BE7D35-34C4-49FA-B20E-B69289C10B5E} = {68491FED-7441-4B58-989D-DF6F198FC91A} {2959DC55-E0E6-42D7-9DD1-9DE14841EF63} = {68491FED-7441-4B58-989D-DF6F198FC91A} {E8681596-D4BF-484A-A428-06D749FD4C5D} = {2959DC55-E0E6-42D7-9DD1-9DE14841EF63} - {F0D73CEC-6CB7-4BF1-B6DD-29D785BF9A5B} = {383995FF-B661-4E15-A830-640FC5BA8A1F} - {A4D8F3F8-F0ED-49F9-8C50-3F3311A98B2F} = {383995FF-B661-4E15-A830-640FC5BA8A1F} - {9BD06CA5-0169-418B-A8C8-60584EEDCEFE} = {383995FF-B661-4E15-A830-640FC5BA8A1F} - {22EC5EB8-52C1-4BC2-BDD3-09D5DC6BFA3F} = {383995FF-B661-4E15-A830-640FC5BA8A1F} - {8E7F9812-2DF1-483C-93AB-F8BBC18D9761} = {383995FF-B661-4E15-A830-640FC5BA8A1F} - {D4D2DA65-D16D-4236-ABD0-492681944D00} = {6042AE23-A07E-4F6F-B1C3-F17617AEB722} - {EC7A08E9-3355-486B-BA30-41A1F8CAC5F5} = {383995FF-B661-4E15-A830-640FC5BA8A1F} - {5DD4C255-EF06-4ECE-A0C3-1CF0EDB5193C} = {EC7A08E9-3355-486B-BA30-41A1F8CAC5F5} - {74149D50-9DED-45D7-9C52-5F74BEE6B80D} = {EC7A08E9-3355-486B-BA30-41A1F8CAC5F5} - {975AAE87-E410-4FFF-8A9E-6FD7E020A3C9} = {EC7A08E9-3355-486B-BA30-41A1F8CAC5F5} - {373F9664-5B59-4068-B1E2-61CDD3B2F760} = {EC7A08E9-3355-486B-BA30-41A1F8CAC5F5} - {950FE681-764C-4B75-BB95-938A9F17B2D9} = {EC7A08E9-3355-486B-BA30-41A1F8CAC5F5} - {F110D91A-F1A9-4627-85C8-501F814FED26} = {E4AD67C8-9255-4013-A3C4-962694399770} {16B18299-3640-4FA8-A4E6-74B1EB741301} = {1B2FF31A-187A-4D36-AD81-1ABD9BCF9044} {1B2FF31A-187A-4D36-AD81-1ABD9BCF9044} = {62E888C1-9FCD-413D-91CB-1F2DD3D356E3} {4231AB12-3FB7-408E-B7C2-9CC0FFB710B1} = {1B2FF31A-187A-4D36-AD81-1ABD9BCF9044} @@ -2884,9 +2438,6 @@ Global {3FADF704-2581-47AC-A1F7-07091B6328A1} = {A7081ADB-DB21-4678-8510-A5367D470743} {EEB2D542-5A2C-4E18-A0E6-72844C359DAD} = {3FADF704-2581-47AC-A1F7-07091B6328A1} {E47D82C7-7A1C-4BEF-ACA8-43971FD6C6BA} = {64E37EF0-0C85-4F02-A430-6D3B1DBF13DF} - {5E0E61DA-06FF-4F08-9C76-0A8856C90EF5} = {8A9DBB76-6618-4982-87D7-6CBD8375EB15} - {356C5F47-025F-4ED6-8E8A-8745E181C455} = {5E0E61DA-06FF-4F08-9C76-0A8856C90EF5} - {C2E9EDAE-2558-4899-A486-917AE7A5D24F} = {5E0E61DA-06FF-4F08-9C76-0A8856C90EF5} {8CDAF37E-3DB1-4573-B5AA-376C93A8D299} = {64E37EF0-0C85-4F02-A430-6D3B1DBF13DF} {49B51B95-3DC5-45BD-B91A-3056FF5014B5} = {8CDAF37E-3DB1-4573-B5AA-376C93A8D299} {DD899DC4-A2B7-4C7B-A644-EDB56A61145C} = {8CDAF37E-3DB1-4573-B5AA-376C93A8D299} @@ -2903,9 +2454,6 @@ Global {B7AEC624-6A40-42E7-BDB5-4487ACE48CE4} = {5B129E6F-8CB7-4E2E-9F3E-C59CF22C9CA9} {66B1723A-D578-418C-B21C-2C3B5CBD1180} = {5BE84027-D1B4-4264-A7EC-E84658350CA7} {6088C3D3-E17E-41BC-A21F-F222F5123DF1} = {D10FC534-0091-42B4-809F-82C1E2164ED5} - {12FD44BF-B1CD-4B8A-9C7F-318ED6FE48FD} = {8A9DBB76-6618-4982-87D7-6CBD8375EB15} - {A04C3ECC-51BB-43A9-9C38-2305AB31F60D} = {6042AE23-A07E-4F6F-B1C3-F17617AEB722} - {21317D81-BED0-46F0-8FBC-A9B7F1C7F2FD} = {E4AD67C8-9255-4013-A3C4-962694399770} {2D87B9C4-E2FA-47DB-B6B9-BAFF8E0B7558} = {F83E3E53-2DFE-4B1F-B988-204CA4A42572} {AE12559A-5C8F-4590-9B18-B935155B15C5} = {F83E3E53-2DFE-4B1F-B988-204CA4A42572} {6FB69510-B616-4F6D-82CC-36AD52CEF4D3} = {5944A182-13B8-4DA6-AEE2-0A01E64A9648} @@ -2915,16 +2463,10 @@ Global {3AAD9D87-BC2D-446C-B56B-60F8A1492C30} = {C2FAC276-9D6E-498A-BBA2-F3F14ADF4D0D} {FCD6DF86-4E3B-4CDC-9849-28884B3B40D8} = {C2FAC276-9D6E-498A-BBA2-F3F14ADF4D0D} {8BF4E6EC-4BF7-43B6-B11B-9047759E4FAE} = {D10FC534-0091-42B4-809F-82C1E2164ED5} - {AF718133-0A37-4F1A-96DF-61C3D9836B7F} = {8A9DBB76-6618-4982-87D7-6CBD8375EB15} - {F3C2B14A-C350-4E30-9EB5-5BFCCC4EEB5B} = {383995FF-B661-4E15-A830-640FC5BA8A1F} - {5130EF56-9225-453C-A9AF-EB80A8A19E18} = {EC7A08E9-3355-486B-BA30-41A1F8CAC5F5} {2BD60D01-E28C-4887-BD48-49C950650E91} = {2959DC55-E0E6-42D7-9DD1-9DE14841EF63} {F6BD4124-2DCA-453E-B73C-D9DB6323CCDC} = {D2DF986D-5EA6-40ED-93F3-2CF3A035F26B} {1C180CB0-DF6B-4AC8-815D-6EE2CBBA676F} = {2959DC55-E0E6-42D7-9DD1-9DE14841EF63} {4F1E9488-FAC5-4966-90E6-F1DFE35F8370} = {F6BD4124-2DCA-453E-B73C-D9DB6323CCDC} - {32E0798A-5FBB-4EF3-9D25-2E7FFC64149C} = {383995FF-B661-4E15-A830-640FC5BA8A1F} - {89A12439-90DF-428D-8AB0-3E91540676C4} = {8A9DBB76-6618-4982-87D7-6CBD8375EB15} - {D54C1134-1805-4DD7-84A6-BF680784443C} = {EC7A08E9-3355-486B-BA30-41A1F8CAC5F5} {CBF61DB2-035B-4084-9872-0350C4DDA9EE} = {E8681596-D4BF-484A-A428-06D749FD4C5D} {5BBCCDEC-C77C-4A68-9911-C69B38666E18} = {68491FED-7441-4B58-989D-DF6F198FC91A} {6019A267-5675-44D2-89DB-A2A51FCEE523} = {5BBCCDEC-C77C-4A68-9911-C69B38666E18} @@ -2942,29 +2484,15 @@ Global {1C969B47-5901-4BBF-BC99-8602CC4A1A4F} = {C591947F-B9DD-4B6E-921B-C175A009FFDC} {94191595-7D89-4986-ADD5-620032811EAC} = {0FB9A049-E04C-40C7-9727-FD8B1265DF87} {BC848CB9-1065-4FC5-8CB4-8EE733E18E50} = {C591947F-B9DD-4B6E-921B-C175A009FFDC} - {B57859AD-720E-41D2-9C15-85F49AC73D18} = {383995FF-B661-4E15-A830-640FC5BA8A1F} - {30A143AF-4E9D-457E-BDAE-DFBC5A262F4A} = {383995FF-B661-4E15-A830-640FC5BA8A1F} {CD5365A1-1781-4088-A9A2-EC58F3581D3B} = {4231AB12-3FB7-408E-B7C2-9CC0FFB710B1} {2A691CCB-E2A0-408D-BC2D-7D2157B3E85A} = {CD5365A1-1781-4088-A9A2-EC58F3581D3B} - {EEACDE24-9D4A-4F65-B13A-644E89A7918D} = {8A9DBB76-6618-4982-87D7-6CBD8375EB15} {3C12BE69-247B-4448-9700-0ACEE8440A34} = {E8B3FB42-C450-4B12-9C2C-7B9A02B616BB} - {1221F32F-7310-49FF-94DD-2BCF570E03F2} = {EC7A08E9-3355-486B-BA30-41A1F8CAC5F5} {9208B446-A7E0-4B5A-A42D-37E63B76E875} = {3C12BE69-247B-4448-9700-0ACEE8440A34} {02591EE4-1033-4575-984F-7AB290E7C6FA} = {48853497-9C2D-4ADA-AED3-61280AF1418D} {A5B30EEA-2DE1-4233-8584-936CB862191B} = {02591EE4-1033-4575-984F-7AB290E7C6FA} - {6E853D47-6C4F-4102-85A2-31EB172FB864} = {383995FF-B661-4E15-A830-640FC5BA8A1F} - {4B175C6B-F5BE-4B65-BFCC-A949CA5BC6A3} = {8A9DBB76-6618-4982-87D7-6CBD8375EB15} - {2B861EF5-124F-4D13-8291-F223B6588C35} = {6042AE23-A07E-4F6F-B1C3-F17617AEB722} - {62D22ED4-76A6-41EE-9121-992608E3590D} = {E4AD67C8-9255-4013-A3C4-962694399770} - {E4AD67C8-9255-4013-A3C4-962694399770} = {EC7A08E9-3355-486B-BA30-41A1F8CAC5F5} - {6042AE23-A07E-4F6F-B1C3-F17617AEB722} = {383995FF-B661-4E15-A830-640FC5BA8A1F} {64B54122-44F1-4379-9422-953EF706A3A6} = {5944A182-13B8-4DA6-AEE2-0A01E64A9648} {83310F46-E1C7-4438-B32A-9F6F7EA13FCF} = {64B54122-44F1-4379-9422-953EF706A3A6} {8A51A2A9-FBF4-40DC-AD89-AD3B9D3A50DC} = {64B54122-44F1-4379-9422-953EF706A3A6} - {43389D12-17E1-4F07-9A42-5CFCC24D08B2} = {6042AE23-A07E-4F6F-B1C3-F17617AEB722} - {289BF8C8-968F-4105-A65E-C1C6FD8857F2} = {E4AD67C8-9255-4013-A3C4-962694399770} - {9B4F7AC1-97FD-400A-9810-7F7672FBAF65} = {6042AE23-A07E-4F6F-B1C3-F17617AEB722} - {7E11AD82-5E5C-43E9-B7C3-77A127B628E8} = {E4AD67C8-9255-4013-A3C4-962694399770} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {40383055-CC50-4600-AD9A-53C14F620D03} diff --git a/src/Contrib/Configuration/ConfigurationApi/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Masa.Contrib.Configuration.ConfigurationApi.Dcc.csproj b/src/Contrib/Configuration/ConfigurationApi/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Masa.Contrib.Configuration.ConfigurationApi.Dcc.csproj index 1a4c6b640..0c614da84 100644 --- a/src/Contrib/Configuration/ConfigurationApi/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Masa.Contrib.Configuration.ConfigurationApi.Dcc.csproj +++ b/src/Contrib/Configuration/ConfigurationApi/Masa.Contrib.Configuration.ConfigurationApi.Dcc/Masa.Contrib.Configuration.ConfigurationApi.Dcc.csproj @@ -6,11 +6,11 @@ + - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/AlertClient.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/AlertClient.cs deleted file mode 100644 index 326962bfc..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/AlertClient.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Alert; - -public class AlertClient : IAlertClient -{ - public AlertClient(ICaller caller) - { - AlarmRuleService = new AlarmRuleService(caller); - AlarmHistoryService = new AlarmHistoryService(caller); - } - - public IAlarmRuleService AlarmRuleService { get; } - - public IAlarmHistoryService AlarmHistoryService { get; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Constants.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Constants.cs deleted file mode 100644 index 48d4cb566..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Constants.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Masa.Contrib.StackSdks.Alert; - -internal static class Constants -{ - public const string DEFAULT_CLIENT_NAME = "masa.contrib.basicability.alert"; -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Masa.Contrib.StackSdks.Alert.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Masa.Contrib.StackSdks.Alert.csproj deleted file mode 100644 index 2df5dccaf..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Masa.Contrib.StackSdks.Alert.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - enable - enable - - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Service/AlarmHistoryService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Service/AlarmHistoryService.cs deleted file mode 100644 index c37cf7b59..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Service/AlarmHistoryService.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Alert.Service; - -public class AlarmHistoryService : IAlarmHistoryService -{ - readonly ICaller _caller; - readonly string _party = "api/v1/AlarmHistories"; - - public AlarmHistoryService(ICaller caller) - { - _caller = caller; - } - - public async Task ChangeHandlerAsync(Guid id, Guid handler) - { - var requestUri = $"{_party}/{id}/change-handler?handler={handler}"; - await _caller.PostAsync(requestUri, new { }); - } - - public async Task CompletedAsync(Guid id) - { - var requestUri = $"{_party}/{id}/complete"; - await _caller.PostAsync(requestUri, new { }); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Service/AlarmRuleService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Service/AlarmRuleService.cs deleted file mode 100644 index 38586c86b..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/Service/AlarmRuleService.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Alert.Service; - -public class AlarmRuleService : IAlarmRuleService -{ - readonly ICaller _caller; - readonly string _party = "api/v1/AlarmRules"; - - public AlarmRuleService(ICaller caller) - { - _caller = caller; - } - - public async Task CreateAsync(AlarmRuleUpsertModel options) - { - var requestUri = $"{_party}"; - return await _caller.PostAsync(requestUri, options); - } - - public async Task UpdateAsync(Guid id, AlarmRuleUpsertModel options) - { - var requestUri = $"{_party}/{id}"; - await _caller.PutAsync(requestUri, options); - } - - public async Task DeleteAsync(Guid id) - { - var requestUri = $"{_party}/{id}"; - await _caller.DeleteAsync(requestUri, null); - } - - public async Task GetAsync(Guid id) - { - var requestUri = $"{_party}/{id}"; - return await _caller.GetAsync(requestUri); - } - - public async Task SetIsEnabledAsync(Guid id, bool isEnabled) - { - var requestUri = $"{_party}/{id}/enabled/{isEnabled}"; - await _caller.PutAsync(requestUri, null); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/ServiceCollectionExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/ServiceCollectionExtensions.cs deleted file mode 100644 index 2630dedf0..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Microsoft.Extensions.DependencyInjection; - -public static class ServiceCollectionExtensions -{ - public static IServiceCollection AddAlertClient(this IServiceCollection services, string alertServiceBaseAddress) - { - MasaArgumentException.ThrowIfNullOrEmpty(alertServiceBaseAddress); - - return services.AddAlertClient(callerBuilder => - { - callerBuilder.UseHttpClient(builder => - { - builder.Configure = opt => opt.BaseAddress = new Uri(alertServiceBaseAddress); - }) - .UseAuthentication(); - }); - } - - public static IServiceCollection AddAlertClient(this IServiceCollection services, Func alertServiceBaseAddressFunc) - { - MasaArgumentException.ThrowIfNull(alertServiceBaseAddressFunc); - - return services.AddAlertClient(callerBuilder => - { - callerBuilder - .UseHttpClient(builder => - { - builder.BaseAddress = alertServiceBaseAddressFunc.Invoke(); - }) - .UseAuthentication(); - }); - } - - public static IServiceCollection AddAlertClient(this IServiceCollection services, Action callerBuilder) - { - MasaArgumentException.ThrowIfNull(callerBuilder); - - if (services.Any(service => service.ServiceType == typeof(IAlertClient))) - return services; - - services.AddCaller(DEFAULT_CLIENT_NAME, callerBuilder); - - services.AddScoped(serviceProvider => - { - var caller = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); - var alertCaching = new AlertClient(caller); - return alertCaching; - }); - - MasaApp.TrySetServiceCollection(services); - return services; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/_Imports.cs deleted file mode 100644 index c134a0b7b..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Alert/_Imports.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Data; -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Alert; -global using Masa.BuildingBlocks.StackSdks.Alert.Model; -global using Masa.BuildingBlocks.StackSdks.Alert.Service; -global using Masa.Contrib.StackSdks.Alert; -global using Masa.Contrib.StackSdks.Alert.Service; -global using Masa.Contrib.StackSdks.Isolation; -global using static Masa.Contrib.StackSdks.Alert.Constants; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/AuthClient.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/AuthClient.cs deleted file mode 100644 index d2c08b9d3..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/AuthClient.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth; - -public class AuthClient : IAuthClient -{ - public AuthClient(ICaller caller, IMultiEnvironmentUserContext userContext, IMultilevelCacheClient multilevelCacheClient) - { - UserService = new UserService(caller, userContext, multilevelCacheClient); - SubjectService = new SubjectService(caller); - TeamService = new TeamService(caller, userContext); - ProjectService = new ProjectService(caller, userContext); - PermissionService = new PermissionService(caller, userContext); - CustomLoginService = new CustomLoginService(caller); - ThirdPartyIdpService = new ThirdPartyIdpService(caller, multilevelCacheClient); - } - - public IUserService UserService { get; } - - public ISubjectService SubjectService { get; } - - public ITeamService TeamService { get; } - - public IPermissionService PermissionService { get; } - - public IProjectService ProjectService { get; } - - public ICustomLoginService CustomLoginService { get; } - - public IThirdPartyIdpService ThirdPartyIdpService { get; } -} - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Constants.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Constants.cs deleted file mode 100644 index 61c996418..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Constants.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth; - -public static class Constants -{ - public const string DEFAULT_CLIENT_NAME = "masa.contrib.basicability.auth"; - public const string DEFAULT_SSO_CLIENT_NAME = "masa.contrib.basicability.auth.sso"; - public const string DEFAULT_SUBSCRIBE_KEY_PREFIX = "masa.auth:"; -} - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Masa.Contrib.StackSdks.Auth.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Masa.Contrib.StackSdks.Auth.csproj deleted file mode 100644 index a81ee8aee..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Masa.Contrib.StackSdks.Auth.csproj +++ /dev/null @@ -1,27 +0,0 @@ - - - - enable - enable - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Model/AuthClientMultilevelCacheProvider.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Model/AuthClientMultilevelCacheProvider.cs deleted file mode 100644 index 82ec8d517..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Model/AuthClientMultilevelCacheProvider.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Model; - -public class AuthClientMultilevelCacheProvider -{ - readonly IMultilevelCacheClientFactory _clientFactory; - IMultilevelCacheClient? _multilevelCacheClient; - - public AuthClientMultilevelCacheProvider(IMultilevelCacheClientFactory clientFactory) - { - _clientFactory = clientFactory; - } - - public IMultilevelCacheClient GetMultilevelCacheClient() - { - if (_multilevelCacheClient == null) - { - _multilevelCacheClient = _clientFactory.Create(DEFAULT_CLIENT_NAME); - } - return _multilevelCacheClient; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/README.md b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/README.md deleted file mode 100644 index 6076c77a0..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/README.md +++ /dev/null @@ -1,46 +0,0 @@ -[中](README.zh-CN.md) | EN - -## Masa.Contrib.StackSdks.Auth - -Injecting IAuthClient interface,cal the service to obtain the capabilities provided by the auth SDK. -SDK need to get current user ID dependency Masa.Contrib.Authentication.Identity(../../Identity/Masa.Contrib.Authentication.Identity/README.zh,Therefore,the identitymodel service needs to be added before use. - -### Service Introduction - -```c# -IAuthClient -├── UserService -├── SubjectService -├── TeamService -├── PermissionService -└── ProjectService -``` - -### Use Introduction - -#### Install dependent package - -```C# -Install-Package Masa.Contrib.StackSdks.Auth -``` - -#### Register auth service - -```C# -builder.Services.AddAuthClient("http://authservice.com"); -``` - -> `http://authservice.com` is auth service address - -#### Dependency injection IAuthClient - -```c# -var app = builder.Build(); - -app.MapGet("/GetTeams", ([FromServices] IAuthClient authClient) => -{ - return authClient.TeamService.GetAllAsync(); -}); - -app.Run(); -``` diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/README.zh-CN.md b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/README.zh-CN.md deleted file mode 100644 index 1fd4e39b0..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/README.zh-CN.md +++ /dev/null @@ -1,45 +0,0 @@ -中 | [EN](README.md) - -## Masa.Contrib.StackSdks.Auth - -通过注入IAuthClient接口,调用对应Service获取Auth SDK 提供的能力。 -SDK获取当前用户ID依赖Masa.Contrib.Identity.IdentityModel(../../Identity/Masa.Contrib.Authentication.Identity/README.zh-CN.zh,所以使用前需添加IdentityModel服务。 - -### 服务介绍 -```c# -IAuthClient -├── UserService 用户服务 -├── SubjectService 全局搜索用户、角色、团队、组织架构 -├── TeamService 团队服务 -├── PermissionService 权限、菜单服务 -└── ProjectService 全局导航服务 -``` - -### 使用介绍 - -#### 安装依赖包 - -```C# -Install-Package Masa.Contrib.StackSdks.Auth -``` - -#### 注册相关服务 - -```C# -builder.Services.AddAuthClient("http://authservice.com"); -``` - -> `http://authservice.com` 为Auth后台服务地址 - -#### 依赖注入IAuthClient - -```c# -var app = builder.Build(); - -app.MapGet("/GetTeams", ([FromServices] IAuthClient authClient) => -{ - return authClient.TeamService.GetAllAsync(); -}); - -app.Run(); -``` diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/CustomLoginService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/CustomLoginService.cs deleted file mode 100644 index 3256e3369..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/CustomLoginService.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Service; - -public class CustomLoginService : ICustomLoginService -{ - readonly ICaller _caller; - - public CustomLoginService(ICaller caller) - { - _caller = caller; - } - - public async Task GetCustomLoginByClientIdAsync(string environment, string clientId) - { - var requestUri = $"api/sso/customLogin/getByClientId"; - return await _caller.GetAsync(requestUri, new { environment, clientId }); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/LoginService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/LoginService.cs deleted file mode 100644 index d026caec0..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/LoginService.cs +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Service; - -public class LoginService : ILoginService -{ - readonly IHttpClientFactory _httpClientFactory; - - public LoginService(IHttpClientFactory httpClientFactory) - { - _httpClientFactory = httpClientFactory; - } - - public async Task LoginByPasswordAsync(LoginByPasswordModel login) - { - var httpClient = CreateHttpClient(); - var request = new PasswordTokenRequest() - { - ClientId = login.ClientId, - ClientSecret = login.ClientSecret, - GrantType = GrantType.RESOURCE_OWNER_PASSWORD, - UserName = login.Account, - Password = login.Password, - Scope = string.Join(' ', login.Scope), - }; - var tokenResponse = await httpClient.RequestPasswordTokenAsync(request); - - return ToModel(tokenResponse); - } - - public async Task LoginByPhoneNumberAsync(LoginByPhoneNumberFromSsoModel login) - { - var client = CreateHttpClient(); - - var paramter = new Dictionary - { - ["client_Id"] = login.ClientId, - ["client_secret"] = login.ClientSecret, - ["grant_type"] = GrantType.PHONE_CODE, - ["scope"] = string.Join(' ', login.Scope), - ["PhoneNumber"] = login.PhoneNumber, - ["code"] = login.Code - }; - - var tokenResponse = await RequestTokenRawAsync(client, paramter); - - return ToModel(tokenResponse); - } - - public async Task LoginByThirdPartyIdpAsync(LoginByThirdPartyIdpModel login) - { - var client = CreateHttpClient(); - - var paramter = new Dictionary - { - ["client_Id"] = login.ClientId, - ["client_secret"] = login.ClientSecret, - ["grant_type"] = GrantType.THIRD_PARTY_IDP, - ["scope"] = string.Join(' ', login.Scope), - ["scheme"] = login.Scheme, - ["code"] = login.Code ?? "", - ["idToken"] = login.IdToken ?? "", - }; - - var tokenResponse = await RequestTokenRawAsync(client, paramter); - var tokenModel = ToModel(tokenResponse); - var thirdPartyUser = tokenResponse.Json.GetProperty("thirdPartyUserData").Deserialize(); - var registerSuccess = tokenResponse.Json.TryGetBoolean("registerSuccess"); - - return new LoginByThirdPartyIdpResultModel - { - ThirdPartyIdpLoginResultType = registerSuccess is true ? ThirdPartyIdpLoginResultTypes.Success : ThirdPartyIdpLoginResultTypes.NotRegister, - Token = tokenModel, - ThirdPartyIdentity = thirdPartyUser - }; - } - - public async Task LoginByLdapAsync(LoginByLdapModel login) - { - var client = CreateHttpClient(); - - var paramter = new Dictionary - { - ["client_Id"] = login.ClientId, - ["client_secret"] = login.ClientSecret, - ["grant_type"] = GrantType.LDAP, - ["scope"] = string.Join(' ', login.Scope), - ["userName"] = login.UserName, - ["scheme"] = login.Scheme - }; - - var tokenResponse = await RequestTokenRawAsync(client, paramter); - - return ToModel(tokenResponse); - } - - HttpClient CreateHttpClient() - { - return _httpClientFactory.CreateClient(DEFAULT_SSO_CLIENT_NAME); - } - - static async Task GetDiscoveryDocumentAsync(HttpClient httpClient) - { - var disco = await httpClient.GetDiscoveryDocumentAsync(); - if (disco.IsError) - throw new UserFriendlyException(disco.Error); - - return disco; - } - - static async Task RequestTokenRawAsync(HttpClient httpClient, Dictionary paramter) - { - var disco = await GetDiscoveryDocumentAsync(httpClient); - var tokenResponse = await httpClient.RequestTokenRawAsync(disco.TokenEndpoint, new Parameters(paramter)); - - return tokenResponse; - } - - static TokenModel ToModel(TokenResponse tokenResponse) - { - if (tokenResponse.IsError) - throw new UserFriendlyException(tokenResponse.Error); - - return new TokenModel - { - AccessToken = tokenResponse.AccessToken, - IdentityToken = tokenResponse.IdentityToken, - RefreshToken = tokenResponse.RefreshToken, - ExpiresIn = tokenResponse.ExpiresIn, - }; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/PermissionService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/PermissionService.cs deleted file mode 100644 index 3c71c856d..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/PermissionService.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Service; - -public class PermissionService : IPermissionService -{ - readonly ICaller _caller; - readonly IUserContext _userContext; - - const string PART = "api/permission/"; - - public PermissionService(ICaller caller, IUserContext userContext) - { - _caller = caller; - _userContext = userContext; - } - - public async Task AuthorizedAsync(string appId, string code) - { - var userId = _userContext.GetUserId(); - var requestUri = $"{PART}authorized?appId={appId}&code={code}&userId={userId}"; - return await _caller.GetAsync(requestUri); - } - - public async Task> GetMenusAsync(string appId) - { - var userId = _userContext.GetUserId(); - var requestUri = $"{PART}menus?appId={appId}&userId={userId}"; - return await _caller.GetAsync>(requestUri, default) ?? new(); - } - - public async Task> GetElementPermissionsAsync(string appId) - { - var userId = _userContext.GetUserId(); - var requestUri = $"{PART}element-permissions?appId={appId}&userId={userId}"; - return await _caller.GetAsync>(requestUri, default) ?? new(); - } - - public async Task AddFavoriteMenuAsync(Guid menuId) - { - try - { - var userId = _userContext.GetUserId(); - await _caller.PutAsync($"{PART}addFavoriteMenu?permissionId={menuId}&userId={userId}", null); - return true; - } - catch - { - return false; - } - } - - public async Task RemoveFavoriteMenuAsync(Guid menuId) - { - try - { - var userId = _userContext.GetUserId(); - await _caller.PutAsync($"{PART}removeFavoriteMenu?permissionId={menuId}&userId={userId}", null); - return true; - } - catch - { - return false; - } - } - - public async Task> GetFavoriteMenuListAsync() - { - var userId = _userContext.GetUserId(); - var requestUri = $"{PART}menu-favorite-list?userId={userId}"; - return await _caller.GetAsync>(requestUri, default) ?? new(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/ProjectService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/ProjectService.cs deleted file mode 100644 index 76af16eba..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/ProjectService.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Service; - -public class ProjectService : IProjectService -{ - readonly ICaller _caller; - readonly IUserContext _userContext; - - const string PARTY = "api/project/"; - - public ProjectService(ICaller caller, IUserContext userContext) - { - _caller = caller; - _userContext = userContext; - } - - public async Task> GetGlobalNavigations() - { - var userId = _userContext.GetUserId(); - var requestUri = $"{PARTY}navigations?userId={userId}"; - return await _caller.GetAsync>(requestUri) ?? new(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/SubjectService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/SubjectService.cs deleted file mode 100644 index 951b1d275..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/SubjectService.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Service; - -public class SubjectService : ISubjectService -{ - readonly ICaller _caller; - - public SubjectService(ICaller caller) - { - _caller = caller; - } - - public async Task> GetListAsync(string filter) - { - var requestUri = $"api/subject/getList"; - return await _caller.GetAsync>(requestUri, new { filter }) ?? new(); - } -} - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/TeamService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/TeamService.cs deleted file mode 100644 index d76c887bf..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/TeamService.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Service; - -public class TeamService : ITeamService -{ - readonly ICaller _caller; - readonly string _party = "api/team/"; - readonly IUserContext _userContext; - - public TeamService(ICaller caller, IUserContext userContext) - { - _caller = caller; - _userContext = userContext; - } - - public async Task GetDetailAsync(Guid id) - { - var requestUri = $"{_party}detail"; - return await _caller.GetAsync(requestUri, new { id }); - } - - public async Task> GetListAsync(Guid userId = default) - { - var requestUri = $"{_party}list"; - if (Guid.Empty != userId) - { - requestUri = $"{requestUri}?userId={userId}"; - } - return await _caller.GetAsync>(requestUri) ?? new(); - } - - public async Task> GetAllAsync(string environment) - { - var requestUri = $"{_party}list?{IsolationConsts.ENVIRONMENT}={environment}"; - return await _caller.GetAsync>(requestUri) ?? new(); - } - - public async Task> GetUserTeamsAsync() - { - var userId = _userContext.GetUserId(); - var requestUri = $"{_party}list?userId={userId}"; - return await _caller.GetAsync>(requestUri) ?? new(); - } -} - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/ThirdPartyIdpService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/ThirdPartyIdpService.cs deleted file mode 100644 index 28ef0022b..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/ThirdPartyIdpService.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Service; - -public class ThirdPartyIdpService : IThirdPartyIdpService -{ - readonly ICaller _caller; - readonly IMultilevelCacheClient _memoryCacheClient; - - public ThirdPartyIdpService(ICaller caller, IMultilevelCacheClient memoryCacheClient) - { - _caller = caller; - _memoryCacheClient = memoryCacheClient; - } - - public async Task> GetAllAsync() - { - var requestUri = $"api/thirdPartyIdp/getAll"; - return await _caller.GetAsync>(requestUri) ?? new(); - } - - public async Task> GetAllFromCacheAsync() - { - var thirdPartyIdps = await _memoryCacheClient.GetAsync>(CacheKeyConsts.ALL_THIRD_PARTY_IDP); - return thirdPartyIdps ?? new(); - } - - public Task GetLdapOptionsAsync(string scheme) - { - var requestUri = $"api/thirdPartyIdp/ldapOptions"; - return _caller.GetAsync(requestUri, new { scheme }); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/UserService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/UserService.cs deleted file mode 100644 index 829b68c86..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/Service/UserService.cs +++ /dev/null @@ -1,415 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Service; - -public class UserService : IUserService -{ - readonly ICaller _caller; - readonly IUserContext _userContext; - - public UserService(ICaller caller, IUserContext userContext, IMultilevelCacheClient multilevelCacheClient) - { - _caller = caller; - _userContext = userContext; - } - - public async Task AddAsync(AddUserModel user) - { - var requestUri = $"api/user/external"; - return await _caller.PostAsync(requestUri, user) ?? throw new UserFriendlyException("operation failed"); - } - - public async Task UpsertThirdPartyUserAsync(UpsertThirdPartyUserModel user) - { - var requestUri = $"api/thirdPartyUser/upsertThirdPartyUserExternal"; - return await _caller.PostAsync(requestUri, user) ?? throw new UserFriendlyException("operation failed"); - } - - public async Task RemoveThirdPartyUserAsync(Guid id) - { - var requestUri = $"api/thirdPartyUser/remove"; - await _caller.DeleteAsync(requestUri, new { id }); - } - - public async Task RemoveThirdPartyUserByThridPartyIdentityAsync(string thridPartyIdentity) - { - var requestUri = $"api/thirdPartyUser/removeByThridPartyIdentity"; - await _caller.DeleteAsync(requestUri, new { thridPartyIdentity }); - } - - public async Task UpsertAsync(UpsertUserModel user) - { - var requestUri = $"api/user/upsertExternal"; - return await _caller.PostAsync(requestUri, user) ?? throw new UserFriendlyException("operation failed"); - } - - public async Task> GetListByDepartmentAsync(Guid departmentId) - { - var requestUri = $"api/staff/getListByDepartment"; - return await _caller.GetAsync>(requestUri, new { id = departmentId }) ?? new(); - } - - public async Task> GetListByRoleAsync(Guid roleId) - { - var requestUri = $"api/user/getListByRole"; - return await _caller.GetAsync>(requestUri, new { id = roleId }) ?? new(); - } - - public async Task> GetListByTeamAsync(Guid teamId) - { - var requestUri = $"api/staff/getListByTeam"; - return await _caller.GetAsync>(requestUri, new { id = teamId }) ?? new(); - } - - public async Task GetTotalByDepartmentAsync(Guid departmentId) - { - var requestUri = $"api/staff/getTotalByDepartment"; - return await _caller.GetAsync(requestUri, new { id = departmentId }); - } - - public async Task GetTotalByRoleAsync(Guid roleId) - { - var requestUri = $"api/staff/getTotalByRole"; - return await _caller.GetAsync(requestUri, new { id = roleId }); - } - - public async Task GetTotalByTeamAsync(Guid teamId) - { - var requestUri = $"api/staff/getTotalByTeam"; - return await _caller.GetAsync(requestUri, new { id = teamId }); - } - - public async Task ValidateAccountAsync(ValidateAccountModel validateAccountModel) - { - var requestUri = $"api/user/validateByAccount"; - return await _caller.PostAsync(requestUri, validateAccountModel); - } - - public async Task GetByAccountAsync(string account) - { - var requestUri = $"api/user/byAccount"; - return await _caller.GetAsync(requestUri, new { account }); - } - - public async Task> GetListByAccountAsync(IEnumerable accounts) - { - var requestUri = $"api/user/listByAccount"; - return await _caller.GetAsync>(requestUri, new { accounts = string.Join(',', accounts) }) ?? new(); - } - - public async Task GetByPhoneNumberAsync(string phoneNumber) - { - var requestUri = $"api/user/byPhoneNumber"; - return await _caller.GetAsync(requestUri, new { phoneNumber }); - } - - public async Task GetByEmailAsync(string email) - { - var requestUri = $"api/user/byEmail"; - return await _caller.GetAsync(requestUri, new { email }); - } - - public async Task GetByIdAsync(Guid userId) - { - var user = await GetListByIdsAsync(userId); - return user.FirstOrDefault(); - } - - public async Task> GetListByIdsAsync(params Guid[] userIds) - { - var requestUri = $"api/user/byIds"; - return await _caller.PostAsync>(requestUri, userIds) ?? new(); - } - - public async Task GetCurrentUserAsync() - { - var id = _userContext.GetUserId(); - var requestUri = $"api/user/byId/{id}"; - return await _caller.GetAsync(requestUri, new { id }); - } - - public async Task GetCurrentStaffAsync() - { - var userId = _userContext.GetUserId(); - var requestUri = $"api/staff/getDetailByUserId"; - return await _caller.GetAsync(requestUri, new { userId }); - } - - public async Task VisitedAsync(string appId, string url) - { - var userId = _userContext.GetUserId(); - var requestUri = $"api/user/visit"; - await _caller.PostAsync(requestUri, new { UserId = userId, appId = appId, Url = url }, true); - } - - public async Task> GetVisitedListAsync() - { - var userId = _userContext.GetUserId(); - var requestUri = $"api/user/visitedList"; - return (await _caller.GetAsync>(requestUri, new { userId = userId })) ?? new(); - } - - public async Task UpdatePasswordAsync(UpdateUserPasswordModel user) - { - if (user.Id == Guid.Empty) - { - user.Id = _userContext.GetUserId(); - } - var requestUri = $"api/user/password"; - await _caller.PutAsync(requestUri, user); - } - - public async Task UpdateUserAvatarAsync(UpdateUserAvatarModel user) - { - if (user.Id == Guid.Empty) - { - user.Id = _userContext.GetUserId(); - } - var requestUri = $"api/user/avatar"; - await _caller.PutAsync(requestUri, user); - } - - public async Task UpdateStaffAvatarAsync(UpdateStaffAvatarModel staff) - { - if (staff.UserId == Guid.Empty) - { - staff.UserId = _userContext.GetUserId(); - } - var requestUri = $"api/staff/updateAvatar"; - await _caller.PutAsync(requestUri, staff); - } - - public async Task UpdateBasicInfoAsync(UpdateUserBasicInfoModel user) - { - if (user.Id == Guid.Empty) - { - user.Id = _userContext.GetUserId(); - } - var requestUri = $"api/user/basicInfo"; - await _caller.PutAsync(requestUri, user); - } - - public async Task UpdateStaffBasicInfoAsync(UpdateStaffBasicInfoModel staff) - { - if (staff.UserId == Guid.Empty) - { - staff.UserId = _userContext.GetUserId(); - } - var requestUri = $"api/staff/updateBasicInfo"; - await _caller.PutAsync(requestUri, staff); - } - - public async Task UpsertSystemDataAsync(Guid userId, string systemId, T data) - { - var requestUri = "api/user/systemData"; - await _caller.PostAsync(requestUri, - new { UserId = userId, SystemId = systemId, Data = JsonSerializer.Serialize(data) }, - true); - } - - public async Task UpsertSystemDataAsync(string systemId, T data) - { - var userId = _userContext.GetUserId(); - await UpsertSystemDataAsync(userId, systemId, data); - } - - public async Task GetSystemDataAsync(string systemId) - { - var userId = _userContext.GetUserId(); - return await GetSystemDataAsync(userId, systemId); - } - - public async Task GetSystemDataAsync(Guid userId, string systemId) - { - var dataList = await GetSystemListDataAsync(new List { userId }, systemId); - return dataList.FirstOrDefault().Value ?? default; - } - - public async Task> GetSystemListDataAsync(IEnumerable userIds, string systemId) - { - var requestUri = $"api/user/systemData/byIds"; - var data = await _caller.PostAsync>(requestUri, new GetSystemDataModel { UserIds = userIds.ToList(), SystemId = systemId }) ?? new(); - return data.ToDictionary(d => d.Key, d => typeof(T) == typeof(string) ? (T)(object)d.Value : JsonSerializer.Deserialize(d.Value)); - } - - public async Task DisableAsync(DisableUserModel user) - { - var requestUri = $"api/user/disable"; - return await _caller.PutAsync(requestUri, user); - } - - public async Task UpdatePhoneNumberAsync(UpdateUserPhoneNumberModel user) - { - if (user.Id == Guid.Empty) - { - user.Id = _userContext.GetUserId(); - } - var requestUri = $"api/user/phoneNumber"; - return await _caller.PutAsync(requestUri, user); - } - - public async Task LoginByPhoneNumberAsync(LoginByPhoneNumberModel login) - { - var requestUri = $"api/user/loginByPhoneNumber"; - return await _caller.PostAsync(requestUri, login); - } - - public async Task RemoveUserRolesAsync(RemoveUserRolesModel user) - { - var requestUri = $"api/user/userRoles"; - await _caller.DeleteAsync(requestUri, user); - } - - public async Task AddThirdPartyUserAsync(AddThirdPartyUserModel user, bool whenExistReturn = true) - { - var requestUri = $"api/thirdPartyUser/addThirdPartyUser?whenExistReturn={whenExistReturn}"; - return await _caller.PostAsync(requestUri, user) ?? throw new UserFriendlyException("operation failed"); - } - - public async Task GetThirdPartyUserAsync(GetThirdPartyUserModel model) - { - var requestUri = $"api/thirdPartyUser"; - return await _caller.GetAsync(requestUri, model); - } - - public async Task GetThirdPartyUserByUserIdAsync(GetThirdPartyUserByUserIdModel model) - { - var requestUri = $"api/thirdPartyUser/GetByUserId"; - return await _caller.GetAsync(requestUri, model); - } - - public async Task SetCurrentTeamAsync(Guid teamId) - { - var userId = _userContext.GetUserId(); - var requestUri = $"api/staff/UpdateCurrentTeam"; - await _caller.PutAsync(requestUri, new UpdateCurrentTeamModel - { - UserId = userId, - TeamId = teamId - }); - } - - public async Task SendMsgCodeAsync(SendMsgCodeModel model) - { - if (model.UserId == Guid.Empty) - { - model.UserId = _userContext.GetUserId(); - } - var requestUri = $"api/message/sms"; - await _caller.PostAsync(requestUri, model); - } - - public async Task VerifyMsgCodeAsync(VerifyMsgCodeModel model) - { - if (model.UserId == Guid.Empty) - { - model.UserId = _userContext.GetUserId(); - } - var requestUri = $"api/user/verifyMsgCode"; - return await _caller.PostAsync(requestUri, model); - } - - public async Task SendEmailAsync(SendEmailModel model) - { - var requestUri = $"api/message/email"; - await _caller.PostAsync(requestUri, model); - } - - public async Task RegisterByPhoneAsync(RegisterByPhoneModel model) - { - var requestUri = $"api/user/register"; - return await _caller.PostAsync(requestUri, model); - } - - public async Task RegisterByEmailAsync(RegisterByEmailModel model) - { - var requestUri = $"api/user/register"; - return await _caller.PostAsync(requestUri, model); - } - - public async Task HasPasswordAsync(Guid userId = default) - { - if (userId == Guid.Empty) - { - userId = _userContext.GetUserId(); - } - var requestUri = $"api/user/hasPassword"; - return await _caller.GetAsync(requestUri, new { userId }); - } - - public async Task RegisterThirdPartyUserAsync(RegisterThirdPartyUserModel model) - { - var requestUri = $"api/thirdPartyUser/register"; - return await _caller.PostAsync(requestUri, model) ?? throw new UserFriendlyException("Register failed"); - } - - public async Task HasPhoneNumberInEnvAsync(string env, string phoneNumber) - { - ArgumentNullException.ThrowIfNull(env); - ArgumentNullException.ThrowIfNull(phoneNumber); - var requestUri = $"api/user/HasPhoneNumberInEnv?env={env}&phoneNumber={phoneNumber}"; - return await _caller.GetAsync(requestUri); - } - - public async Task ResetPasswordByEmailAsync(ResetPasswordByEmailModel resetPasswordByEmailModel) - { - var requestUri = $"api/user/reset_password_by_email"; - return await _caller.PostAsync(requestUri, resetPasswordByEmailModel); - } - - public async Task ResetPasswordByPhoneAsync(ResetPasswordByPhoneModel resetPasswordByPhoneModel) - { - var requestUri = $"api/user/reset_password_by_phone"; - return await _caller.PostAsync(requestUri, resetPasswordByPhoneModel); - } - - public async Task RemoveAsync(Guid id) - { - var requestUri = "api/user"; - await _caller.DeleteAsync(requestUri, new RemoveUserModel(id)); - } - - public async Task> SearchAsync(string search) - { - var requestUri = $"api/user/select?search={search}"; - return await _caller.GetAsync>(requestUri) ?? new(); - } - - public Task BindRolesAsync(BindUserRolesModel model) - { - var requestUri = $"api/user/bind_roles"; - return _caller.PostAsync(requestUri, model); - } - - public Task UnbindRolesAsync(UnbindUserRolesModel model) - { - var requestUri = $"api/user/unbind_roles"; - return _caller.PostAsync(requestUri, model); - } - - public async Task> GetClaimValuesAsync(Guid userId) - { - var requestUri = $"api/user/claim-values/{userId}"; - return await _caller.GetAsync>(requestUri) ?? new(); - } - - public Task AddClaimValuesAsync(UserClaimValuesModel userClaimValuesModel) - { - var requestUri = $"api/user/claim-values"; - return _caller.PostAsync(requestUri, userClaimValuesModel); - } - - public async Task GetImpersonateAsync(GetImpersonateInputModel model) - { - var requestUri = $"api/user/impersonate"; - return await _caller.GetAsync(requestUri, model) ?? new(); - } - - public async Task ImpersonateAsync(ImpersonateInputModel model) - { - var requestUri = $"api/user/impersonate"; - return await _caller.PostAsync(requestUri, model) ?? new(); - } -} - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/ServiceCollectionExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/ServiceCollectionExtensions.cs deleted file mode 100644 index a8f555ecd..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -// ReSharper disable once CheckNamespace - -namespace Microsoft.Extensions.DependencyInjection; - -public static class ServiceCollectionExtensions -{ - public static IServiceCollection AddAuthClient(this IServiceCollection services, IConfiguration configuration, - string? authServiceBaseAddress = null) - { - var redisOptions = configuration.GetSection("$public.RedisConfig").Get(); - authServiceBaseAddress ??= configuration.GetValue("$public.AppSettings:AuthClient:Url"); - services.AddAuthClient(authServiceBaseAddress, redisOptions); - - return services; - } - - public static IServiceCollection AddAuthClient(this IServiceCollection services, string authServiceBaseAddress, - RedisConfigurationOptions redisOptions) - { - MasaArgumentException.ThrowIfNullOrEmpty(authServiceBaseAddress); - - return services.AddAuthClient(callerBuilder => - { - callerBuilder - .UseHttpClient(builder => builder.BaseAddress = authServiceBaseAddress) - .AddMiddleware() - .UseAuthentication(); - }, redisOptions); - } - - private static IServiceCollection AddAuthClient(this IServiceCollection services, Action callerBuilder, - RedisConfigurationOptions redisOptions) - { - MasaArgumentException.ThrowIfNull(callerBuilder); - if (services.All(service => service.ServiceType != typeof(IMultiEnvironmentUserContext))) - throw new Exception("Please add IMultiEnvironmentUserContext first."); - - services.AddCaller(DEFAULT_CLIENT_NAME, callerBuilder); - - services.AddAuthClientMultilevelCache(redisOptions); - services.AddScoped(serviceProvider => - { - var userContext = serviceProvider.GetRequiredService(); - var caller = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); - var authClientMultilevelCacheProvider = serviceProvider.GetRequiredService(); - var authClient = new AuthClient(caller, userContext, authClientMultilevelCacheProvider.GetMultilevelCacheClient()); - return authClient; - }); - services.AddScoped(serviceProvider => - { - var callProvider = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); - var authClientMultilevelCacheProvider = serviceProvider.GetRequiredService(); - var thirdPartyIdpService = new ThirdPartyIdpService(callProvider, authClientMultilevelCacheProvider.GetMultilevelCacheClient()); - return thirdPartyIdpService; - }); - - MasaApp.TrySetServiceCollection(services); - - return services; - } - - public static IServiceCollection AddSsoClient(this IServiceCollection services, string ssoServiceAddress) - { - services.AddHttpClient(DEFAULT_SSO_CLIENT_NAME, httpClient => - { - httpClient.BaseAddress = new Uri(ssoServiceAddress); - }); - services.AddSingleton(); - - return services; - } - - public static IServiceCollection AddAuthClientMultilevelCache(this IServiceCollection services, RedisConfigurationOptions redisOptions) - { - services.AddMultilevelCache( - DEFAULT_CLIENT_NAME, - distributedCacheOptions => distributedCacheOptions.UseStackExchangeRedisCache(redisOptions), - multilevelCacheOptions => - { - multilevelCacheOptions.SubscribeKeyType = SubscribeKeyType.SpecificPrefix; - multilevelCacheOptions.SubscribeKeyPrefix = $"{DEFAULT_SUBSCRIBE_KEY_PREFIX}-db-{redisOptions.DefaultDatabase}"; - } - ); - services.AddSingleton(); - - return services; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/SsoClient.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/SsoClient.cs deleted file mode 100644 index d3001e4a3..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/SsoClient.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth; - -public class SsoClient : ISsoClient -{ - public SsoClient(IHttpClientFactory httpClientFactory) - { - LoginService = new LoginService(httpClientFactory); - } - - public ILoginService LoginService { get; set; } -} - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/_Imports.cs deleted file mode 100644 index 37bea4e45..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/_Imports.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using IdentityModel.Client; -global using Masa.BuildingBlocks.Authentication.Identity; -global using Masa.BuildingBlocks.Authentication.OpenIdConnect.Models.Constans; -global using Masa.BuildingBlocks.Caching; -global using Masa.BuildingBlocks.Data; -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Auth; -global using Masa.BuildingBlocks.StackSdks.Auth.Contracts.Consts; -global using Masa.BuildingBlocks.StackSdks.Auth.Contracts.Enum; -global using Masa.BuildingBlocks.StackSdks.Auth.Contracts.Model; -global using Masa.BuildingBlocks.StackSdks.Auth.Service; -global using Masa.BuildingBlocks.StackSdks.Isolation; -global using Masa.Contrib.Caching.Distributed.StackExchangeRedis; -global using Masa.Contrib.StackSdks.Auth; -global using Masa.Contrib.StackSdks.Auth.Model; -global using Masa.Contrib.StackSdks.Auth.Service; -global using Masa.Contrib.StackSdks.Isolation; -global using Microsoft.Extensions.Configuration; -global using Microsoft.Extensions.Logging; -global using System.Text.Json; -global using static Masa.Contrib.StackSdks.Auth.Constants; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/AuthenticationService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/AuthenticationService.cs deleted file mode 100644 index 343e6cc33..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/AuthenticationService.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Caller; - -public class AuthenticationService : IAuthenticationService -{ - private readonly TokenProvider _tokenProvider; - private readonly JwtTokenValidator? _jwtTokenValidator; - private readonly IMultiEnvironmentContext _multiEnvironmentContext; - - public AuthenticationService(TokenProvider tokenProvider, - JwtTokenValidator? jwtTokenValidator, - IMultiEnvironmentContext multiEnvironmentContext) - { - _tokenProvider = tokenProvider; - _jwtTokenValidator = jwtTokenValidator; - _multiEnvironmentContext = multiEnvironmentContext; - } - - public async Task ExecuteAsync(HttpRequestMessage requestMessage) - { - if (_jwtTokenValidator != null) - { - await _jwtTokenValidator.ValidateTokenAsync(_tokenProvider); - } - - if (!_tokenProvider.AccessToken.IsNullOrWhiteSpace()) - requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _tokenProvider.AccessToken); - - if (!string.IsNullOrEmpty(_multiEnvironmentContext.CurrentEnvironment) && !requestMessage.Headers.Any(x=>x.Key == IsolationConsts.ENVIRONMENT)) - requestMessage.Headers.Add(IsolationConsts.ENVIRONMENT, _multiEnvironmentContext.CurrentEnvironment); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Constant.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Constant.cs deleted file mode 100644 index 18f4e4e1e..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Constant.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Caller; - -internal static class Constant -{ - public const string HTTP_NAME = "IdentityClient"; -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Generater/DefaultTokenGenerater.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Generater/DefaultTokenGenerater.cs deleted file mode 100644 index b907deddb..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Generater/DefaultTokenGenerater.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Caller; - -internal class DefaultTokenGenerater : ITokenGenerater -{ - private readonly IHttpContextAccessor _httpContextAccessor; - private const string SCHEME = "Bearer "; - - public DefaultTokenGenerater(IHttpContextAccessor httpContextAccessor) - { - _httpContextAccessor = httpContextAccessor; - } - - public TokenProvider Generater() - { - StringValues authenticationHeaderValue; - - if (_httpContextAccessor.HttpContext?.Request.Headers.TryGetValue("Authorization", out authenticationHeaderValue) == true) - { - var accessToken = authenticationHeaderValue.ToString(); - - if (!string.IsNullOrEmpty(accessToken) && accessToken.ToString().IndexOf(SCHEME) > -1) - { - accessToken = accessToken.Replace(SCHEME, ""); - } - - return new TokenProvider { AccessToken = accessToken }; - } - - return new TokenProvider(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Generater/ITokenGenerater.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Generater/ITokenGenerater.cs deleted file mode 100644 index 391abceb5..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Generater/ITokenGenerater.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Caller; - -public interface ITokenGenerater -{ - TokenProvider Generater(); -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Jwt/ClientRefreshTokenOptions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Jwt/ClientRefreshTokenOptions.cs deleted file mode 100644 index 62ac86517..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Jwt/ClientRefreshTokenOptions.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Caller; - -public class ClientRefreshTokenOptions -{ - public string ClientId { get; set; } = string.Empty; - - public string ClientSecret { get; set; } = string.Empty; -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Jwt/JwtTokenValidator.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Jwt/JwtTokenValidator.cs deleted file mode 100644 index 199429958..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Jwt/JwtTokenValidator.cs +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Caller; - -public class JwtTokenValidator -{ - readonly JwtTokenValidatorOptions _jwtTokenValidatorOptions; - readonly ClientRefreshTokenOptions _clientRefreshTokenOptions; - readonly HttpClient _httpClient; - readonly ILogger? _logger; - - public JwtTokenValidator( - IOptions jwtTokenValidatorOptions, - HttpClient httpClient, - IHttpClientFactory httpClientFactory, - IOptions clientRefreshTokenOptions, - ILogger? logger) - { - _jwtTokenValidatorOptions = jwtTokenValidatorOptions.Value; - _httpClient = httpClientFactory.CreateClient(Constant.HTTP_NAME); - _clientRefreshTokenOptions = clientRefreshTokenOptions.Value; - _logger = logger; - } - - public async Task ValidateTokenAsync(TokenProvider tokenProvider) - { - var discoveryDocument = await GetDiscoveryDocument(); - var validationParameters = new TokenValidationParameters - { - ValidateLifetime = _jwtTokenValidatorOptions.ValidateLifetime, - ValidateAudience = _jwtTokenValidatorOptions.ValidateAudience, - ValidateIssuer = _jwtTokenValidatorOptions.ValidateIssuer, - ValidIssuer = discoveryDocument.Issuer, - ValidAudiences = _jwtTokenValidatorOptions.ValidAudiences, - ValidateIssuerSigningKey = true, - IssuerSigningKeys = GetIssuerSigningKeys(discoveryDocument) - }; - JwtSecurityTokenHandler handler = new(); - handler.InboundClaimTypeMap.Clear(); - ClaimsPrincipal? claimsPrincipal = null; - try - { - claimsPrincipal = handler.ValidateToken(tokenProvider.AccessToken, validationParameters, out SecurityToken _); - } - catch (SecurityTokenExpiredException) - { - var tokenResult = await RefreshTokenAsync(tokenProvider.RefreshToken); - if (tokenResult != null) - { - if (tokenResult.IsError) - { - _logger?.LogError("JwtTokenValidator failed, RefreshToken failed, Error Message: {Message}", tokenResult.Error); - } - else - { - tokenProvider.AccessToken = tokenResult.AccessToken; - return handler.ValidateToken(tokenProvider.AccessToken, validationParameters, out SecurityToken _); - } - } - } - catch (Exception e) - { - _logger?.LogError(e, "JwtTokenValidator failed"); - throw new UserFriendlyException("JwtTokenValidator failed"); - } - return claimsPrincipal; - } - - public async Task RefreshTokenAsync(string? refreshToken) - { - if (string.IsNullOrEmpty(refreshToken)) - { - _logger?.LogWarning("RefreshToken is null,please AllowOfflineAccess value(true) and RequestedScopes should contains offline_access"); - throw new ArgumentNullException(nameof(refreshToken)); - } - if (string.IsNullOrEmpty(_clientRefreshTokenOptions.ClientId)) - { - _logger?.LogWarning("ClientRefreshTokenOptions.ClientId is empty,refresh token no work"); - return null; - } - var tokenEndpoint = (await GetDiscoveryDocument()).TokenEndpoint; - var tokenClient = new TokenClient(_httpClient, new TokenClientOptions - { - Address = tokenEndpoint, - ClientId = _clientRefreshTokenOptions.ClientId, - ClientSecret = _clientRefreshTokenOptions.ClientSecret - }); - var tokenResult = await tokenClient.RequestRefreshTokenAsync(refreshToken).ConfigureAwait(false); - return tokenResult; - } - - private async Task GetDiscoveryDocument() - { - return await _httpClient.GetDiscoveryDocumentAsync(_jwtTokenValidatorOptions.AuthorityEndpoint); - } - - private static List GetIssuerSigningKeys(DiscoveryDocumentResponse discoveryDocument) - { - var keys = new List(); - foreach (var webKey in discoveryDocument.KeySet.Keys) - { - var e = Base64Url.Decode(webKey.E); - var n = Base64Url.Decode(webKey.N); - var key = new RsaSecurityKey(new RSAParameters { Exponent = e, Modulus = n }) - { - KeyId = webKey.Kid - }; - keys.Add(key); - } - return keys; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Jwt/JwtTokenValidatorOptions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Jwt/JwtTokenValidatorOptions.cs deleted file mode 100644 index b5f64a4a8..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Jwt/JwtTokenValidatorOptions.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Caller; - -public class JwtTokenValidatorOptions -{ - public string AuthorityEndpoint { get; set; } = string.Empty; - - public bool ValidateLifetime { get; set; } = true; - - public bool ValidateAudience { get; set; } - - public bool ValidateIssuer { get; set; } = true; - - public IEnumerable ValidAudiences { get; set; } = Enumerable.Empty(); -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Masa.Contrib.StackSdks.Caller.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Masa.Contrib.StackSdks.Caller.csproj deleted file mode 100644 index 07e52cb27..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/Masa.Contrib.StackSdks.Caller.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - enable - enable - - - - - - - - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/MasaCallerClientBuilderExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/MasaCallerClientBuilderExtensions.cs deleted file mode 100644 index 818a5c4e1..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/MasaCallerClientBuilderExtensions.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -using Masa.BuildingBlocks.Isolation; -using Masa.Contrib.Isolation.MultiEnvironment; - -namespace Microsoft.Extensions.DependencyInjection; - -public static class MasaCallerClientBuilderExtensions -{ - /// - /// Caller adds default authentication - /// - /// - /// The default scheme used as a fallback for all other schemes. - /// - public static IMasaCallerClientBuilder UseAuthentication( - this IMasaCallerClientBuilder masaCallerClientBuilder) - { - masaCallerClientBuilder.Services.AddHttpContextAccessor(); - masaCallerClientBuilder.Services.TryAddScoped(); - masaCallerClientBuilder.Services.TryAddScoped(s => s.GetRequiredService().Generater()); - masaCallerClientBuilder.Services.TryAddScoped(); - masaCallerClientBuilder.Services.TryAddScoped(typeof(IMultiEnvironmentContext), s => s.GetRequiredService()); - masaCallerClientBuilder.UseAuthentication(serviceProvider => - new AuthenticationService( - serviceProvider.GetRequiredService(), - null, - serviceProvider.GetRequiredService() - )); - return masaCallerClientBuilder; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/ServiceCollectionExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/ServiceCollectionExtensions.cs deleted file mode 100644 index 7c6e6c89d..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Caller; - -public static class ServiceCollectionExtensions -{ - public static IServiceCollection AddStackCaller( - this IServiceCollection services, - Assembly assembly, - Action jwtTokenValidatorOptions, - Action? clientRefreshTokenOptions = null) - { - MasaArgumentException.ThrowIfNull(jwtTokenValidatorOptions); - - services.AddHttpClient(Constant.HTTP_NAME).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler - { - ServerCertificateCustomValidationCallback = delegate { return true; } - }); - - services.Configure(jwtTokenValidatorOptions); - services.Configure(clientRefreshTokenOptions); - services.TryAddScoped(); - services.TryAddScoped(s => s.GetRequiredService().Generater()); - services.AddSingleton(); - services.AddAutoRegistrationCaller(assembly); - - return services; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/StackHttpClientCaller.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/StackHttpClientCaller.cs deleted file mode 100644 index 08e539c26..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/StackHttpClientCaller.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Caller; - -public abstract class StackHttpClientCaller : HttpClientCallerBase -{ - protected override void UseHttpClientPost(MasaHttpClientBuilder masaHttpClientBuilder) - { - masaHttpClientBuilder.UseAuthentication(serviceProvider => new AuthenticationService( - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService(), - serviceProvider.GetRequiredService() - )); - base.UseHttpClientPost(masaHttpClientBuilder); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/TokenProvider.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/TokenProvider.cs deleted file mode 100644 index 2ff814c05..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/TokenProvider.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Caller; - -public class TokenProvider -{ - public string? AccessToken { get; set; } - - public string? RefreshToken { get; set; } - - public string? IdToken { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/_Imports.cs deleted file mode 100644 index 4a8844cdb..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Caller/_Imports.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using IdentityModel; -global using IdentityModel.Client; -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Isolation; -global using Masa.BuildingBlocks.Isolation; -global using Masa.Contrib.Service.Caller.HttpClient; -global using Masa.Contrib.StackSdks.Caller; -global using Microsoft.AspNetCore.Http; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.Extensions.DependencyInjection.Extensions; -global using Microsoft.Extensions.Logging; -global using Microsoft.Extensions.Options; -global using Microsoft.Extensions.Primitives; -global using Microsoft.IdentityModel.Tokens; -global using System.IdentityModel.Tokens.Jwt; -global using System.Net.Http.Headers; -global using System.Reflection; -global using System.Security.Claims; -global using System.Security.Cryptography; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/Constants.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/Constants.cs deleted file mode 100644 index 78ba35156..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/Constants.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Config; - -internal static class Constants -{ - internal const string DEFAULT_PUBLIC_ID = "public-$Config"; - - internal const string DEFAULT_CONFIG_NAME = "$public.DefaultConfig"; -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/HttpProtocol.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/HttpProtocol.cs deleted file mode 100644 index 3c019ace5..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/HttpProtocol.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Config; - -internal static class HttpProtocol -{ - public const string HTTP = "http"; - - public const string HTTPS = "https"; -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/Masa.Contrib.StackSdks.Config.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/Masa.Contrib.StackSdks.Config.csproj deleted file mode 100644 index d1363d980..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/Masa.Contrib.StackSdks.Config.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - enable - enable - - - - - - - - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackApp.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackApp.cs deleted file mode 100644 index 647f39416..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackApp.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Config; - -public class MasaStackApp : Enumeration -{ - public static readonly MasaStackApp WEB = new(1, nameof(WEB).ToLowerInvariant()); - public static readonly MasaStackApp SSO = new(2, nameof(SSO).ToLowerInvariant()); - public static readonly MasaStackApp Service = new(3, nameof(Service).ToLowerInvariant()); - public static readonly MasaStackApp Worker = new(4, nameof(Worker).ToLowerInvariant()); - - public MasaStackApp(int id, string name) - : base(id, name) - { - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfig.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfig.cs deleted file mode 100644 index 60794ad93..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfig.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Config; - -public class MasaStackConfig : IMasaStackConfig -{ - private readonly IConfigurationApiClient _configurationApiClient; - - private static ConcurrentDictionary ConfigMap { get; set; } = new(StringComparer.OrdinalIgnoreCase); - - public MasaStackConfig() { } - - public MasaStackConfig(IConfigurationApiClient client, Dictionary configs) - { - _configurationApiClient = client; - ConfigMap = new(configs); - } - - public RedisModel RedisModel - { - get - { - var redisStr = GetValue(MasaStackConfigConstant.REDIS); - return JsonSerializer.Deserialize(redisStr) ?? throw new JsonException(); - } - } - - public ElasticModel ElasticModel - { - get - { - var redisStr = GetValue(MasaStackConfigConstant.ELASTIC); - return JsonSerializer.Deserialize(redisStr) ?? throw new JsonException(); - } - } - - public bool IsDemo => bool.Parse(GetValue(MasaStackConfigConstant.IS_DEMO)); - - public string Version => GetValue(MasaStackConfigConstant.VERSION); - - public string Cluster => GetValue(MasaStackConfigConstant.CLUSTER); - - public string OtlpUrl => GetValue(MasaStackConfigConstant.OTLP_URL); - - public string DomainName => GetValue(MasaStackConfigConstant.DOMAIN_NAME); - - public string Environment => GetValue(MasaStackConfigConstant.ENVIRONMENT); - - public string Namespace => GetValue(MasaStackConfigConstant.NAMESPACE); - - public string AdminPwd => GetValue(MasaStackConfigConstant.ADMIN_PWD); - - public string DccSecret => GetValue(MasaStackConfigConstant.DCC_SECRET); - - public string SuffixIdentity => GetValue(MasaStackConfigConstant.SUFFIX_IDENTITY); - - public List GetProjectList() => this.GetMasaStack().Select(jNode => jNode!["id"]!.ToString()).ToList(); - - public string GetValue(string key) - { - GetValues().TryGetValue(key, out var value); - return value ?? ConfigMap[key]; - } - - public virtual Dictionary GetValues() - { - try - { - var remoteConfigs = _configurationApiClient.GetAsync>( - ConfigMap[MasaStackConfigConstant.ENVIRONMENT], - ConfigMap[MasaStackConfigConstant.CLUSTER], - DEFAULT_PUBLIC_ID, - DEFAULT_CONFIG_NAME).ConfigureAwait(false).GetAwaiter().GetResult(); - return remoteConfigs; - } - catch (ArgumentException) - { - return new(ConfigMap); - } - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfigExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfigExtensions.cs deleted file mode 100644 index 00e01e3b2..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfigExtensions.cs +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Config; - -public static class MasaStackConfigExtensions -{ - public static JsonArray GetMasaStack(this IMasaStackConfig masaStackConfig) - { - var value = masaStackConfig.GetValue(MasaStackConfigConstant.MASA_STACK); - if (string.IsNullOrEmpty(value)) - { - return new(); - } - return JsonSerializer.Deserialize(value) ?? new(); - } - - public static List GetAllService(this IMasaStackConfig masaStackConfig) - { - var webs = GetMasaStack(masaStackConfig).Select(jsonObject => jsonObject?[MasaStackApp.Service.Name]!).ToList(); - webs.RemoveAll(i => i == null); - return webs ?? new(); - } - - public static List GetAllWeb(this IMasaStackConfig masaStackConfig) - { - var webs = GetMasaStack(masaStackConfig).Select(jsonObject => jsonObject?[MasaStackApp.WEB.Name]!).ToList(); - webs.RemoveAll(i => i == null); - return webs ?? new(); - } - - public static bool HasAlert(this IMasaStackConfig masaStackConfig) - { - return GetMasaStack(masaStackConfig).Any(jsonObject => jsonObject?["id"]?.ToString() == MasaStackProject.Alert.Name); - } - - public static bool HasTsc(this IMasaStackConfig masaStackConfig) - { - return GetMasaStack(masaStackConfig).Any(jsonObject => jsonObject?["id"]?.ToString() == MasaStackProject.TSC.Name); - } - - public static bool HasScheduler(this IMasaStackConfig masaStackConfig) - { - return GetMasaStack(masaStackConfig).Any(jsonObject => jsonObject?["id"]?.ToString() == MasaStackProject.Scheduler.Name); - } - - public static string GetConnectionString(this IMasaStackConfig masaStackConfig, string projectName) - { - var connStr = masaStackConfig.GetValue(MasaStackConfigConstant.CONNECTIONSTRING); - var dbModel = JsonSerializer.Deserialize(connStr); - var databaseName = $"{projectName}{(string.IsNullOrWhiteSpace(masaStackConfig.SuffixIdentity) ? "" : "_" + masaStackConfig.SuffixIdentity)}"; - - return dbModel?.ToString(databaseName) ?? ""; - } - - public static string GetDomain(this IMasaStackConfig masaStackConfig, MasaStackProject project, MasaStackApp app) - { - return GetMasaStack(masaStackConfig).FirstOrDefault(i => i?["id"]?.ToString() == project.Name)?[app.Name]?["domain"]?.ToString() ?? ""; - } - - - public static string GetAuthServiceDomain(this IMasaStackConfig masaStackConfig) - { - return GetDomain(masaStackConfig, MasaStackProject.Auth, MasaStackApp.Service); - } - - public static string GetPmServiceDomain(this IMasaStackConfig masaStackConfig) - { - return GetDomain(masaStackConfig, MasaStackProject.PM, MasaStackApp.Service); - } - - public static string GetDccServiceDomain(this IMasaStackConfig masaStackConfig) - { - return GetDomain(masaStackConfig, MasaStackProject.DCC, MasaStackApp.Service); - } - - public static string GetTscServiceDomain(this IMasaStackConfig masaStackConfig) - { - return GetDomain(masaStackConfig, MasaStackProject.TSC, MasaStackApp.Service); - } - - public static string GetAlertServiceDomain(this IMasaStackConfig masaStackConfig) - { - return GetDomain(masaStackConfig, MasaStackProject.Alert, MasaStackApp.Service); - } - - public static string GetMcServiceDomain(this IMasaStackConfig masaStackConfig) - { - return GetDomain(masaStackConfig, MasaStackProject.MC, MasaStackApp.Service); - } - - public static string GetSchedulerServiceDomain(this IMasaStackConfig masaStackConfig) - { - return GetDomain(masaStackConfig, MasaStackProject.Scheduler, MasaStackApp.Service); - } - - public static string GetSchedulerWorkerDomain(this IMasaStackConfig masaStackConfig) - { - return GetDomain(masaStackConfig, MasaStackProject.Scheduler, MasaStackApp.Worker); - } - - public static string GetSsoDomain(this IMasaStackConfig masaStackConfig) - { - return GetDomain(masaStackConfig, MasaStackProject.Auth, MasaStackApp.SSO); - } - - public static IEnumerable> GetUIDomainPairs(this IMasaStackConfig masaStackConfig) - { - foreach (var web in GetAllWeb(masaStackConfig)) - { - var id = web["id"]?.ToString() ?? ""; - var domain = web["domain"]?.ToString() ?? ""; - if (string.IsNullOrEmpty(id)) - { - continue; - } - yield return new KeyValuePair(id, domain); - } - } - - public static string GetId(this IMasaStackConfig masaStackConfig, MasaStackProject project, MasaStackApp app) - { - return masaStackConfig.GetMasaStack().FirstOrDefault(i => i?["id"]?.ToString() == project.Name) - ?[app.Name]?["id"]?.ToString() ?? ""; - } - - public static string GetServiceId(this IMasaStackConfig masaStackConfig, MasaStackProject project) - { - return masaStackConfig.GetId(project, MasaStackApp.Service); - } - - public static string GetWebId(this IMasaStackConfig masaStackConfig, MasaStackProject project) - { - return masaStackConfig.GetId(project, MasaStackApp.WEB); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfigOptions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfigOptions.cs deleted file mode 100644 index 847159ad1..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfigOptions.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Config; - -public static class MasaStackConfigOptions -{ - private static ConcurrentDictionary ConfigMap { get; set; } = new(StringComparer.OrdinalIgnoreCase); - - public static string GetValue(string key) => GetValue(key, () => string.Empty); - - public static string GetValue(string key, Func defaultFunc) - { - if (ConfigMap.ContainsKey(key)) return ConfigMap[key]; - return defaultFunc.Invoke(); - } - - public static Dictionary GetValues() => new(ConfigMap); - - public static void SetValue(string key, string value) => ConfigMap[key] = value; - - public static void SetValues(Dictionary configMap) - { - foreach (var config in configMap) - { - SetValue(config.Key, config.Value); - } - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfigUtils.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfigUtils.cs deleted file mode 100644 index 535eb37eb..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackConfigUtils.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -[assembly: InternalsVisibleTo("Masa.Contrib.StackSdks.Config.Tests")] -namespace Masa.Contrib.StackSdks.Config; - -internal static class MasaStackConfigUtils -{ - public static DccOptions GetDefaultDccOptions(Dictionary configMap, MasaStackProject project, MasaStackApp app) - { - var data = GetMasaStackJsonArray(configMap); - var dccServerAddress = data.FirstOrDefault(i => i?["id"]?.ToString() == MasaStackProject.DCC.Name)?[MasaStackApp.Service.Name]?["domain"]?.ToString() ?? ""; - var redisStr = configMap.GetValueOrDefault(MasaStackConfigConstant.REDIS) ?? throw new Exception("redis options can not null"); - var redis = JsonSerializer.Deserialize(redisStr) ?? throw new JsonException(); - var secret = configMap.GetValueOrDefault(MasaStackConfigConstant.DCC_SECRET); - - var options = new DccOptions - { - Environment = configMap.GetValueOrDefault(MasaStackConfigConstant.ENVIRONMENT)!, - ManageServiceAddress = dccServerAddress, - RedisOptions = new Caching.Distributed.StackExchangeRedis.RedisConfigurationOptions - { - Servers = new List - { - new Caching.Distributed.StackExchangeRedis.RedisServerOptions(redis.RedisHost,redis.RedisPort) - }, - DefaultDatabase = redis.RedisDb, - Password = redis.RedisPassword - }, - PublicSecret = secret, - ConfigObjectSecret = secret, - AppId = GetAppId(configMap, project, app) - }; - - return options; - } - - static string GetAppId(Dictionary configMap, MasaStackProject project, MasaStackApp app) - { - var data = GetMasaStackJsonArray(configMap); - return data.FirstOrDefault(i => i?["id"]?.ToString() == project.Name)?[app.Name]?["id"]?.ToString() ?? ""; - } - - static JsonArray GetMasaStackJsonArray(Dictionary configMap) - { - var value = configMap.GetValueOrDefault(MasaStackConfigConstant.MASA_STACK) ?? ""; - return JsonSerializer.Deserialize(value) ?? new(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackProject.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackProject.cs deleted file mode 100644 index f57adb04f..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MasaStackProject.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Config; - -public class MasaStackProject : Enumeration -{ - public static readonly MasaStackProject Auth = new(1, nameof(Auth).ToLowerInvariant()); - public static readonly MasaStackProject PM = new(2, nameof(PM).ToLowerInvariant()); - public static readonly MasaStackProject DCC = new(3, nameof(DCC).ToLowerInvariant()); - public static readonly MasaStackProject MC = new(4, nameof(MC).ToLowerInvariant()); - public static readonly MasaStackProject Alert = new(5, nameof(Alert).ToLowerInvariant()); - public static readonly MasaStackProject Scheduler = new(6, nameof(Scheduler).ToLowerInvariant()); - public static readonly MasaStackProject TSC = new(7, nameof(TSC).ToLowerInvariant()); - - public MasaStackProject(int id, string name) - : base(id, name) - { - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MultiEnvironmentMasaStackConfig.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MultiEnvironmentMasaStackConfig.cs deleted file mode 100644 index ec7cd26a2..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/MultiEnvironmentMasaStackConfig.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Config -{ - public class MultiEnvironmentMasaStackConfig : MasaStackConfig, IMultiEnvironmentMasaStackConfig - { - private readonly IConfigurationApiClient _configurationApiClient; - - private static ConcurrentDictionary ConfigMap { get; set; } = new(StringComparer.OrdinalIgnoreCase); - - public MultiEnvironmentMasaStackConfig(IConfigurationApiClient client, Dictionary configs) - { - _configurationApiClient = client; - ConfigMap = new(configs); - } - - public override Dictionary GetValues() - { - try - { - var remoteConfigs = _configurationApiClient.GetAsync>( - ConfigMap[MasaStackConfigConstant.ENVIRONMENT], - ConfigMap[MasaStackConfigConstant.CLUSTER], - DEFAULT_PUBLIC_ID, - DEFAULT_CONFIG_NAME).ConfigureAwait(false).GetAwaiter().GetResult(); - return remoteConfigs; - } - catch (ArgumentException) - { - return new(ConfigMap); - } - } - - public IMasaStackConfig SetEnvironment(string environment) - { - var configs = new Dictionary(ConfigMap) - { - [MasaStackConfigConstant.ENVIRONMENT] = environment - }; - - var stackConfig = new MultiEnvironmentMasaStackConfig(_configurationApiClient, configs); - return stackConfig; - } - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/ServiceCollectionExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/ServiceCollectionExtensions.cs deleted file mode 100644 index 73d1c6415..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,119 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Microsoft.Extensions.DependencyInjection; - -public static class ServiceCollectionExtensions -{ - private static async Task InitializeMasaStackConfiguration( - IServiceCollection services, - Dictionary configs) - { - var serviceProvider = services.BuildServiceProvider(); - var configurationApiManage = serviceProvider.GetRequiredService(); - var configurationApiClient = serviceProvider.GetRequiredService(); - - try - { - var remoteConfigs = await configurationApiClient.GetAsync>( - configs[MasaStackConfigConstant.ENVIRONMENT], - configs[MasaStackConfigConstant.CLUSTER], - DEFAULT_PUBLIC_ID, - DEFAULT_CONFIG_NAME); - - if (remoteConfigs != null) - { - await configurationApiManage.UpdateAsync( - configs[MasaStackConfigConstant.ENVIRONMENT], - configs[MasaStackConfigConstant.CLUSTER], - DEFAULT_PUBLIC_ID, - DEFAULT_CONFIG_NAME, - configs); - } - } - catch (ArgumentException) - { - // remoteConfigs is null - await configurationApiManage.AddAsync( - configs[MasaStackConfigConstant.ENVIRONMENT], - configs[MasaStackConfigConstant.CLUSTER], - DEFAULT_PUBLIC_ID, - new Dictionary - { - { DEFAULT_CONFIG_NAME, configs } - }); - } - } - - public static async Task AddMasaStackConfigAsync(this IServiceCollection services, MasaStackProject project, MasaStackApp app, bool init = false, DccOptions? dccOptions = null) - { - var configs = GetConfigMap(services); - - dccOptions ??= MasaStackConfigUtils.GetDefaultDccOptions(configs, project, app); - services.AddSingleton(dccOptions); - services.AddMasaConfiguration(builder => builder.UseDcc(dccOptions)); - - if (init) - { - await InitializeMasaStackConfiguration(services, configs).ConfigureAwait(false); - } - - services.TryAddScoped(serviceProvider => - { - var configurationApiClient = serviceProvider.GetRequiredService(); - return new MasaStackConfig(configurationApiClient, configs); - }); - - services.TryAddScoped(serviceProvider => - { - var configurationApiClient = serviceProvider.GetRequiredService(); - return new MultiEnvironmentMasaStackConfig(configurationApiClient, configs); - }); - - return services; - } - - public static IMasaStackConfig GetMasaStackConfig(this IServiceCollection services) - { - return services.BuildServiceProvider().GetRequiredService(); - } - - public static DccOptions? GetDccOptions(this IServiceCollection services) - { - return services.BuildServiceProvider().GetService(); - } - - public static IMultiEnvironmentMasaStackConfig GetMultiEnvironmentMasaStackConfig(this IServiceCollection services) - { - return services.BuildServiceProvider().GetRequiredService(); - } - - private static Dictionary GetConfigMap(IServiceCollection services) - { - var serviceProvider = services.BuildServiceProvider(); - var configuration = serviceProvider.GetRequiredService(); - - string environment = configuration.GetValue(MasaStackConfigConstant.ENVIRONMENT); - environment = string.IsNullOrWhiteSpace(environment) ? configuration["ASPNETCORE_ENVIRONMENT"] : environment; - - var configs = new Dictionary() - { - { MasaStackConfigConstant.VERSION, configuration.GetValue(MasaStackConfigConstant.VERSION) }, - { MasaStackConfigConstant.IS_DEMO, configuration.GetValue(MasaStackConfigConstant.IS_DEMO).ToString() }, - { MasaStackConfigConstant.DOMAIN_NAME, configuration.GetValue(MasaStackConfigConstant.DOMAIN_NAME) }, - { MasaStackConfigConstant.NAMESPACE, configuration.GetValue(MasaStackConfigConstant.NAMESPACE) }, - { MasaStackConfigConstant.CLUSTER, configuration.GetValue(MasaStackConfigConstant.CLUSTER) }, - { MasaStackConfigConstant.OTLP_URL, configuration.GetValue(MasaStackConfigConstant.OTLP_URL) }, - { MasaStackConfigConstant.REDIS, configuration.GetValue(MasaStackConfigConstant.REDIS) }, - { MasaStackConfigConstant.CONNECTIONSTRING, configuration.GetValue(MasaStackConfigConstant.CONNECTIONSTRING) }, - { MasaStackConfigConstant.MASA_STACK, configuration.GetValue(MasaStackConfigConstant.MASA_STACK) }, - { MasaStackConfigConstant.ELASTIC, configuration.GetValue(MasaStackConfigConstant.ELASTIC) }, - { MasaStackConfigConstant.ENVIRONMENT, environment }, - { MasaStackConfigConstant.ADMIN_PWD, configuration.GetValue(MasaStackConfigConstant.ADMIN_PWD) }, - { MasaStackConfigConstant.DCC_SECRET, configuration.GetValue(MasaStackConfigConstant.DCC_SECRET) }, - { MasaStackConfigConstant.SUFFIX_IDENTITY, configuration.GetValue(MasaStackConfigConstant.SUFFIX_IDENTITY) } - }; - - return configs; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/StringExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/StringExtensions.cs deleted file mode 100644 index 69bad231c..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/StringExtensions.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Config; - -public static class StringExtensions -{ - public static string ToName(this string str) - { - TextInfo textInfo = new CultureInfo("en-US", false).TextInfo; - return textInfo.ToTitleCase(str.Replace('-', '.').Replace('_', '.')); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/_Imports.cs deleted file mode 100644 index 3604b067b..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Config/_Imports.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Configuration; -global using Masa.BuildingBlocks.Data.Contracts; -global using Masa.BuildingBlocks.StackSdks.Config; -global using Masa.BuildingBlocks.StackSdks.Config.Models; -global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Options; -global using Masa.Contrib.StackSdks.Config; -global using Microsoft.Extensions.Configuration; -global using Microsoft.Extensions.DependencyInjection.Extensions; -global using System.Collections.Concurrent; -global using System.Globalization; -global using System.Runtime.CompilerServices; -global using System.Text.Json; -global using System.Text.Json.Nodes; -global using static Masa.Contrib.StackSdks.Config.Constants; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/DccClient.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/DccClient.cs deleted file mode 100644 index e11477f05..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/DccClient.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Dcc; - -public class DccClient : IDccClient -{ - public DccClient(IDistributedCacheClient distributedCacheClient) - { - LabelService = new LabelService(distributedCacheClient); - } - - public ILabelService LabelService { get; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/Internal/Constants.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/Internal/Constants.cs deleted file mode 100644 index fc04d1697..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/Internal/Constants.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Dcc.Internal; - -internal static class Constants -{ - internal const string DEFAULT_CLIENT_NAME = "masa.contrib.basicability.dcc"; -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/Masa.Contrib.StackSdks.Dcc.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/Masa.Contrib.StackSdks.Dcc.csproj deleted file mode 100644 index 5689c613e..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/Masa.Contrib.StackSdks.Dcc.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - enable - enable - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/README.md b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/README.md deleted file mode 100644 index 7761d2106..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/README.md +++ /dev/null @@ -1,54 +0,0 @@ -[中](README.zh-CN.md) | EN - -## Masa.Contrib.StackSdks.Dcc - -Effect: - -Obtain relevant data of Dcc service through DccClient,If you need to use the configuration related capabilities, please refer to the[document](../../Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/README.zh-CN.md) - -```c# -IDccClient -├── LabelService Label service -``` - -Example: - -```C# -Install-Package Masa.Contrib.StackSdks.Dcc -``` - -appsettings.json - -```json -{ - "DccOptions": { - "RedisOptions": { - "Servers": [ - { - "Host": "localhost", - "Port": 8889 - } - ], - "DefaultDatabase": 0, - "Password": "" - } - } -} -``` - -```C# -builder.Services.AddDccClient(); -``` - -How to use: - -```c# -var app = builder.Build(); - -app.MapGet("/GetProjectTypes", ([FromServices] IDccClient dccClient, string typeCode) => -{ - return dccClient.LabelService.GetListByTypeCodeAsync(typeCode); -}); - -app.Run(); -``` diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/README.zh-CN.md b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/README.zh-CN.md deleted file mode 100644 index aa18c6961..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/README.zh-CN.md +++ /dev/null @@ -1,54 +0,0 @@ -中 | [EN](README.md) - -## Masa.Contrib.StackSdks.Dcc - -作用: - -通过DccClient获取Dcc服务的相关数据,如需使用配置相关能力请查看[文档](../../Configuration/Masa.Contrib.Configuration.ConfigurationApi.Dcc/README.zh-CN.md) - -```c# -IDccClient -├── LabelService 标签服务 -``` - -用例: - -```C# -Install-Package Masa.Contrib.StackSdks.Dcc -``` - -appsettings.json - -```json -{ - "DccOptions": { - "RedisOptions": { - "Servers": [ - { - "Host": "localhost", - "Port": 8889 - } - ], - "DefaultDatabase": 0, - "Password": "" - } - } -} -``` - -```C# -builder.Services.AddDccClient(); -``` - -如何使用: - -```c# -var app = builder.Build(); - -app.MapGet("/GetProjectTypes", ([FromServices] IDccClient dccClient, string typeCode) => -{ - return dccClient.LabelService.GetListByTypeCodeAsync(typeCode); -}); - -app.Run(); -``` diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/Service/LabelService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/Service/LabelService.cs deleted file mode 100644 index 2027a94d8..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/Service/LabelService.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Dcc.Service; - -public class LabelService : ILabelService -{ - private readonly IDistributedCacheClient _distributedCacheClient; - - public LabelService(IDistributedCacheClient distributedCacheClient) - { - _distributedCacheClient = distributedCacheClient; - } - - public async Task> GetListByTypeCodeAsync(string typeCode) - { - var result = await _distributedCacheClient.GetAsync>(typeCode); - - return result ?? new(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/ServiceCollectionExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/ServiceCollectionExtensions.cs deleted file mode 100644 index 592bcd2a6..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -// ReSharper disable once CheckNamespace - -namespace Microsoft.Extensions.DependencyInjection; - -public static class ServiceCollectionExtensions -{ - public static IServiceCollection AddDccClient(this IServiceCollection services, string sectionName = "DccOptions") - { - services.AddConfigure($"{sectionName}:RedisOptions", DEFAULT_CLIENT_NAME); - return services.AddDccClientCore(); - } - - public static IServiceCollection AddDccClient(this IServiceCollection services, Action options) - { - services.Configure(DEFAULT_CLIENT_NAME, options); - return services.AddDccClientCore(); - } - - public static IServiceCollection AddDccClient(this IServiceCollection services, RedisConfigurationOptions options) - { - services.AddDistributedCache(DEFAULT_CLIENT_NAME, distributedCacheOptions => - { - distributedCacheOptions.UseStackExchangeRedisCache(options); - }); - - return services.AddDccClientCore(false); - } - - private static IServiceCollection AddDccClientCore(this IServiceCollection services, bool isUseStackExchangeRedisCache = true) - { - if (isUseStackExchangeRedisCache) - services.AddDistributedCache(DEFAULT_CLIENT_NAME, distributedCacheOptions => - { - distributedCacheOptions.UseStackExchangeRedisCache(); - }); - - services.AddSingleton(serviceProvider => - { - var client = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); - - return new DccClient(client); - }); - MasaApp.TrySetServiceCollection(services); - return services; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/_Imports.cs deleted file mode 100644 index cc241b80c..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Dcc/_Imports.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Caching; -global using Masa.BuildingBlocks.Data; -global using Masa.BuildingBlocks.StackSdks.Dcc; -global using Masa.BuildingBlocks.StackSdks.Dcc.Contracts.Model; -global using Masa.BuildingBlocks.StackSdks.Dcc.Service; -global using Masa.Contrib.Caching.Distributed.StackExchangeRedis; -global using Masa.Contrib.StackSdks.Dcc; -global using Masa.Contrib.StackSdks.Dcc.Service; -global using static Masa.Contrib.StackSdks.Dcc.Internal.Constants; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/ApplicationBuilderExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/ApplicationBuilderExtensions.cs deleted file mode 100644 index 03b6b276c..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/ApplicationBuilderExtensions.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Isolation; - -public static class ApplicationBuilderExtensions -{ - public static WebApplication UseStackIsolation(this WebApplication app) - { - app.UseIsolation(); - app.UseMiddleware(); - return app; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/DccConfigurationIsolationRepository.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/DccConfigurationIsolationRepository.cs deleted file mode 100644 index 22eecbf53..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/DccConfigurationIsolationRepository.cs +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Isolation; - -internal class DccConfigurationIsolationRepository : AbstractConfigurationRepository -{ - readonly IConfigurationApiClient _client; - - public override SectionTypes SectionType => SectionTypes.ConfigurationApi; - - readonly ConcurrentDictionary> _dictionaries = new(); - - readonly ConcurrentDictionary _configObjectConfigurationTypeRelations = new(); - - public DccConfigurationIsolationRepository( - IEnumerable sectionOptions, - IConfigurationApiClient client, - ILoggerFactory loggerFactory) - : base(loggerFactory) - { - _client = client; - - foreach (var sectionOption in sectionOptions) - { - Initialize(sectionOption).ConfigureAwait(false).GetAwaiter().GetResult(); - } - } - - private async Task Initialize(DccSectionOptions sectionOption) - { - foreach (var configObject in sectionOption.ConfigObjects) - { - string key = $"{sectionOption.Environment}-{sectionOption.Cluster}-{sectionOption.AppId}-{configObject}".ToLower(); - var result = await _client.GetRawAsync(sectionOption.Environment, sectionOption.Cluster, sectionOption.AppId, configObject, (val) => - { - if (_configObjectConfigurationTypeRelations.TryGetValue(key, out var configurationType)) - { - _dictionaries[key] = FormatRaw(sectionOption.Environment, sectionOption.AppId, configObject, val, configurationType); - FireRepositoryChange(SectionType, Load()); - } - }); - - _configObjectConfigurationTypeRelations.TryAdd(key, result.ConfigurationType); - _dictionaries[key] = FormatRaw(sectionOption.Environment, sectionOption.AppId, configObject, result.Raw, result.ConfigurationType); - } - } - - private static IDictionary FormatRaw(string environment, string appId, string configObject, string? raw, ConfigurationTypes configurationType) - { - if (raw == null) - return new Dictionary(); - - return configurationType switch - { - ConfigurationTypes.Json => SecondaryFormat(environment, appId, configObject, JsonConfigurationParser.Parse(raw)), - ConfigurationTypes.Properties => SecondaryFormat(environment, appId, configObject, JsonSerializer.Deserialize>(raw)!), - ConfigurationTypes.Text => new Dictionary - { - { $"{environment}{ConfigurationPath.KeyDelimiter}{appId}{ConfigurationPath.KeyDelimiter}{configObject}" , raw } - }, - ConfigurationTypes.Xml => SecondaryFormat(environment, appId, configObject, JsonConfigurationParser.Parse(raw)), - ConfigurationTypes.Yaml => SecondaryFormat(environment, appId, configObject, JsonConfigurationParser.Parse(raw)), - _ => throw new NotSupportedException(nameof(configurationType)), - }; - } - - private static IDictionary SecondaryFormat( - string environment, - string appId, - string configObject, - IDictionary data) - { - var dictionary = new Dictionary(); - foreach (var item in data) - { - dictionary[$"{environment}{ConfigurationPath.KeyDelimiter}{appId}{ConfigurationPath.KeyDelimiter}{configObject}{ConfigurationPath.KeyDelimiter}{item.Key}"] = item.Value; - } - return dictionary; - } - - public override Properties Load() - { - Dictionary properties = _dictionaries - .SelectMany(item => item.Value) - .ToDictionary(keyValuePair => keyValuePair.Key, keyValuePair => keyValuePair.Value ?? ""); - - return new Properties(properties); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EnvironmentCallerMiddleware.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EnvironmentCallerMiddleware.cs deleted file mode 100644 index 4bf3b065f..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EnvironmentCallerMiddleware.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Isolation; - -public class EnvironmentCallerMiddleware : ICallerMiddleware -{ - readonly ILogger? _logger; - - public EnvironmentCallerMiddleware(ILoggerFactory? loggerFactory = null) - { - _logger = loggerFactory?.CreateLogger(); - } - - public async Task HandleAsync(MasaHttpContext masaHttpContext, CallerHandlerDelegate next, CancellationToken cancellationToken = default) - { - try - { - if (masaHttpContext.RequestMessage.Content != null && masaHttpContext.RequestMessage.Content.Headers.ContentType?.MediaType == "application/json") - { - var body = await masaHttpContext.RequestMessage.Content.ReadAsStringAsync(CancellationToken.None); - var obj = JsonSerializer.Deserialize(body, new JsonSerializerOptions - { - PropertyNameCaseInsensitive = true - }); - if (!string.IsNullOrEmpty(obj?.Environment) && !masaHttpContext.RequestMessage.Headers.Any(x => x.Key == IsolationConsts.ENVIRONMENT)) - { - masaHttpContext.RequestMessage.Headers.Add(IsolationConsts.ENVIRONMENT, obj?.Environment); - } - } - } - catch (Exception exception) - { - _logger?.LogDebug(exception, "Environment Middleware Deserialize!"); - } - finally - { - await next(); - } - } -} - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EnvironmentMiddleware.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EnvironmentMiddleware.cs deleted file mode 100644 index 6f6785355..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EnvironmentMiddleware.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Isolation -{ - internal class EnvironmentMiddleware : IMiddleware - { - readonly IMultiEnvironmentContext _multiEnvironmentContext; - readonly ILogger _logger; - - public EnvironmentMiddleware(IMultiEnvironmentContext multiEnvironmentContext, - ILogger logger) - { - _multiEnvironmentContext = multiEnvironmentContext; - _logger = logger; - } - - public Task InvokeAsync(HttpContext context, RequestDelegate next) - { - _logger.LogDebug("----- Current Environment Is [{CurrentEnvironment}] -----", _multiEnvironmentContext.CurrentEnvironment); - return next(context); - } - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EnvironmentModel.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EnvironmentModel.cs deleted file mode 100644 index 2b4b3b48e..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EnvironmentModel.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Isolation; - -internal class EnvironmentModel : IEnvironmentModel -{ - public string Environment { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EsIsolationConfigProvider.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EsIsolationConfigProvider.cs deleted file mode 100644 index fdf8cc871..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/EsIsolationConfigProvider.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Isolation; - -public class EsIsolationConfigProvider -{ - readonly IMultiEnvironmentContext _multiEnvironmentContext; - readonly EnvironmentProvider _environmentProvider; - readonly IMultiEnvironmentMasaStackConfig _multiEnvironmentMasaStackConfig; - readonly IMasaStackConfig _masaStackConfig; - readonly ILogger? _logger; - - readonly Dictionary _esOptions = new(StringComparer.InvariantCultureIgnoreCase); - - public EsIsolationConfigProvider( - EnvironmentProvider environmentProvider, - ILogger? logger, - IMultiEnvironmentContext multiEnvironmentContext, - IMultiEnvironmentMasaStackConfig multiEnvironmentMasaStackConfig, - IMasaStackConfig masaStackConfig) - { - _multiEnvironmentContext = multiEnvironmentContext; - _environmentProvider = environmentProvider; - _multiEnvironmentMasaStackConfig = multiEnvironmentMasaStackConfig; - _logger = logger; - _masaStackConfig = masaStackConfig; - - InitData(); - } - - void InitData() - { - foreach (var envionment in _environmentProvider.GetEnvionments()) - { - var result = _esOptions.TryAdd(envionment, _multiEnvironmentMasaStackConfig.SetEnvironment(envionment).ElasticModel); - if (!result) - { - _logger?.LogWarning("Duplicate key {Envionment}", envionment); - } - } - } - - public ElasticModel GetEsOptions() - { - if (!_esOptions.Any()) - { - throw new UserFriendlyException("Missing es configuration, please check the configuration of MasaStackConfig"); - } - if (_esOptions.ContainsKey(_multiEnvironmentContext.CurrentEnvironment)) - { - return _esOptions[_multiEnvironmentContext.CurrentEnvironment]; - } - if (_esOptions.ContainsKey(_masaStackConfig.Environment)) - { - _logger?.LogError("The current environment does not match the es configuration, use the configuration of the _masaStackConfig.Environment {Envionment}", _masaStackConfig.Environment); - return _esOptions[_masaStackConfig.Environment]; - } - - _logger?.LogError("No es configuration is matched, the first item is used by default"); - return _esOptions.First().Value; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/IsolationConfigurationApi.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/IsolationConfigurationApi.cs deleted file mode 100644 index 9773e2b7e..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/IsolationConfigurationApi.cs +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Isolation; - -internal class IsolationConfigurationApi : IConfigurationApi -{ - readonly IConfiguration _configuration; - readonly IHttpContextAccessor _httpContextAccessor; - readonly IMasaStackConfig _stackConfig; - - public IsolationConfigurationApi( - IConfiguration configuration, - IHttpContextAccessor httpContextAccessor, - IServiceProvider serviceProvider) - { - _configuration = configuration; - _httpContextAccessor = httpContextAccessor; - _stackConfig = serviceProvider.CreateScope().ServiceProvider.GetRequiredService(); - } - - public IConfiguration Get(string appId) - { - var multiEnvironmentContext = _httpContextAccessor.HttpContext?.RequestServices.GetService(); - var environment = multiEnvironmentContext?.CurrentEnvironment; - if (environment.IsNullOrEmpty()) - { - var multiEnvironmentUserContext = _httpContextAccessor.HttpContext?.RequestServices.GetService(); - environment = multiEnvironmentUserContext?.Environment; - } - - if (environment.IsNullOrEmpty()) - { - environment = _stackConfig.Environment; - } - if (environment.IsNullOrEmpty()) - { - return _configuration.GetSection(SectionTypes.ConfigurationApi.ToString()).GetSection(appId); - } - return _configuration.GetSection(SectionTypes.ConfigurationApi.ToString()).GetSection(environment).GetSection(appId); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/Masa.Contrib.StackSdks.Isolation.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/Masa.Contrib.StackSdks.Isolation.csproj deleted file mode 100644 index 64df7aa75..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/Masa.Contrib.StackSdks.Isolation.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - enable - enable - - - - - - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/MasaConfigurationBuilderExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/MasaConfigurationBuilderExtensions.cs deleted file mode 100644 index 2e2fc3d15..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/MasaConfigurationBuilderExtensions.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Isolation; - -internal static class MasaConfigurationBuilderExtensions -{ - public static IMasaConfigurationBuilder UseDccIsolation(this IMasaConfigurationBuilder builder) - { - var serviceProvider = builder.Services.BuildServiceProvider(); - var dccOptions = builder.Services.GetDccOptions(); - MasaArgumentException.ThrowIfNull(dccOptions); - var dccConfigurationOptions = ComplementDccConfigurationOption(builder, dccOptions); - - var configurationApiClient = serviceProvider.GetRequiredService(); - var loggerFactory = serviceProvider.GetRequiredService(); - var source = new MasaConfigurationIsolationSource(new DccConfigurationIsolationRepository(dccConfigurationOptions.GetAllSections(), - configurationApiClient, loggerFactory)); - - var configurationBuilder = serviceProvider.GetService() as IConfigurationBuilder; - configurationBuilder.AddConfiguration(builder.Add(source).Build()); - return builder; - } - - public static DccConfigurationOptions ComplementDccConfigurationOption( - IMasaConfigurationBuilder builder, - DccOptions dccOptions) - { - DccConfigurationOptions dccConfigurationOptions = dccOptions; - var serviceProvider = builder.Services.BuildServiceProvider(); - var environmentProvider = serviceProvider.GetRequiredService(); - var cacheClient = serviceProvider.GetRequiredService().Create("masa.contrib.configuration.configurationapi.dcc"); - var masaAppConfigureOptions = serviceProvider.GetRequiredService>().Value; - - dccConfigurationOptions.PublicId = masaAppConfigureOptions.GetValue(nameof(DccOptions.PublicId), () => DccConsts.PUBLIC_ID); - dccConfigurationOptions.PublicSecret = masaAppConfigureOptions.GetValue(nameof(DccOptions.PublicSecret)); - - dccConfigurationOptions.DefaultSection.ComplementAndCheckAppId(masaAppConfigureOptions.AppId); - dccConfigurationOptions.DefaultSection.ComplementAndCheckEnvironment(masaAppConfigureOptions.Environment); - dccConfigurationOptions.DefaultSection.ComplementAndCheckCluster(masaAppConfigureOptions.Cluster); - dccConfigurationOptions.DefaultSection.ComplementConfigObjects(cacheClient); - - foreach (var environment in environmentProvider.GetEnvionments()) - { - if (environment != dccConfigurationOptions.DefaultSection.Environment && - !dccConfigurationOptions.ExpandSections.Exists(section => section.AppId.Equals(dccConfigurationOptions.DefaultSection.AppId) - && section.Environment.Equals(environment))) - { - var environmentAppSection = new DccSectionOptions - { - AppId = dccConfigurationOptions.DefaultSection.AppId, - Secret = dccConfigurationOptions.DefaultSection.Secret, - Environment = environment, - Cluster = dccConfigurationOptions.DefaultSection.Cluster - }; - environmentAppSection.ComplementConfigObjects(cacheClient); - dccConfigurationOptions.ExpandSections.Add(environmentAppSection); - } - if (!dccConfigurationOptions.ExpandSections.Exists(section => section.AppId.Equals(dccConfigurationOptions.PublicId) && section.Environment.Equals(environment))) - { - var publicSection = new DccSectionOptions - { - AppId = dccConfigurationOptions.PublicId, - Secret = dccConfigurationOptions.PublicSecret, - Environment = environment, - Cluster = dccConfigurationOptions.DefaultSection.Cluster - }; - publicSection.ComplementConfigObjects(cacheClient); - dccConfigurationOptions.ExpandSections.Add(publicSection); - } - } - return dccConfigurationOptions; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/MasaConfigurationIsolationProvider.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/MasaConfigurationIsolationProvider.cs deleted file mode 100644 index 2553babf9..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/MasaConfigurationIsolationProvider.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Isolation; - -internal class MasaConfigurationIsolationProvider : ConfigurationProvider, IRepositoryChangeListener, IDisposable -{ - private readonly ConcurrentDictionary _data; - private readonly DccConfigurationIsolationRepository _configurationIsolationRepository; - - public MasaConfigurationIsolationProvider(DccConfigurationIsolationRepository configurationIsolationRepository) - { - _data = new(); - _configurationIsolationRepository = configurationIsolationRepository; - configurationIsolationRepository.AddChangeListener(this); - } - - public override void Load() - { - var properties = _configurationIsolationRepository.Load(); - _data[_configurationIsolationRepository.SectionType] = properties; - SetData(); - } - - public void OnRepositoryChange(SectionTypes sectionType, Properties newProperties) - { - if (_data[sectionType] == newProperties) - return; - - _data[sectionType] = newProperties; - SetData(); - OnReload(); - } - - void SetData() - { - Data = _data.SelectMany(kv => - kv.Value.GetPropertyNames().Select(key => - new KeyValuePair($"{kv.Key}{ConfigurationPath.KeyDelimiter}{key}", kv.Value.GetProperty(key)!) - ) - ).ToDictionary(kv => kv.Key, kv => kv.Value, StringComparer.OrdinalIgnoreCase); - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - _configurationIsolationRepository.RemoveChangeListener(this); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/MasaConfigurationIsolationSource.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/MasaConfigurationIsolationSource.cs deleted file mode 100644 index 9019f533b..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/MasaConfigurationIsolationSource.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Isolation; - -internal class MasaConfigurationIsolationSource : IConfigurationSource -{ - readonly DccConfigurationIsolationRepository _configurationIsolationRepository; - - public MasaConfigurationIsolationSource(DccConfigurationIsolationRepository configurationIsolationRepository) - { - _configurationIsolationRepository = configurationIsolationRepository; - } - - public IConfigurationProvider Build(IConfigurationBuilder builder) => new MasaConfigurationIsolationProvider(_configurationIsolationRepository); -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/ServiceCollectionExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/ServiceCollectionExtensions.cs deleted file mode 100644 index b0c23a672..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Isolation; - -public static class ServiceCollectionExtensions -{ - public static async Task AddStackIsolationAsync(this IServiceCollection services, string name) - { - services.AddIsolation(isolationBuilder => - { - isolationBuilder.UseMultiEnvironment(IsolationConsts.ENVIRONMENT, new List() - { - new HttpContextItemParserProvider(), - new QueryStringParserProvider(), - new FormParserProvider(), - new RouteParserProvider(), - new HeaderParserProvider(), - new CurrentUserEnvironmentParseProvider(), - new MasaAppConfigureParserProvider(), - new EnvironmentVariablesParserProvider() - }); - }); - - var pmClient = services.BuildServiceProvider().GetRequiredService(); - var environments = (await pmClient.EnvironmentService.GetListAsync()).Select(e => e.Name).ToList(); - - services.AddSingleton((sp) => { return new EnvironmentProvider(environments); }); - - services.AddDccIsolation(builder => builder.UseDccIsolation()); - - if (!name.IsNullOrEmpty()) - { - services.ConfigureConnectionStrings(name); - } - services.ConfigureRedisOptions(); - services.ConfigureMultilevelCacheOptions(); - services.ConfigStorageOptions(); - - services.AddScoped(); - - services.AddScoped(); - - return services; - } - - static void ConfigureConnectionStrings(this IServiceCollection services, string name) - { - var (environments, multiEnvironmentMasaStackConfig, masaStackConfig) = services.GetInternal(); - services.Configure>(options => - { - foreach (var environment in environments) - { - options.Data.Add(new() - { - Environment = environment, - Data = new ConnectionStrings(new List>() - { - new(ConnectionStrings.DEFAULT_CONNECTION_STRING_NAME, multiEnvironmentMasaStackConfig.SetEnvironment(environment).GetConnectionString(name)) - }) - }); - } - }); - - services.Configure(options => - { - //default value map appsettings.json -> ConnectionStrings -> DefaultConnection - if (!options.Any()) - { - options.Add(ConnectionStrings.DEFAULT_CONNECTION_STRING_NAME, masaStackConfig.GetConnectionString(name)); - } - }); - } - - static void ConfigureRedisOptions(this IServiceCollection services) - { - var (environments, multiEnvironmentMasaStackConfig, masaStackConfig) = services.GetInternal(); - services.Configure>(options => - { - foreach (var environment in environments) - { - var redisModel = multiEnvironmentMasaStackConfig.SetEnvironment(environment).RedisModel; - options.Data.Add(new IsolationConfigurationOptions() - { - Environment = environment, - Data = new RedisConfigurationOptions - { - Password = redisModel.RedisPassword, - Servers = new() { - new RedisServerOptions - { - Host = redisModel.RedisHost, - Port = redisModel.RedisPort - } - }, - DefaultDatabase = redisModel.RedisDb, - InstanceId = environment - } - }); - } - }); - services.Configure(options => - { - var redisModel = masaStackConfig.RedisModel; - options.Password = redisModel.RedisPassword; - options.Servers = new() - { - new RedisServerOptions - { - Host = redisModel.RedisHost, - Port = redisModel.RedisPort - } - }; - options.DefaultDatabase = redisModel.RedisDb; - }); - } - - static void ConfigureMultilevelCacheOptions(this IServiceCollection services) - { - var (environments, _, _) = services.GetInternal(); - string subKeyPrefix = Assembly.GetEntryAssembly()?.GetName().Name ?? ""; - services.Configure>(options => - { - foreach (var environment in environments) - { - options.Data.Add(new IsolationConfigurationOptions() - { - Environment = environment, - Data = new MultilevelCacheGlobalOptions - { - InstanceId = environment, - SubscribeKeyType = SubscribeKeyType.SpecificPrefix, - SubscribeKeyPrefix = subKeyPrefix - } - }); - } - }); - services.Configure(options => - { - options.SubscribeKeyType = SubscribeKeyType.SpecificPrefix; - options.SubscribeKeyPrefix = subKeyPrefix; - }); - } - - static void ConfigStorageOptions(this IServiceCollection services) - { - var (environments, _, _) = services.GetInternal(); - var configuration = services.BuildServiceProvider().GetRequiredService(); - services.Configure>(options => - { - foreach (var environment in environments) - { - try - { - var ossOptions = configuration.GetSection(SectionTypes.ConfigurationApi.ToString()).GetSection(environment) - .GetSection(DccConsts.PUBLIC_ID).GetSection("$public.OSS").Get(); - if (ossOptions == null) - { - continue; - } - options.Data.Add(new IsolationConfigurationOptions() - { - Environment = environment, - Data = Convert(ossOptions) - }); - } - catch (Exception ex) - { - Console.Out.WriteLine(ex.Message); - } - } - }); - - services.Configure(options => - { - var ossOptions = configuration.GetSection(SectionTypes.ConfigurationApi.ToString()) - .GetSection(DccConsts.PUBLIC_ID).GetSection("$public.OSS").Get(); - options.AccessKeyId = ossOptions.AccessId; - options.AccessKeySecret = ossOptions.AccessSecret; - options.Sts = new AliyunStsOptions - { - RegionId = ossOptions.RegionId - }; - options.Storage = new AliyunStorageOptions - { - BucketNames = new BucketNames(new Dictionary { { BucketNames.DEFAULT_BUCKET_NAME, ossOptions.Bucket } }), - Endpoint = ossOptions.Endpoint, - RoleArn = ossOptions.RoleArn, - RoleSessionName = ossOptions.RoleSessionName - }; - }); - - AliyunStorageConfigureOptions Convert(OssOptions ossOptions) - { - return new AliyunStorageConfigureOptions - { - AccessKeyId = ossOptions.AccessId, - AccessKeySecret = ossOptions.AccessSecret, - Sts = new AliyunStsOptions - { - RegionId = ossOptions.RegionId - }, - Storage = new AliyunStorageOptions - { - BucketNames = new BucketNames(new Dictionary { { BucketNames.DEFAULT_BUCKET_NAME, ossOptions.Bucket } }), - Endpoint = ossOptions.Endpoint, - RoleArn = ossOptions.RoleArn, - RoleSessionName = ossOptions.RoleSessionName - } - }; - } - } - - public static void AddDccIsolation(this IServiceCollection services, Action configureDelegate) - { - services.Replace(new ServiceDescriptor(typeof(IConfigurationApi), typeof(IsolationConfigurationApi), ServiceLifetime.Singleton)); - - MasaConfigurationBuilder masaConfigurationBuilder = new MasaConfigurationBuilder(services, new ConfigurationBuilder()); - configureDelegate?.Invoke(masaConfigurationBuilder); - } - - static (List, IMultiEnvironmentMasaStackConfig, IMasaStackConfig) GetInternal(this IServiceCollection services) - { - var masaStackConfig = services.BuildServiceProvider().GetRequiredService(); - var multiEnvironmentMasaStackConfig = services.BuildServiceProvider().GetRequiredService(); - var environmentProvider = services.BuildServiceProvider().GetRequiredService(); - return (environmentProvider.GetEnvionments(), multiEnvironmentMasaStackConfig, masaStackConfig); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/_Imports.cs deleted file mode 100644 index 8720caa05..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Isolation/_Imports.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Authentication.Identity; -global using Masa.BuildingBlocks.Caching; -global using Masa.BuildingBlocks.Configuration; -global using Masa.BuildingBlocks.Configuration.Options; -global using Masa.BuildingBlocks.Data; -global using Masa.BuildingBlocks.Isolation; -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Config; -global using Masa.BuildingBlocks.StackSdks.Config.Models; -global using Masa.BuildingBlocks.StackSdks.Isolation; -global using Masa.BuildingBlocks.StackSdks.Isolation.Models; -global using Masa.BuildingBlocks.StackSdks.Pm; -global using Masa.BuildingBlocks.Storage.ObjectStorage; -global using Masa.Contrib.Caching.Distributed.StackExchangeRedis; -global using Masa.Contrib.Caching.MultilevelCache; -global using Masa.Contrib.Configuration; -global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Internal.Parser; -global using Masa.Contrib.Configuration.ConfigurationApi.Dcc.Options; -global using Masa.Contrib.Isolation.MultiEnvironment; -global using Masa.Contrib.Isolation.Parser; -global using Masa.Contrib.StackSdks.Config; -global using Masa.Contrib.Storage.ObjectStorage.Aliyun; -global using Masa.Contrib.Storage.ObjectStorage.Aliyun.Options; -global using Microsoft.AspNetCore.Builder; -global using Microsoft.AspNetCore.Http; -global using Microsoft.Extensions.Configuration; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.Extensions.DependencyInjection.Extensions; -global using Microsoft.Extensions.Logging; -global using Microsoft.Extensions.Options; -global using System.Collections.Concurrent; -global using System.Reflection; -global using System.Text.Json; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Constants.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Constants.cs deleted file mode 100644 index 0a8b699bf..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Constants.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc; - -internal static class Constants -{ - public const string DEFAULT_CLIENT_NAME = "masa.contrib.basicability.mc"; -} - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Infrastructure/Extensions/DictionaryExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Infrastructure/Extensions/DictionaryExtensions.cs deleted file mode 100644 index 9ef71c22b..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Infrastructure/Extensions/DictionaryExtensions.cs +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Infrastructure.Extensions; - -/// -/// Extension methods for Dictionary. -/// -public static class DictionaryExtensions -{ - /// - /// This method is used to try to get a value in a dictionary if it does exists. - /// - /// Type of the value - /// The collection object - /// Key - /// Value of the key (or default value if key not exists) - /// True if key does exists in the dictionary - internal static bool TryGetValue(this IDictionary dictionary, string key, out T value) - { - object valueObj; - if (dictionary.TryGetValue(key, out valueObj!) && valueObj is T) - { - value = (T)valueObj; - return true; - } - - value = default!; - return false; - } - - /// - /// Gets a value from the dictionary with given key. Returns default value if can not find. - /// - /// Dictionary to check and get - /// Key to find the value - /// Type of the key - /// Type of the value - /// Value if found, default if can not found. - public static TValue? GetOrDefault(this IDictionary dictionary, TKey key) - { - return dictionary.TryGetValue(key, out var obj) ? obj : default; - } - - /// - /// Gets a value from the dictionary with given key. Returns default value if can not find. - /// - /// Dictionary to check and get - /// Key to find the value - /// Type of the key - /// Type of the value - /// Value if found, default if can not found. - public static TValue? GetOrDefault(this IReadOnlyDictionary dictionary, TKey key) - { - return dictionary.TryGetValue(key, out var obj) ? obj : default; - } - - /// - /// Gets a value from the dictionary with given key. Returns default value if can not find. - /// - /// Dictionary to check and get - /// Key to find the value - /// Type of the key - /// Type of the value - /// Value if found, default if can not found. - public static TValue? GetOrDefault(this ConcurrentDictionary dictionary, TKey key) where TKey : notnull - { - return dictionary.TryGetValue(key, out var obj) ? obj : default; - } - - /// - /// Gets a value from the dictionary with given key. Returns default value if can not find. - /// - /// Dictionary to check and get - /// Key to find the value - /// A factory method used to create the value if not found in the dictionary - /// Type of the key - /// Type of the value - /// Value if found, default if can not found. - public static TValue? GetOrAdd(this IDictionary dictionary, [NotNull] TKey key, Func factory) - { - TValue? obj; - - if (key == null) - { - throw new KeyNotFoundException(); - } - - if (dictionary.TryGetValue(key, out obj)) - { - return obj; - } - - return dictionary[key] = factory(key); - } - - /// - /// Gets a value from the dictionary with given key. Returns default value if can not find. - /// - /// Dictionary to check and get - /// Key to find the value - /// A factory method used to create the value if not found in the dictionary - /// Type of the key - /// Type of the value - /// Value if found, default if can not found. - public static TValue? GetOrAdd(this IDictionary dictionary, [NotNull] TKey key, Func factory) - { - return dictionary.GetOrAdd(key, k => factory()); - } - - /// - /// Gets a value from the concurrent dictionary with given key. Returns default value if can not find. - /// - /// Concurrent dictionary to check and get - /// Key to find the value - /// A factory method used to create the value if not found in the dictionary - /// Type of the key - /// Type of the value - /// Value if found, default if can not found. - public static TValue GetOrAdd(this ConcurrentDictionary dictionary, [NotNull] TKey key, - Func factory) where TKey : notnull - { - return dictionary.GetOrAdd(key, k => factory()); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Infrastructure/Extensions/ExtraPropertiesExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Infrastructure/Extensions/ExtraPropertiesExtensions.cs deleted file mode 100644 index 619478d92..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Infrastructure/Extensions/ExtraPropertiesExtensions.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Infrastructure.Extensions; - -public static class ExtraPropertiesExtensions -{ - public static bool HasProperty(this ExtraPropertyDictionary source, string name) - { - return source.ContainsKey(name); - } - - public static object? GetProperty(this ExtraPropertyDictionary source, string name, object? defaultValue = null) - { - return source.GetOrDefault(name) - ?? defaultValue; - } - - public static TProperty? GetProperty(this ExtraPropertyDictionary source, string name, TProperty? defaultValue = default) - { - var value = source.GetProperty(name); - if (value == null) - { - return defaultValue; - } - - if (TypeHelper.IsPrimitiveExtended(typeof(TProperty), includeEnums: true)) - { - var conversionType = typeof(TProperty); - if (TypeHelper.IsNullable(conversionType)) - { - conversionType = conversionType.GetFirstGenericArgumentIfNullable(); - } - - if (conversionType == typeof(Guid)) - { - return (TProperty?)TypeDescriptor.GetConverter(conversionType).ConvertFromInvariantString(value.ToString()!); - } - - if (conversionType == typeof(DateTimeOffset)) - { - return (TProperty?)TypeDescriptor.GetConverter(conversionType).ConvertFromInvariantString(value.ToString()!); - } - - return (TProperty?)Convert.ChangeType(value?.ToString(), conversionType, CultureInfo.InvariantCulture); - } - - throw new Exception("GetProperty does not support non-primitive types. Use non-generic GetProperty method and handle type casting manually."); - } - - public static TSource SetProperty( - this TSource source, - string name, - object value) - where TSource : ExtraPropertyDictionary - { - source[name] = value; - - return source; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Infrastructure/Helper/TypeHelper.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Infrastructure/Helper/TypeHelper.cs deleted file mode 100644 index 7eabc6663..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Infrastructure/Helper/TypeHelper.cs +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Infrastructure.Helper; - -public static class TypeHelper -{ - private static readonly HashSet FloatingTypes = new HashSet - { - typeof(float), - typeof(double), - typeof(decimal) - }; - - private static readonly HashSet NonNullablePrimitiveTypes = new HashSet - { - typeof(byte), - typeof(short), - typeof(int), - typeof(long), - typeof(sbyte), - typeof(ushort), - typeof(uint), - typeof(ulong), - typeof(bool), - typeof(float), - typeof(decimal), - typeof(DateTime), - typeof(DateTimeOffset), - typeof(TimeSpan), - typeof(Guid) - }; - - public static bool IsNonNullablePrimitiveType(Type type) - { - return NonNullablePrimitiveTypes.Contains(type); - } - - public static bool IsFunc(object obj) - { - if (obj == null) - { - return false; - } - - var type = obj.GetType(); - if (!type.GetTypeInfo().IsGenericType) - { - return false; - } - - return type.GetGenericTypeDefinition() == typeof(Func<>); - } - - public static bool IsFunc(object obj) - { - return obj != null && obj.GetType() == typeof(Func); - } - - public static bool IsPrimitiveExtended(Type type, bool includeNullables = true, bool includeEnums = false) - { - if (IsPrimitiveExtendedInternal(type, includeEnums)) - { - return true; - } - - if (includeNullables && IsNullable(type) && type.GenericTypeArguments.Any()) - { - return IsPrimitiveExtendedInternal(type.GenericTypeArguments[0], includeEnums); - } - - return false; - } - - public static bool IsNullable(Type type) - { - return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); - } - - public static Type GetFirstGenericArgumentIfNullable(this Type t) - { - if (t.GetGenericArguments().Length > 0 && t.GetGenericTypeDefinition() == typeof(Nullable<>)) - { - return t.GetGenericArguments().FirstOrDefault() ?? t; - } - - return t; - } - - private static bool IsPrimitiveExtendedInternal(Type type, bool includeEnums) - { - if (type.IsPrimitive) - { - return true; - } - - if (includeEnums && type.IsEnum) - { - return true; - } - - return type == typeof(string) || - type == typeof(decimal) || - type == typeof(DateTimeOffset) || - type == typeof(DateTimeOffset) || - type == typeof(TimeSpan) || - type == typeof(Guid); - } - - public static T? GetDefaultValue() - { - return default; - } - - public static object? GetDefaultValue(Type type) - { - if (type.IsValueType) - { - return Activator.CreateInstance(type); - } - - return null; - } - - public static bool IsFloatingType(Type type, bool includeNullable = true) - { - if (FloatingTypes.Contains(type)) - { - return true; - } - - if (includeNullable && - IsNullable(type) && - FloatingTypes.Contains(type.GenericTypeArguments[0])) - { - return true; - } - - return false; - } - - public static object ConvertFrom(object value) - { - return ConvertFrom(typeof(TTargetType), value); - } - - public static object ConvertFrom(Type targetType, object value) - { - return TypeDescriptor - .GetConverter(targetType) - .ConvertFrom(value)?? value; - } - - public static Type StripNullable(Type type) - { - return IsNullable(type) - ? type.GenericTypeArguments[0] - : type; - } - - public static bool IsDefaultValue(object obj) - { - if (obj == null) - { - return true; - } - - return obj.Equals(GetDefaultValue(obj.GetType())); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Masa.Contrib.StackSdks.Mc.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Masa.Contrib.StackSdks.Mc.csproj deleted file mode 100644 index fb8354daa..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Masa.Contrib.StackSdks.Mc.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - enable - enable - - - - - - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/McClient.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/McClient.cs deleted file mode 100644 index c7c217c7d..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/McClient.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc; - -public class McClient: IMcClient -{ - public McClient(ICaller caller) - { - ChannelService = new ChannelService(caller); - MessageTaskService = new MessageTaskService(caller); - MessageTemplateService = new MessageTemplateService(caller); - ReceiverGroupService = new ReceiverGroupService(caller); - WebsiteMessageService = new WebsiteMessageService(caller); - } - - public IChannelService ChannelService { get; } - - public IMessageTaskService MessageTaskService { get; } - - public IMessageTemplateService MessageTemplateService { get; } - - public IReceiverGroupService ReceiverGroupService { get; } - - public IWebsiteMessageService WebsiteMessageService { get; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/ChannelService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/ChannelService.cs deleted file mode 100644 index 1e7fedc91..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/ChannelService.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Service; - -public class ChannelService : IChannelService -{ - readonly ICaller _caller; - readonly string _party = "api/channel"; - - public ChannelService(ICaller caller) - { - _caller = caller; - } - - public async Task GetAsync(Guid id) - { - var requestUri = $"{_party}/{id}"; - return await _caller.GetAsync(requestUri); - } - - public async Task> GetListAsync(GetChannelModel options) - { - var requestUri = $"{_party}"; - return await _caller.GetAsync>(requestUri, options) ?? new(); - } - - public async Task CreateAsync(CreateChannelModel options) - { - var requestUri = $"{_party}"; - await _caller.PostAsync(requestUri, options); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/MessageTaskService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/MessageTaskService.cs deleted file mode 100644 index 6b8f3414f..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/MessageTaskService.cs +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Service; - -public class MessageTaskService : IMessageTaskService -{ - readonly ICaller _caller; - readonly string _party = "api/message-task"; - - public MessageTaskService(ICaller caller) - { - _caller = caller; - } - - public async Task GetAsync(Guid id) - { - var requestUri = $"{_party}/{id}"; - return await _caller.GetAsync(requestUri); - } - - public async Task SendOrdinaryMessageByInternalAsync(SendOrdinaryMessageByInternalModel options) - { - var requestUri = $"{_party}/SendOrdinaryMessageByInternal"; - await _caller.PostAsync(requestUri, options); - } - - public async Task SendTemplateMessageByInternalAsync(SendTemplateMessageByInternalModel options) - { - var requestUri = $"{_party}/SendTemplateMessageByInternal"; - await _caller.PostAsync(requestUri, options); - } - - public async Task SendOrdinaryMessageByExternalAsync(SendOrdinaryMessageByExternalModel options) - { - var requestUri = $"{_party}/SendOrdinaryMessageByExternal"; - await _caller.PostAsync(requestUri, options); - } - - public async Task SendTemplateMessageByExternalAsync(SendTemplateMessageByExternalModel options) - { - var requestUri = $"{_party}/SendTemplateMessageByExternal"; - await _caller.PostAsync(requestUri, options); - } - - public async Task> GetListAsync(GetMessageTaskModel options) - { - var requestUri = $"{_party}"; - return await _caller.GetAsync>(requestUri, options) ?? new(); - } - - public async Task DeleteAsync(Guid id) - { - var requestUri = $"{_party}/{id}"; - await _caller.DeleteAsync(requestUri, null); - } - - public async Task UpdateAsync(Guid id, MessageTaskUpsertModel messageTask) - { - var requestUri = $"{_party}/{id}"; - await _caller.PutAsync(requestUri, messageTask); - } - - public async Task SetIsEnabledAsync(Guid id, bool isEnabled) - { - var requestUri = $"{_party}/{id}/enabled/{isEnabled}"; - await _caller.PutAsync(requestUri, new { }); - } - - public async Task WithdrawnAsync(Guid id) - { - var requestUri = $"{_party}/{id}/Withdrawn"; - await _caller.PostAsync(requestUri, new { }); - } - - public async Task ResendAsync(Guid id) - { - var requestUri = $"{_party}/{id}/Resend"; - await _caller.PostAsync(requestUri, new { }); - } - - public async Task BindClientIdAsync(BindClientIdModel options) - { - var requestUri = $"{_party}/BindClientId"; - await _caller.PostAsync(requestUri, options); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/MessageTemplateService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/MessageTemplateService.cs deleted file mode 100644 index 514e10c31..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/MessageTemplateService.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Service; - -public class MessageTemplateService : IMessageTemplateService -{ - readonly ICaller _caller; - readonly string _party = "api/message-template"; - - public MessageTemplateService(ICaller caller) - { - _caller = caller; - } - - public async Task GetAsync(Guid id) - { - var requestUri = $"{_party}/{id}"; - return await _caller.GetAsync(requestUri); - } - - public async Task> GetListAsync(GetMessageTemplateModel options) - { - var requestUri = $"{_party}"; - return await _caller.GetAsync>(requestUri, options) ?? new(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/ReceiverGroupService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/ReceiverGroupService.cs deleted file mode 100644 index 500b1b8b2..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/ReceiverGroupService.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Service; - -public class ReceiverGroupService : IReceiverGroupService -{ - readonly ICaller _caller; - readonly string _party = "api/receiver-group"; - - public ReceiverGroupService(ICaller caller) - { - _caller = caller; - } - - public async Task GetAsync(Guid id) - { - var requestUri = $"{_party}/{id}"; - return await _caller.GetAsync(requestUri); - } - - public async Task> GetListAsync(GetReceiverGroupModel options) - { - var requestUri = $"{_party}"; - return await _caller.GetAsync>(requestUri, options) ?? new(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/WebsiteMessageService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/WebsiteMessageService.cs deleted file mode 100644 index ad3c3934f..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/Service/WebsiteMessageService.cs +++ /dev/null @@ -1,85 +0,0 @@ -namespace Masa.Contrib.StackSdks.Mc.Service; - -public class WebsiteMessageService : IWebsiteMessageService -{ - readonly ICaller _caller; - readonly string _party = "api/website-message"; - - public WebsiteMessageService(ICaller caller) - { - _caller = caller; - } - - public async Task CheckAsync() - { - var requestUri = $"{_party}/Check"; - await _caller.PostAsync(requestUri, null); - } - - public async Task DeleteAsync(Guid id) - { - var requestUri = $"{_party}/{id}"; - await _caller.DeleteAsync(requestUri, null); - } - - public async Task GetAsync(Guid id) - { - var requestUri = $"{_party}/{id}"; - return await _caller.GetAsync(requestUri); - } - - public async Task> GetChannelListAsync() - { - var requestUri = $"{_party}/ChannelList"; - return await _caller.GetAsync>(requestUri) ?? new(); - } - - public async Task> GetListAsync(GetWebsiteMessageModel options) - { - var requestUri = $"{_party}"; - return await _caller.GetAsync>(requestUri, options) ?? new(); - } - - public async Task> GetNoticeListAsync(GetNoticeListModel options) - { - var requestUri = $"{_party}/NoticeList"; - return await _caller.GetAsync>(requestUri, options) ?? new(); - } - - public async Task ReadAsync(ReadWebsiteMessageModel options) - { - var requestUri = $"{_party}/Read"; - await _caller.PostAsync(requestUri, options); - } - - public async Task SetAllReadAsync(ReadAllWebsiteMessageModel options) - { - var requestUri = $"{_party}/SetAllRead"; - await _caller.PostAsync(requestUri, options); - } - - public async Task SendCheckNotificationAsync() - { - var requestUri = $"{_party}/SendCheckNotification"; - await _caller.PostAsync(requestUri, null); - } - - public async Task SendGetNotificationAsync(List userIds) - { - var requestUri = $"{_party}/SendGetNotification"; - await _caller.PostAsync(requestUri, userIds); - } - - public async Task> GetListByTagAsync(List tags, string channelCode) - { - var requestUri = $"{_party}/ListByTag"; - var options = new { tags = string.Join(",", tags), channelCode }; - return await _caller.GetAsync>(requestUri, options) ?? new(); - } - - public async Task GetUnreadAsync(GetUnreadModel options) - { - var requestUri = $"{_party}/Unread"; - return await _caller.GetAsync(requestUri, options); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/ServiceCollectionExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/ServiceCollectionExtensions.cs deleted file mode 100644 index 94e6887a1..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -// ReSharper disable once CheckNamespace - -namespace Microsoft.Extensions.DependencyInjection; - -public static class ServiceCollectionExtensions -{ - public static IServiceCollection AddMcClient(this IServiceCollection services, string mcServiceBaseAddress) - { - MasaArgumentException.ThrowIfNullOrEmpty(mcServiceBaseAddress); - - return services.AddMcClient(callerBuilder => - { - callerBuilder.UseHttpClient(builder => - { - builder.Configure = opt => opt.BaseAddress = new Uri(mcServiceBaseAddress); - }) - .UseAuthentication(); - }); - } - - public static IServiceCollection AddMcClient(this IServiceCollection services, Func mcServiceBaseAddressFunc) - { - MasaArgumentException.ThrowIfNull(mcServiceBaseAddressFunc); - - return services.AddMcClient(callerBuilder => - { - callerBuilder - .UseHttpClient(builder => - { - builder.BaseAddress = mcServiceBaseAddressFunc.Invoke(); - }) - .UseAuthentication(); - }); - } - - public static IServiceCollection AddMcClient(this IServiceCollection services, Action callerBuilder) - { - MasaArgumentException.ThrowIfNull(callerBuilder); - - if (services.Any(service => service.ServiceType == typeof(IMcClient))) - return services; - - services.AddCaller(DEFAULT_CLIENT_NAME, callerBuilder); - - services.AddScoped(serviceProvider => - { - var caller = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); - var mcCaching = new McClient(caller); - return mcCaching; - }); - - MasaApp.TrySetServiceCollection(services); - return services; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/_Imports.cs deleted file mode 100644 index be9b80040..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/_Imports.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Data; -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Mc; -global using Masa.BuildingBlocks.StackSdks.Mc.Model; -global using Masa.BuildingBlocks.StackSdks.Mc.Service; -global using Masa.Contrib.StackSdks.Mc; -global using Masa.Contrib.StackSdks.Mc.Infrastructure.Helper; -global using Masa.Contrib.StackSdks.Mc.Service; -global using Masa.Contrib.StackSdks.Isolation; -global using System.Collections.Concurrent; -global using System.ComponentModel; -global using System.Diagnostics.CodeAnalysis; -global using System.Globalization; -global using System.Reflection; -global using static Masa.Contrib.StackSdks.Mc.Constants; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/ApplicationBuilderExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/ApplicationBuilderExtensions.cs deleted file mode 100644 index af7a713ab..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/ApplicationBuilderExtensions.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Middleware; - -public static class ApplicationBuilderExtensions -{ - public static WebApplication UseStackMiddleware(this WebApplication app) - { - app.UseMiddleware(); - - app.MapHealthChecks("/hc", new HealthCheckOptions() - { - Predicate = _ => true, - ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse - }); - app.MapHealthChecks("/liveness", new HealthCheckOptions - { - Predicate = r => r.Name.Contains("self") - }); - return app; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DefaultDisabledEventDeterminer.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DefaultDisabledEventDeterminer.cs deleted file mode 100644 index f94d0bf51..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DefaultDisabledEventDeterminer.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Middleware; - -public class DefaultDisabledEventDeterminer : IDisabledEventDeterminer -{ - readonly IUserContext _userContext; - readonly IMasaStackConfig _masaStackConfig; - - public DefaultDisabledEventDeterminer(IUserContext userContext, IMasaStackConfig masaStackConfig) - { - _userContext = userContext; - _masaStackConfig = masaStackConfig; - } - - public bool DisabledCommand => true; - - public bool Determiner() - { - var account = _userContext.GetUser()?.Account?.ToLower(); - return _masaStackConfig.IsDemo && account != "admin" && !account.IsNullOrEmpty(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DefaultDisabledRequestDeterminer.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DefaultDisabledRequestDeterminer.cs deleted file mode 100644 index c8a759e90..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DefaultDisabledRequestDeterminer.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Middleware; - -internal class DefaultDisabledRequestDeterminer : IDisabledRequestDeterminer -{ - readonly IMasaStackConfig _masaStackConfig; - - public DefaultDisabledRequestDeterminer(IMasaStackConfig masaStackConfig) - { - _masaStackConfig = masaStackConfig; - } - - public bool Determiner() - { - return _masaStackConfig.IsDemo; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DisabledEventMiddleware.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DisabledEventMiddleware.cs deleted file mode 100644 index 34c1c2562..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DisabledEventMiddleware.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Middleware; - -internal class DisabledEventMiddleware : EventMiddleware - where TEvent : notnull, IEvent -{ - readonly ILogger>? _logger; - readonly IDisabledEventDeterminer _disabledEventDeterminer; - - public DisabledEventMiddleware( - IDisabledEventDeterminer disabledEventDeterminer, - ILoggerFactory? loggerFactory = null) - { - _logger = loggerFactory?.CreateLogger>(); - _disabledEventDeterminer = disabledEventDeterminer; - } - - public override async Task HandleAsync(TEvent @event, EventHandlerDelegate next) - { - if (_disabledEventDeterminer.Determiner() && (_disabledEventDeterminer.DisabledCommand && @event is ICommand)) - { - var allowedEventAttribute = Attribute.GetCustomAttribute(typeof(TEvent), typeof(AllowedEventAttribute)); - if (allowedEventAttribute == null) - { - _logger?.LogWarning("disabled event operation"); - throw new UserFriendlyException("DISABLED_OPERATE"); - } - } - await next(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DisabledRequestMiddleware.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DisabledRequestMiddleware.cs deleted file mode 100644 index bb67ff0d6..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/DisabledRequestMiddleware.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Middleware; - -public class DisabledRequestMiddleware : IMiddleware -{ - private readonly IDisabledRequestDeterminer _disabledRequestDeterminer; - - public DisabledRequestMiddleware(IDisabledRequestDeterminer disabledRequestDeterminer) - { - _disabledRequestDeterminer = disabledRequestDeterminer; - } - - public Task InvokeAsync(HttpContext context, RequestDelegate next) - { - if (_disabledRequestDeterminer.Determiner()) - { - var disabledRouteAttribute = context.GetEndpoint()?.Metadata - .GetMetadata(); - if (disabledRouteAttribute != null) - { - throw new UserFriendlyException("FORBIDDEN"); - } - } - - return next(context); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/Masa.Contrib.StackSdks.Middleware.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/Masa.Contrib.StackSdks.Middleware.csproj deleted file mode 100644 index 85d74f1da..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/Masa.Contrib.StackSdks.Middleware.csproj +++ /dev/null @@ -1,28 +0,0 @@ - - - - enable - enable - - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/README.md b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/README.md deleted file mode 100644 index 84ee87e61..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/README.md +++ /dev/null @@ -1,35 +0,0 @@ -[中](README.zh-CN.md) | EN - -## Masa.Contrib.StackSdks.Middleware - -Example: - -```C# -Install-Package Masa.Contrib.StackSdks.Middleware -``` - -```C# -builder.Services.AddStackMiddleware(); - -... - -app.UseStackMiddleware(); -``` - -`Masa.Contrib.StackSdks.Middleware` provides default implementations of `IDisabledEventDeterminer` and `IDisabledRequestDeterminer`, relying on `Masa.Contrib.Authentication.Identity`, `Masa.Contrib.StackSdks.Config`. The initialization of the corresponding code should be completed before `AddStackMiddleware`. - -You can rewrite `IDisabledEventDeterminer` and `IDisabledRequestDeterminer` to replace the default implementation according to business needs. - -```C# -builder.Services.AddScoped(); - -builder.Services.AddStackMiddleware(); -``` - -### DisabledEventMiddleware - -According to the return value of the `Determiner` method of `IDisabledRequestDeterminer`, the attribute `DisabledRouteAttribute` is determined, and the request whose routing metadata contains this attribute is disabled. - -### DisabledRequestMiddleware - -According to the return value of the `Determiner` method of `IDisabledEventDeterminer` and the `DisabledCommand` attribute (the default implementation is true, which disables all Commands), it is really necessary to add the `AllowedEventAttribute` feature to the release implementation. diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/README.zh-CN.md b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/README.zh-CN.md deleted file mode 100644 index 0d3eca86b..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/README.zh-CN.md +++ /dev/null @@ -1,35 +0,0 @@ -中 | [EN](README.md) - -## Masa.Contrib.StackSdks.Middleware - -用例: - -```C# -Install-Package Masa.Contrib.StackSdks.Middleware -``` - -```C# -builder.Services.AddStackMiddleware(); - -... - -app.UseStackMiddleware(); -``` - -`Masa.Contrib.StackSdks.Middleware`提供了`IDisabledEventDeterminer`和`IDisabledRequestDeterminer`的默认实现,依赖`Masa.Contrib.Authentication.Identity`,`Masa.Contrib.StackSdks.Config`。`AddStackMiddleware`前应完成相应代码的初始化。 - -可以根据业务需要重写`IDisabledEventDeterminer`和`IDisabledRequestDeterminer`替换默认实现。 - -```C# -builder.Services.AddScoped(); - -builder.Services.AddStackMiddleware(); -``` - -### DisabledEventMiddleware - -根据`IDisabledRequestDeterminer`的`Determiner`方法返回值,判断特性`DisabledRouteAttribute`,路由元数据包含该特性的请求禁用。 - -### DisabledRequestMiddleware - -根据`IDisabledEventDeterminer`的`Determiner`方法返回值和`DisabledCommand`属性(默认实现为true,禁用所有Command),真的特殊需要放行实现添加`AllowedEventAttribute`特性。 diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/ServiceCollectionExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/ServiceCollectionExtensions.cs deleted file mode 100644 index 9180a91c1..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Microsoft.Extensions.DependencyInjection; - -public static class ServiceCollectionExtensions -{ - public static IServiceCollection AddStackMiddleware(this IServiceCollection services) - { - services.AddPluggableServices(); - services.AddScoped(); - services.AddTransient(typeof(IEventMiddleware<>), typeof(DisabledEventMiddleware<>)); - services.AddTransient(typeof(IEventMiddleware<>), typeof(ValidatorEventMiddleware<>)); - services.AddHealthChecks().AddCheck("self", () => HealthCheckResult.Healthy("A healthy result.")); - return services; - } - - private static IServiceCollection AddPluggableServices(this IServiceCollection services) - { - services.TryAddScoped(); - services.TryAddScoped(); - return services; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/_Imports.cs deleted file mode 100644 index 4d20a816e..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Middleware/_Imports.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using HealthChecks.UI.Client; -global using Masa.BuildingBlocks.Authentication.Identity; -global using Masa.BuildingBlocks.Dispatcher.Events; -global using Masa.BuildingBlocks.ReadWriteSplitting.Cqrs.Commands; -global using Masa.BuildingBlocks.StackSdks.Auth.Contracts; -global using Masa.BuildingBlocks.StackSdks.Config; -global using Masa.BuildingBlocks.StackSdks.Middleware; -global using Masa.Contrib.StackSdks.Middleware; -global using Microsoft.AspNetCore.Builder; -global using Microsoft.AspNetCore.Diagnostics.HealthChecks; -global using Microsoft.AspNetCore.Http; -global using Microsoft.Extensions.DependencyInjection.Extensions; -global using Microsoft.Extensions.Diagnostics.HealthChecks; -global using Microsoft.Extensions.Logging; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Constants.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Constants.cs deleted file mode 100644 index 6ceb3cf67..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Constants.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Pm; - -public static class Constants -{ - internal const string DEFAULT_CLIENT_NAME = "masa.contrib.basicability.pm"; -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Masa.Contrib.StackSdks.Pm.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Masa.Contrib.StackSdks.Pm.csproj deleted file mode 100644 index 20db3b1d3..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Masa.Contrib.StackSdks.Pm.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - enable - enable - - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/PmClient.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/PmClient.cs deleted file mode 100644 index faaf9e29d..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/PmClient.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -using Masa.Contrib.StackSdks.Pm.Service; - -namespace Masa.Contrib.StackSdks.Pm; - -public class PmClient : IPmClient -{ - public PmClient(ICaller caller) - { - EnvironmentService = new EnvironmentService(caller); - ClusterService = new ClusterService(caller); - ProjectService = new ProjectService(caller); - AppService = new AppService(caller); - } - - public IProjectService ProjectService { get; init; } - - public IEnvironmentService EnvironmentService { get; init; } - - public IClusterService ClusterService { get; init; } - - public IAppService AppService { get; init; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/README.md b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/README.md deleted file mode 100644 index 65f5356d1..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/README.md +++ /dev/null @@ -1,38 +0,0 @@ -[中](README.zh-CN.md) | EN - -## Masa.Contrib.StackSdks.Pm - -Effect: - -Obtain relevant data of Pm service through pmclient - -```c# -IPmClient -├── EnvironmentService Environment service -├── ClusterService Cluster service -├── ProjectService Project service -├── AppService App service -``` - -Example: - -```C# -Install-Package Masa.Contrib.StackSdks.Pm -``` - -```C# -builder.Services.AddPmClient("Pm service address"); -``` - -How to use: - -```c# -var app = builder.Build(); - -app.MapGet("/GetProjectApps", ([FromServices] IPmClient pmClient) => -{ - return pmClient.ProjectService.GetProjectAppsAsync("development"); -}); - -app.Run(); -``` diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/README.zh-CN.md b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/README.zh-CN.md deleted file mode 100644 index d0d654591..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/README.zh-CN.md +++ /dev/null @@ -1,38 +0,0 @@ -中 | [EN](README.md) - -## Masa.Contrib.StackSdks.Pm - -作用: - -通过PmClient获取Pm服务的相关数据 - -```c# -IPmClient -├── EnvironmentService 环境服务 -├── ClusterService 集群服务 -├── ProjectService 项目服务 -├── AppService 应用服务 -``` - -用例: - -```C# -Install-Package Masa.Contrib.StackSdks.Pm -``` - -```C# -builder.Services.AddPmClient("Pm服务地址"); -``` - -如何使用: - -```c# -var app = builder.Build(); - -app.MapGet("/GetProjectApps", ([FromServices] IPmClient pmClient) => -{ - return pmClient.ProjectService.GetProjectAppsAsync("development"); -}); - -app.Run(); -``` diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/AppService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/AppService.cs deleted file mode 100644 index ceec7549f..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/AppService.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Pm.Service; - -public class AppService : IAppService -{ - private readonly ICaller _caller; - - public AppService(ICaller caller) - { - _caller = caller; - } - - public async Task GetAsync(int id) - { - var requestUri = $"api/v1/app/{id}"; - var result = await _caller.GetAsync(requestUri); - - return result ?? new(); - } - - public async Task GetByIdentityAsync(string identity) - { - var requestUri = $"open-api/app/{identity}"; - var result = await _caller.GetAsync(requestUri); - - return result ?? new(); - } - - public async Task> GetListAsync() - { - var requestUri = $"api/v1/app"; - var result = await _caller.GetAsync>(requestUri); - - return result ?? new(); - } - - public async Task> GetListByProjectIdsAsync(List projectIds) - { - var requestUri = $"api/v1/projects/app"; - var result = await _caller.PostAsync, List>(requestUri, projectIds); - - return result ?? new(); - } - - public async Task GetWithEnvironmentClusterAsync(int id) - { - var requestUri = $"api/v1/appWhitEnvCluster/{id}"; - var result = await _caller.GetAsync(requestUri); - - return result ?? new(); - } - - public async Task> GetListByAppTypes(params AppTypes[] appTypes) - { - var requestUri = $"open-api/app/by-types"; - var result = await _caller.PostAsync>(requestUri, appTypes); - - return result ?? new(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/ClusterService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/ClusterService.cs deleted file mode 100644 index 108492a56..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/ClusterService.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Pm.Service; - -public class ClusterService : IClusterService -{ - private readonly ICaller _caller; - - public ClusterService(ICaller caller) - { - _caller = caller; - } - - public async Task GetAsync(int id) - { - var requestUri = $"api/v1/cluster/{id}"; - var result = await _caller.GetAsync(requestUri); - - return result ?? new(); - } - - public async Task> GetEnvironmentClustersAsync() - { - var requestUri = $"api/v1/envClusters"; - var result = await _caller.GetAsync>(requestUri); - - return result ?? new(); - } - - public async Task> GetListAsync() - { - var requestUri = $"api/v1/cluster"; - var result = await _caller.GetAsync>(requestUri); - - return result ?? new(); - } - - public async Task> GetListByEnvIdAsync(int envId) - { - var requestUri = $"api/v1/{envId}/cluster"; - var result = await _caller.GetAsync>(requestUri); - - return result ?? new(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/EnvironmentService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/EnvironmentService.cs deleted file mode 100644 index 91d4c1862..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/EnvironmentService.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Pm.Service; - -public class EnvironmentService : IEnvironmentService -{ - private readonly ICaller _caller; - - public EnvironmentService(ICaller caller) - { - _caller = caller; - } - - public async Task GetAsync(int id) - { - var requestUri = $"api/v1/env/{id}"; - var result = await _caller.GetAsync(requestUri); - - return result ?? new(); - } - - public async Task> GetListAsync() - { - var requestUri = $"api/v1/env"; - var result = await _caller.GetAsync>(requestUri); - - return result ?? new(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/ProjectService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/ProjectService.cs deleted file mode 100644 index 22cd60207..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/Service/ProjectService.cs +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Pm.Service; - -public class ProjectService : IProjectService -{ - private readonly ICaller _caller; - - public ProjectService(ICaller caller) - { - _caller = caller; - } - - public async Task> GetProjectAppsAsync(string envName) - { - var requestUri = $"open-api/projectwithapps/{envName}"; - var result = await _caller.GetAsync>(requestUri); - - return result ?? new(); - } - - public async Task GetAsync(int id) - { - var requestUri = $"api/v1/project/{id}"; - var result = await _caller.GetAsync(requestUri); - - return result ?? new(); - } - - public async Task GetByIdentityAsync(string identity) - { - var requestUri = $"open-api/project/{identity}"; - var result = await _caller.GetAsync(requestUri); - - return result ?? new(); - } - - public async Task> GetListByEnvironmentClusterIdAsync(int envClusterId) - { - var requestUri = $"api/v1/{envClusterId}/project"; - var result = await _caller.GetAsync>(requestUri); - - return result ?? new(); - } - - public async Task> GetListByTeamIdsAsync(List teamIds, string environment) - { - var requestUri = $"open-api/project/teamProjects/{environment}"; - var result = await _caller.PostAsync>(requestUri, teamIds); - - return result ?? new(); - } - - public async Task> GetProjectTypesAsync() - { - var requestUri = $"api/v1/project/projectType"; - var result = await _caller.GetAsync>(requestUri); - - return result ?? new(); - } - - public async Task> GetListAsync() - { - var requestUri = $"api/v1/projects"; - var result = await _caller.GetAsync>(requestUri); - - return result ?? new(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/ServiceCollectionExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/ServiceCollectionExtensions.cs deleted file mode 100644 index 690a67d40..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -// ReSharper disable once CheckNamespace - -namespace Microsoft.Extensions.DependencyInjection; - -public static class ServiceCollectionExtensions -{ - public static IServiceCollection AddPmClient(this IServiceCollection services, string pmServiceBaseAddress) - { - MasaArgumentException.ThrowIfNullOrEmpty(pmServiceBaseAddress); - - return services.AddPmClient(callerBuilder => - { - callerBuilder.UseHttpClient(builder => - { - builder.BaseAddress = pmServiceBaseAddress; - }).UseAuthentication(); - }); - } - - public static IServiceCollection AddPmClient(this IServiceCollection services, Func pmServiceBaseAddressFunc) - { - MasaArgumentException.ThrowIfNull(pmServiceBaseAddressFunc); - - return services.AddPmClient(callerBuilder => - { - callerBuilder.UseHttpClient(builder => - { - builder.BaseAddress = pmServiceBaseAddressFunc.Invoke(); - }).UseAuthentication(); - }); - } - - public static IServiceCollection AddPmClient(this IServiceCollection services, Action callerBuilder) - { - MasaArgumentException.ThrowIfNull(callerBuilder); - - if (services.Any(service => service.ServiceType == typeof(IPmClient))) - return services; - - services.AddCaller(DEFAULT_CLIENT_NAME, callerBuilder.Invoke); - - services.AddScoped(serviceProvider => - { - var callProvider = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); - var pmCaching = new PmClient(callProvider); - return pmCaching; - }); - - MasaApp.TrySetServiceCollection(services); - return services; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/_Imports.cs deleted file mode 100644 index ac988b79c..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/_Imports.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Data; -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Pm; -global using Masa.BuildingBlocks.StackSdks.Pm.Enum; -global using Masa.BuildingBlocks.StackSdks.Pm.Model; -global using Masa.BuildingBlocks.StackSdks.Pm.Service; -global using Masa.Contrib.StackSdks.Pm; -global using static Masa.Contrib.StackSdks.Pm.Constants; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Constants.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Constants.cs deleted file mode 100644 index e2e5289e8..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Constants.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Scheduler; - -internal static class Constants -{ - internal const string DEFAULT_CLIENT_NAME = "masa.contrib.basicability.scheduler"; - internal const string ENVIRONMENT_KEY = "env_key"; -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/HttpClientAuthorizationDelegatingHandler.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/HttpClientAuthorizationDelegatingHandler.cs deleted file mode 100644 index 07ca11efa..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/HttpClientAuthorizationDelegatingHandler.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Scheduler; - -public class HttpClientAuthorizationDelegatingHandler : DelegatingHandler -{ - readonly IHttpContextAccessor _httpContextAccessor; - - public HttpClientAuthorizationDelegatingHandler(IHttpContextAccessor httpContextAccessor) - { - _httpContextAccessor = httpContextAccessor; - } - - protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - if (_httpContextAccessor.HttpContext != null) - { - var accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token"); - request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); - } - return await base.SendAsync(request, cancellationToken); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Logger/SchedulerLogger.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Logger/SchedulerLogger.cs deleted file mode 100644 index d379812e7..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Logger/SchedulerLogger.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Scheduler.Logger -{ - public class SchedulerLogger - { - private readonly ILogger _logger; - - private readonly Guid _taskId; - - private readonly Guid _jobId; - - public const string LOGGER_BODY = "{Message}, LogType: {LogType}, LogWriter: {LogWriter}, TaskId: {TaskId}, JobId: {JobId}"; - - public SchedulerLogger(ILoggerFactory loggerFactory, Guid jobId, Guid taskId) - { - _logger = loggerFactory.CreateLogger(); - _jobId = jobId; - _taskId = taskId; - } - - public void LogInformation(string message) - { - _logger.LogInformation(LOGGER_BODY, message, LoggerTypes.JobLog.ToString(), WriterTypes.Job.ToString(), _taskId, _jobId); - } - - public void LogError(Exception exception, string message) - { - _logger.LogError(exception, LOGGER_BODY, message, LoggerTypes.JobLog.ToString(), WriterTypes.Job.ToString(), _taskId, _jobId); - } - - public void LogError(string message) - { - _logger.LogError(LOGGER_BODY, message, LoggerTypes.JobLog.ToString(), WriterTypes.Job.ToString(), _taskId, _jobId); - } - - public void LogWarning(string message) - { - _logger.LogWarning(LOGGER_BODY, message, LoggerTypes.JobLog.ToString(), WriterTypes.Job.ToString(), _taskId, _jobId); - } - - public void LogDebug(string message) - { - _logger.LogDebug(LOGGER_BODY, message, LoggerTypes.JobLog.ToString(), WriterTypes.Job.ToString(), _taskId, _jobId); - } - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Masa.Contrib.StackSdks.Scheduler.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Masa.Contrib.StackSdks.Scheduler.csproj deleted file mode 100644 index 1f2cf4a08..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Masa.Contrib.StackSdks.Scheduler.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - - enable - enable - - - - - - - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/README.md b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/README.md deleted file mode 100644 index b89680e04..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/README.md +++ /dev/null @@ -1,41 +0,0 @@ -[中](README.zh-CN.md) | EN - -## Masa.Contrib.StackSdks.Scheduler - -Effect: - -Operate API of scheduler service through scheduler client - -```c# -ISchedulerClient -├── SchedulerJobService Scheduler Job service -├── SchedulerTaskService Scheduler Task service -``` - -Example: - -```C# -Install-Package Masa.Contrib.StackSdks.Scheduler -``` - -```C# -builder.Services.AddSchedulerClient("Scheduler service address"); -``` - -How to use: - -```c# -var app = builder.Build(); - -app.MapGet("/startjob", ([FromServices] ISchedulerClient schedulerClient) => -{ - var request = new BaseSchedulerJobRequest() - { - JobId = new Guid("39351BF4-0E58-463F-5C96-08DA42DF67D6"), - OperatorId = new Guid("15905535-C90F-4BCA-467B-08DA42E0A2C0") - }; - return schedulerClient.SchedulerJobService.StartAsync(request); -}); - -app.Run(); -``` diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/README.zh-CN.md b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/README.zh-CN.md deleted file mode 100644 index 85cff55be..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/README.zh-CN.md +++ /dev/null @@ -1,41 +0,0 @@ -中 | [EN](README.md) - -## Masa.Contrib.StackSdks.Scheduler - -作用: - -通过Scheduler Client 操作Scheduler服务的API - -```c# -ISchedulerClient -├── SchedulerJobService Job服务 -├── SchedulerTaskService Task服务 -``` - -用例: - -```C# -Install-Package Masa.Contrib.StackSdks.Scheduler -``` - -```C# -builder.Services.AddSchedulerClient("Scheduler service address"); -``` - -如何使用: - -```c# -var app = builder.Build(); - -app.MapGet("/startjob", ([FromServices] ISchedulerClient schedulerClient) => -{ - var request = new BaseSchedulerJobRequest() - { - JobId = new Guid("39351BF4-0E58-463F-5C96-08DA42DF67D6"), - OperatorId = new Guid("15905535-C90F-4BCA-467B-08DA42E0A2C0") - }; - return schedulerClient.SchedulerJobService.StartAsync(request); -}); - -app.Run(); -``` diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/SchedulerClient.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/SchedulerClient.cs deleted file mode 100644 index 1881fa0e2..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/SchedulerClient.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Scheduler; - -public class SchedulerClient : ISchedulerClient -{ - public ISchedulerJobService SchedulerJobService { get; } - - public ISchedulerTaskService SchedulerTaskService { get; } - - public SchedulerClient(ICaller caller) - { - SchedulerJobService = new SchedulerJobService(caller); - SchedulerTaskService = new SchedulerTaskService(caller); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/SchedulerJob.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/SchedulerJob.cs deleted file mode 100644 index cf81723f6..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/SchedulerJob.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Scheduler; - -public abstract class SchedulerJob : ISchedulerJob -{ - protected SchedulerLogger Logger { get; set; } - - protected WebApplicationBuilder Builder { get; set; } - - protected IServiceProvider ServiceProvider { get; set; } - - public Task InitializeAsync(WebApplicationBuilder builder, Guid jobId, Guid taskId) - { - Builder = builder; - ServiceProvider = builder.Services.BuildServiceProvider(); - var loggerFactory = ServiceProvider.GetRequiredService(); - Logger = new SchedulerLogger(loggerFactory, jobId, taskId); - return Task.CompletedTask; - } - - public virtual Task AfterExcuteAsync(JobContext context) - { - return Task.CompletedTask; - } - - public virtual Task BeforeExcuteAsync(JobContext context) - { - return Task.CompletedTask; - } - - public abstract Task ExcuteAsync(JobContext context); -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/ServiceCollectionExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/ServiceCollectionExtensions.cs deleted file mode 100644 index f0243eb12..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/ServiceCollectionExtensions.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -// ReSharper disable once CheckNamespace - -namespace Microsoft.Extensions.DependencyInjection; - -public static class ServiceCollectionExtensions -{ - public static IServiceCollection AddSchedulerClient(this IServiceCollection services, string schedulerServiceBaseAddress) - { - if (string.IsNullOrWhiteSpace(schedulerServiceBaseAddress)) - { - throw new ArgumentNullException(nameof(schedulerServiceBaseAddress)); - } - - return services.AddSchedulerClient(callerBuilder => - { - callerBuilder - .UseHttpClient(builder => - { - builder.Configure = opt => opt.BaseAddress = new Uri(schedulerServiceBaseAddress); - }) - .UseAuthentication(); - }); - } - - public static IServiceCollection AddSchedulerClient(this IServiceCollection services, Action callerBuilder) - { - ArgumentNullException.ThrowIfNull(callerBuilder, nameof(callerBuilder)); - -#if (NET8_0_OR_GREATER) - if (services.Any(service => service.IsKeyedService == false && service.ImplementationType == typeof(SchedulerProvider))) - return services; -#else - if (services.Any(service => service.ImplementationType == typeof(SchedulerProvider))) - return services; -#endif - - services.AddSingleton(); - services.AddCaller(DEFAULT_CLIENT_NAME, callerBuilder); - - services.AddScoped(serviceProvider => - { - var caller = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); - var schedulerClient = new SchedulerClient(caller); - return schedulerClient; - }); - - MasaApp.TrySetServiceCollection(services); - return services; - } - - private sealed class SchedulerProvider - { - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Services/SchedulerJobService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Services/SchedulerJobService.cs deleted file mode 100644 index f50b3667c..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Services/SchedulerJobService.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Scheduler.Services; - -public class SchedulerJobService : ISchedulerJobService -{ - const string API = "/api/scheduler-job"; - - readonly ICaller _caller; - - public SchedulerJobService(ICaller caller) - { - _caller = caller; - } - - public async Task AddAsync(UpsertSchedulerJobRequest job) - { - ValidateUpsertSchedulerJobRequest(job); - - var requestUri = $"{API}/addSchedulerJobBySdk"; - return await _caller.PostAsync(requestUri, job); - } - - public async Task UpdateAsync(Guid id, UpsertSchedulerJobRequest job) - { - ValidateUpsertSchedulerJobRequest(job); - - var requestUri = $"{API}/{id}/updateSchedulerJobBySdk"; - await _caller.PutAsync(requestUri, job); - } - - public async Task DisableAsync(SchedulerJobRequestBase request) - { - var requestData = new ChangeEnabledStatusRequest() - { - JobId = request.JobId, - OperatorId = request.OperatorId, - Enabled = false - }; - var requestUri = $"{API}/changeEnableStatus"; - await _caller.PutAsync(requestUri, requestData); - return true; - } - - public async Task EnableAsync(SchedulerJobRequestBase request) - { - var requestData = new ChangeEnabledStatusRequest() - { - JobId = request.JobId, - OperatorId = request.OperatorId, - Enabled = true - }; - var requestUri = $"{API}/changeEnableStatus"; - await _caller.PutAsync(requestUri, requestData); - return true; - } - - public async Task GetSchedulerJobQueryByIdentityAsync(GetSchedulerJobByIdentityRequest request) - { - var requestUri = $"{API}/getSchedulerJobQueryByIdentity"; - return await _caller.GetAsync(requestUri, request); - } - - public async Task RemoveAsync(SchedulerJobRequestBase request) - { - var requestUri = $"{API}"; - await _caller.DeleteAsync(requestUri, request); - return true; - } - - public async Task StartAsync(SchedulerJobRequestBase request) - { - var requestUri = $"{API}/startJob"; - await _caller.PutAsync(requestUri, request); - return true; - } - - private static void ValidateUpsertSchedulerJobRequest(UpsertSchedulerJobRequest job) - { - MasaArgumentException.ThrowIfNull(job.ProjectIdentity, nameof(job.ProjectIdentity)); - - switch (job.JobType) - { - case JobTypes.JobApp: - MasaArgumentException.ThrowIfNull(job.JobAppConfig, nameof(job.JobAppConfig)); - break; - case JobTypes.Http: - MasaArgumentException.ThrowIfNull(job.HttpConfig, nameof(job.HttpConfig)); - break; - case JobTypes.DaprServiceInvocation: - MasaArgumentException.ThrowIfNull(job.DaprServiceInvocationConfig, nameof(job.DaprServiceInvocationConfig)); - break; - } - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Services/SchedulerTaskService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Services/SchedulerTaskService.cs deleted file mode 100644 index aafbde0df..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/Services/SchedulerTaskService.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Scheduler.Services; - -public class SchedulerTaskService : ISchedulerTaskService -{ - const string API = "/api/scheduler-task"; - - readonly ICaller _caller; - - public SchedulerTaskService(ICaller caller) - { - _caller = caller; - } - - public async Task StopAsync(SchedulerTaskRequestBase request) - { - var requestUri = $"{API}/stop"; - await _caller.PutAsync(requestUri, request); - return true; - } - - public async Task StartAsync(SchedulerTaskRequestBase request) - { - var requestData = new StartSchedulerTaskRequest() - { - TaskId = request.TaskId, - OperatorId = request.OperatorId, - IsManual = true - }; - - var requestUri = $"{API}/start"; - await _caller.PutAsync(requestUri, requestData); - return true; - } - - public async Task NotifyRunResultAsync(NotifySchedulerTaskRunResultRequest request) - { - var requestUri = $"{API}/notifyRunResultBySdk"; - await _caller.PostAsync(requestUri, request); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/_Imports.cs deleted file mode 100644 index 10739e795..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Scheduler/_Imports.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Data; -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Scheduler; -global using Masa.BuildingBlocks.StackSdks.Scheduler.Enum; -global using Masa.BuildingBlocks.StackSdks.Scheduler.Model; -global using Masa.BuildingBlocks.StackSdks.Scheduler.Request; -global using Masa.BuildingBlocks.StackSdks.Scheduler.Service; -global using Masa.Contrib.StackSdks.Isolation; -global using Masa.Contrib.StackSdks.Scheduler; -global using Masa.Contrib.StackSdks.Scheduler.Logger; -global using Masa.Contrib.StackSdks.Scheduler.Services; -global using Microsoft.AspNetCore.Authentication; -global using Microsoft.AspNetCore.Builder; -global using Microsoft.AspNetCore.Http; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.Extensions.Logging; -global using static Masa.Contrib.StackSdks.Scheduler.Constants; - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/ApmClickhouseServiceExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/ApmClickhouseServiceExtensions.cs deleted file mode 100644 index 756f610a7..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/ApmClickhouseServiceExtensions.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Microsoft.Extensions.DependencyInjection; - -public static class ApmClickhouseServiceExtensions -{ - internal static ILogger Logger { get; private set; } - - public static IServiceCollection AddMASAStackApmClickhouse(this IServiceCollection services, string connectionStr, string logTable, string traceTable, string? logSourceTable = null, string? traceSourceTable = null, Action? configer = null) - { - services.AddMASAStackClickhouse(connectionStr, logTable, traceTable, logSourceTable, traceSourceTable, con => - { - Constants.Init(MasaStackClickhouseConnection.LogTable.Split('.')[0], MasaStackClickhouseConnection.LogTable.Split('.')[1], MasaStackClickhouseConnection.TraceTable.Split('.')[1], "otel_errors"); - Init(services, con); - configer?.Invoke(con); - }); - services.AddScoped(); - return services; - } - - private static void Init(IServiceCollection services, IDbConnection connection) - { - var serviceProvider = services.BuildServiceProvider(); - var logfactory = serviceProvider.GetRequiredService(); - Logger = logfactory.CreateLogger("Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse"); - InitTable(connection); - } - - private static void InitTable(IDbConnection connection) - { - if (Convert.ToInt32(connection.ExecuteScalar($"select count() from system.tables where database ='{Constants.Database}' and name in ['{Constants.ErrorTable}','{Constants.ErrorTable}_v']")) > 0) - return; - var createTableSqls = new string[]{ - @$"CREATE TABLE {Constants.Database}.{Constants.ErrorTable} -( - `Timestamp` DateTime64(9) CODEC(Delta(8), ZSTD(1)), - `TraceId` String CODEC(ZSTD(1)), - `SpanId` String CODEC(ZSTD(1)), - `Attributes.exception.message` String CODEC(ZSTD(1)), - `Attributes.exception.type` String CODEC(ZSTD(1)), - `ServiceName` String CODEC(ZSTD(1)), - `Resource.service.namespace` String CODEC(ZSTD(1)), - `Attributes.http.target` String CODEC(ZSTD(1)), - INDEX idx_log_id TraceId TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_log_spanid SpanId TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_log_environment `Resource.service.namespace` TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_log_servicename ServiceName TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_log_type `Attributes.exception.type` TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_log_endpoint `Attributes.http.target` TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_string_message `Attributes.exception.message` TYPE tokenbf_v1(30720, 2, 0) GRANULARITY 1 -) -ENGINE = MergeTree -PARTITION BY toDate(Timestamp) -ORDER BY (Timestamp, - ServiceName, - `Resource.service.namespace`, - `Attributes.exception.type`, -`Attributes.http.target`) -TTL toDateTime(Timestamp) + toIntervalDay(30) -SETTINGS index_granularity = 8192, - ttl_only_drop_parts = 1; -", -$@"CREATE MATERIALIZED VIEW {Constants.Database}.{Constants.ErrorTable}_v TO {Constants.ErrorTableFull} -AS -SELECT -Timestamp,TraceId,SpanId, Body AS `Attributes.exception.message`,LogAttributes['exception.type'] AS `Attributes.exception.type`, - ServiceName,ResourceAttributes['service.namespace'] AS `Resource.service.namespace`, LogAttributes['RequestPath'] AS `Attributes.http.target` -FROM {MasaStackClickhouseConnection.LogSourceTable} -WHERE mapContains(LogAttributes, 'exception.type') -"}; - foreach (var sql in createTableSqls) - { - connection.ExecuteSql(sql); - } - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Cliclhouse/ClickhouseApmService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Cliclhouse/ClickhouseApmService.cs deleted file mode 100644 index 878041eea..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Cliclhouse/ClickhouseApmService.cs +++ /dev/null @@ -1,646 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Cliclhouse; - -internal class ClickhouseApmService : IApmService -{ - private readonly MasaStackClickhouseConnection _dbConnection; - private readonly ClickHouseCommand command; - private readonly ITraceService _traceService; - private readonly static object lockObj = new(); - private static Dictionary serviceOrders = new() { - {nameof(ServiceListDto.Name),SERVICE_NAME}, - {nameof(ServiceListDto.Envs),"env"}, - {nameof(ServiceListDto.Latency),"latency"}, - {nameof(ServiceListDto.Throughput),"throughput"}, - {nameof(ServiceListDto.Failed),"failed"}, - }; - - private static Dictionary endpointOrders = new() { - {nameof(EndpointListDto.Name),"`Attributes.http.target`"}, - {nameof(EndpointListDto.Service),SERVICE_NAME}, - {nameof(EndpointListDto.Method),"`method`"}, - {nameof(EndpointListDto.Latency),"latency"}, - {nameof(EndpointListDto.Throughput),"throughput"}, - {nameof(EndpointListDto.Failed),"failed"}, - }; - - private static Dictionary errorOrders = new() { - {nameof(ErrorMessageDto.Type),"Type"}, - {nameof(ErrorMessageDto.Message),"Message"}, - {nameof(ErrorMessageDto.LastTime),"`time`"}, - {nameof(ErrorMessageDto.Total),"`total`"} - }; - const double MILLSECOND = 1e6; - const string SERVICE_NAME = "ServiceName"; - - public ClickhouseApmService(MasaStackClickhouseConnection dbConnection, ITraceService traceService) - { - _traceService = traceService; - _dbConnection = dbConnection; - command = dbConnection.CreateCommand(); - if (_dbConnection.State == ConnectionState.Closed) - _dbConnection.Open(); - } - - public Task> ServicePageAsync(BaseApmRequestDto query) - { - query.IsServer = true; - var (where, parameters) = AppendWhere(query); - var groupby = "group by ServiceName"; - var countSql = $"select count(1) from(select count(1) from {Constants.TraceTableFull} where {where} {groupby})"; - PaginatedListBase result = new() { Total = Convert.ToInt64(Scalar(countSql, parameters)) }; - var orderBy = GetOrderBy(query, serviceOrders, defaultSort: SERVICE_NAME); - var sql = $@"select * from( -select -ServiceName, -arrayStringConcat(groupUniqArray(`Resource.service.namespace`)) env, -floor(AVG(Duration/{MILLSECOND})) latency, -round(count(1)*1.0/DATEDIFF(MINUTE ,toDateTime(@startTime),toDateTime (@endTime)),2) throughput, -round(sum(has(['{string.Join("','", query.GetErrorStatusCodes())}'],`Attributes.http.status_code`))*100.0/count(1),2) failed -from {Constants.TraceTableFull} where {where} {groupby} {orderBy} @limit)"; - SetData(sql, parameters, result, query, reader => new ServiceListDto() - { - Name = reader[0].ToString()!, - Envs = reader[1]?.ToString()?.Split(',') ?? Array.Empty(), - Latency = (long)Math.Floor(Convert.ToDouble(reader[2])), - Throughput = Math.Round(Convert.ToDouble(reader[3]), 2), - Failed = Math.Round(Convert.ToDouble(reader[4]), 2), - }); - return Task.FromResult(result); - } - - public Task> InstancePageAsync(BaseApmRequestDto query) - { - var groupBy = "group by instance"; - var selectField = $@"ResourceAttributesValues[indexOf(ResourceAttributesKeys,'service.instance.id')] instance`, -AVG(Duration/{MILLSECOND}) Latency, -count(1)*1.0/DATEDIFF(MINUTE ,toDateTime(@startTime),toDateTime (@endTime)) throughput -sum(has(['{string.Join("','", query.GetErrorStatusCodes())}'],`Attributes.http.status_code`))/count(1) failed"; - return GetEndpointAsync(query, groupBy, selectField, reader => new EndpointListDto() - { - Name = reader[0].ToString()!, - Latency = (long)Math.Floor(Convert.ToDouble(reader[1])), - Throughput = Math.Round(Convert.ToDouble(reader[2]), 2), - Failed = Math.Round(Convert.ToDouble(reader[3]), 2) - }); - } - - public Task> DependencyPageAsync(BaseApmRequestDto query) - { - var groupBy = "group by ServiceName,`Attributes.http.target`,`method`"; - var selectField = $@"`Attributes.http.target`,ServiceName,SpanAttributesValues[indexOf(SpanAttributesKeys,'http.method')] `method`, -AVG(Duration{MILLSECOND}) Latency, -count(1)*1.0/DATEDIFF(MINUTE ,toDateTime(@startTime),toDateTime (@endTime)) throughput -sum(has(['{string.Join("','", query.GetErrorStatusCodes())}'],`Attributes.http.status_code`))/count(1) failed"; - return GetEndpointAsync(query, groupBy, selectField, ConvertEndpointDto); - } - - private Task> GetEndpointAsync(BaseApmRequestDto query, string groupBy, string selectField, Func parseFn) - { - var (where, parameters) = AppendWhere(query); - var countSql = $"select count(1) from(select count(1) from {Constants.TraceTableFull} where {where} {groupBy})"; - PaginatedListBase result = new() { Total = Convert.ToInt64(Scalar(countSql, parameters)) }; - var orderBy = GetOrderBy(query, endpointOrders); - var sql = $@"select * from( select {selectField} from {Constants.TraceTableFull} where {where} {groupBy} {orderBy} @limit)"; - SetData(sql, parameters, result, query, parseFn); - return Task.FromResult(result); - } - - public Task> EndpointPageAsync(BaseApmRequestDto query) - { - query.IsServer = true; - var groupBy = "group by ServiceName,`Attributes.http.target`,SpanAttributesValues[indexOf(SpanAttributesKeys,'http.method')]"; - var selectField = $@"`Attributes.http.target`,ServiceName,SpanAttributesValues[indexOf(SpanAttributesKeys,'http.method')] `method`, -floor(AVG(Duration/{MILLSECOND})) latency, -round(count(1)*1.0/DATEDIFF(MINUTE ,toDateTime(@startTime),toDateTime (@endTime)),2) throughput, -round(sum(has(['{string.Join("','", query.GetErrorStatusCodes())}'],`Attributes.http.status_code`))*100.0/count(1),2) failed"; - return GetEndpointAsync(query, groupBy, selectField, ConvertEndpointDto); - } - - private EndpointListDto ConvertEndpointDto(IDataReader reader) - { - return new EndpointListDto() - { - Name = reader[0].ToString()!, - Service = reader[1]?.ToString()!, - Method = reader[2]?.ToString()!, - Latency = (long)Math.Floor(Convert.ToDouble(reader[3])), - Throughput = Math.Round(Convert.ToDouble(reader[4]), 2), - Failed = Math.Round(Convert.ToDouble(reader[5]), 2) - }; - } - - public Task> ChartDataAsync(BaseApmRequestDto query) - { - query.IsServer = true; - var (where, parameters) = AppendWhere(query); - var result = new List(); - var field = query is ApmEndpointRequestDto apmEndpointDto && string.IsNullOrEmpty(apmEndpointDto.Endpoint) ? "Attributes.http.target" : SERVICE_NAME; - var groupby = $"group by {field} ,`time` order by {field} ,`time`"; - var sql = $@"select -{field}, -toStartOfInterval(`Timestamp` , INTERVAL {GetPeriod(query)} ) as `time`, -floor(avg(Duration/{MILLSECOND})) `latency`, -floor(quantile(0.95)(Duration/{MILLSECOND})) `p95`, -floor(quantile(0.99)(Duration/{MILLSECOND})) `p99`, -round(sum(has(['{string.Join("','", query.GetErrorStatusCodes())}'],`Attributes.http.status_code`))*100.0/count(1),2) `failed`, -round(count(1)*1.0/DATEDIFF(MINUTE ,toDateTime(@startTime),toDateTime (@endTime)),2) `throughput` -from {Constants.TraceTableFull} where {where} {groupby}"; - lock (lockObj) - { - using var reader = Query(sql, parameters); - SetChartData(result, reader); - } - GetPreviousChartData(query, sql, parameters, result); - return Task.FromResult(result.AsEnumerable()); - } - - private void GetPreviousChartData(BaseApmRequestDto query, string sql, List parameters, List result) - { - if (!query.ComparisonType.HasValue) - return; - - int day = 0; - switch (query.ComparisonType.Value) - { - case ComparisonTypes.DayBefore: - day = -1; - break; - case ComparisonTypes.WeekBefore: - day = -7; - break; - } - if (day == 0) - return; - - var paramStartTime = parameters.First(p => p.ParameterName == "startTime"); - paramStartTime.Value = ((DateTime)paramStartTime.Value!).AddDays(day); - - var paramEndTime = parameters.First(p => p.ParameterName == "endTime"); - paramEndTime.Value = ((DateTime)paramEndTime.Value!).AddDays(day); - - lock (lockObj) - { - using var readerPrevious = Query(sql, parameters); - SetChartData(result, readerPrevious, isPrevious: true); - } - } - - private static void SetChartData(List result, IDataReader reader, bool isPrevious = false) - { - if (!reader.NextResult()) - return; - ChartLineDto? current = null; - while (reader.Read()) - { - var name = reader[0].ToString()!; - var time = new DateTimeOffset(Convert.ToDateTime(reader[1])).ToUnixTimeSeconds(); - if (current == null || current.Name != name) - { - if (isPrevious && result.Exists(item => item.Name == name)) - { - current = result.First(item => item.Name == name); - } - else - { - current = new ChartLineDto - { - Name = name, - Previous = new List(), - Currents = new List() - }; - result.Add(current); - } - } - - ((List)(isPrevious ? current.Previous : current.Currents)).Add( - new() - { - Latency = (long)Math.Floor(Convert.ToDouble(reader[2])), - P95 = Math.Round(Convert.ToDouble(reader[3]), 2, MidpointRounding.ToZero), - P99 = Math.Round(Convert.ToDouble(reader[4]), 2, MidpointRounding.ToZero), - Failed = Math.Round(Convert.ToDouble(reader[5]), 2, MidpointRounding.ToZero), - Throughput = Math.Round(Convert.ToDouble(reader[6]), 2, MidpointRounding.ToZero), - Time = time - }); - } - } - - public Task EndpointLatencyDistributionAsync(ApmEndpointRequestDto query) - { - var (where, parameters) = AppendWhere(query); - var result = new EndpointLatencyDistributionDto(); - var p95 = Convert.ToDouble(Scalar($"select floor(quantile(0.95)(Duration/{MILLSECOND})) p95 from {Constants.TraceTableFull} where {where}", parameters)); - if (p95 is not double.NaN) - result.P95 = (long)Math.Floor(p95); - var sql = $@"select Duration/{MILLSECOND},count(1) total from {Constants.TraceTableFull} where {where} group by Duration order by Duration"; - var list = new List(); - lock (lockObj) - { - using var reader = Query(sql, parameters); - while (reader.NextResult()) - while (reader.Read()) - { - var item = new ChartPointDto() - { - X = reader[0].ToString()!, - Y = reader[1]?.ToString()! - }; - list.Add(item); - } - } - result.Latencies = list; - return Task.FromResult(result); - } - - public Task> ErrorMessagePageAsync(ApmEndpointRequestDto query) - { - query.IsServer = default; - var (where, parameters) = AppendWhere(query); - var groupby = $"group by Type,Message{(string.IsNullOrEmpty(query.Endpoint) ? "" : ",Endpoint")}"; - var countSql = $"select count(1) from (select Attributes.exception.type as Type,Attributes.exception.message as Message,max(Timestamp) time,count(1) from {Constants.ErrorTableFull} where {where} {groupby})"; - PaginatedListBase result = new() { Total = Convert.ToInt64(Scalar(countSql, parameters)) }; - var orderBy = GetOrderBy(query, errorOrders); - var sql = $@"select * from( select Attributes.exception.type as Type,Attributes.exception.message as Message,max(Timestamp) time,count(1) total from {Constants.ErrorTableFull} where {where} {groupby} {orderBy} @limit)"; - SetData(sql, parameters, result, query, reader => new ErrorMessageDto() - { - Type = reader[0]?.ToString()!, - Message = reader[1]?.ToString()!, - LastTime = Convert.ToDateTime(reader[2])!, - Total = Convert.ToInt32(reader[3]), - }); - return Task.FromResult(result); - } - - private void SetData(string sql, List parameters, PaginatedListBase result, BaseApmRequestDto query, Func parseFn) where TResult : class - { - var start = (query.Page - 1) * query.PageSize; - if (result.Total - start > 0) - { - lock (lockObj) - { - using var reader = Query(sql.Replace("@limit", $"limit {start},{query.PageSize}"), parameters); - result.Result = new(); - while (reader.NextResult()) - while (reader.Read()) - result.Result.Add(parseFn(reader)); - } - } - } - - private static (string where, List parameters) AppendWhere(TQuery query) where TQuery : BaseApmRequestDto - { - List parameters = new(); - var sql = new StringBuilder(); - sql.AppendLine(" Timestamp between @startTime and @endTime"); - parameters.Add(new ClickHouseParameter { ParameterName = "startTime", Value = MasaStackClickhouseConnection.ToTimeZone(query.Start), DbType = DbType.DateTime }); - parameters.Add(new ClickHouseParameter { ParameterName = "endTime", Value = MasaStackClickhouseConnection.ToTimeZone(query.End), DbType = DbType.DateTime }); - if (!string.IsNullOrEmpty(query.Env)) - { - sql.AppendLine(" and Resource.service.namespace=@environment"); - parameters.Add(new ClickHouseParameter { ParameterName = "environment", Value = query.Env }); - } - if (!string.IsNullOrEmpty(query.Service)) - { - sql.AppendLine(" and ServiceName=@serviceName"); - parameters.Add(new ClickHouseParameter { ParameterName = "serviceName", Value = query.Service }); - } - if (query.IsServer.HasValue) - { - sql.AppendLine(" and SpanKind=@spanKind"); - parameters.Add(new ClickHouseParameter { ParameterName = "spanKind", Value = query.IsServer.Value ? "SPAN_KIND_SERVER" : "SPAN_KIND_CLIENT" }); - } - AppendEndpoint(query as ApmEndpointRequestDto, sql, parameters); - AppendDuration(query as ApmTraceLatencyRequestDto, sql, parameters); - - if (!string.IsNullOrEmpty(query.Queries) && query.Queries.Trim().Length > 0) - { - if (!query.Queries.Trim().StartsWith("and ", StringComparison.CurrentCultureIgnoreCase)) - sql.Append(" and "); - sql.AppendLine(query.Queries); - } - - return (sql.ToString(), parameters); - } - - private static void AppendEndpoint(ApmEndpointRequestDto? traceQuery, StringBuilder sql, List parameters) - { - if (traceQuery == null || string.IsNullOrEmpty(traceQuery.Endpoint)) - return; - var name = "endpoint"; - if (traceQuery.IsLog.HasValue && traceQuery.IsLog.Value) - { - sql.AppendLine($" and indexOf(LogAttributesKeys,'RequestPath')>=0 and LogAttributesValues[indexOf(LogAttributesKeys,'RequestPath')] LIKE @{name}"); - parameters.Add(new ClickHouseParameter { ParameterName = name, Value = $"{traceQuery.Endpoint}%" }); - } - else - { - sql.AppendLine($" and Attributes.http.target=@{name}"); - parameters.Add(new ClickHouseParameter { ParameterName = name, Value = traceQuery.Endpoint }); - } - } - - private static void AppendDuration(ApmTraceLatencyRequestDto? query, StringBuilder sql, List parameters) - { - if (query == null || !query.LatMin.HasValue && !query.LatMax.HasValue) return; - if (query.LatMin.HasValue && query.LatMin > 0) - { - sql.AppendLine(" and Duration >=@minDuration"); - parameters.Add(new ClickHouseParameter { ParameterName = "minDuration", Value = (long)(query.LatMin * MILLSECOND) }); - } - if (query.LatMax.HasValue && query.LatMax > 0) - { - sql.AppendLine(" and Duration <=@maxDuration"); - parameters.Add(new ClickHouseParameter { ParameterName = "maxDuration", Value = (long)(query.LatMax * MILLSECOND) }); - } - } - - public async Task> TraceLatencyDetailAsync(ApmTraceLatencyRequestDto query) - { - var queryDto = new BaseRequestDto - { - Start = query.Start, - End = query.End, - Endpoint = query.Endpoint, - Service = query.Service! - }; - var conditions = new List(); - if (!string.IsNullOrEmpty(query.Env)) - { - conditions.Add(new FieldConditionDto - { - Name = "Resource.service.namespace", - Type = ConditionTypes.Equal, - Value = query.Env - }); - } - var name = "Duration"; - if (query.LatMin.HasValue && query.LatMin.Value >= 0) - { - conditions.Add(new FieldConditionDto - { - Name = name, - Type = ConditionTypes.GreatEqual, - Value = (long)(query.LatMin.Value * MILLSECOND), - }); - } - - if (query.LatMax.HasValue && query.LatMax.Value >= 0 && ( - !query.LatMin.HasValue - || query.LatMin.HasValue && query.LatMax - query.LatMin.Value > 0)) - conditions.Add(new FieldConditionDto - { - Name = name, - Type = ConditionTypes.LessEqual, - Value = (long)(query.LatMax.Value * MILLSECOND), - }); - if (conditions.Count > 0) - queryDto.Conditions = conditions; - - return await _traceService.ListAsync(queryDto); - } - - private IDataReader Query(string sql, IEnumerable parameters) - { - command.CommandText = sql; - SetParameters(parameters); - return command.ExecuteReader(); - } - - private object Scalar(string sql, IEnumerable parameters) - { - lock (lockObj) - { - command.CommandText = sql; - SetParameters(parameters); - return command.ExecuteScalar()!; - } - } - - private void SetParameters(IEnumerable parameters) - { - if (command.Parameters.Count > 0) - command.Parameters.Clear(); - if (parameters != null && parameters.Any()) - foreach (var param in parameters) - command.Parameters.Add(param); - } - - private static string? GetOrderBy(BaseApmRequestDto query, Dictionary sortFields, string? defaultSort = null, bool isDesc = false) - { - if (!string.IsNullOrEmpty(query.OrderField) && sortFields.TryGetValue(query.OrderField, out var field)) - { - if (!query.IsDesc.HasValue) - return $"order by {field}"; - return $"order by {field}{(query.IsDesc.Value ? "" : " desc")}"; - } - - if (string.IsNullOrEmpty(defaultSort)) - return null; - return $"order by {defaultSort}{(isDesc ? " desc" : "")}"; - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - _dbConnection.Close(); - _dbConnection.Dispose(); - } - } - - public Task> GetErrorChartAsync(ApmEndpointRequestDto query) - { - query.IsServer = default; - query.IsLog = true; - var (where, parameters) = AppendWhere(query); - var groupby = "group by `time` order by `time`"; - var sql = $@"select -toStartOfInterval(`Timestamp` , INTERVAL {GetPeriod(query)} ) as `time`, -count(1) `total` -from {Constants.LogTableFull} where {where} and SeverityText='Error' and `Attributes.exception.message`!='' {groupby}"; - - return Task.FromResult(getChartCountData(sql, parameters, query.ComparisonType).AsEnumerable()); - } - - private List getChartCountData(string sql, IEnumerable parameters, ComparisonTypes? comparisonTypes = null) - { - var result = new List(); - lock (lockObj) - { - using var currentReader = Query(sql, parameters); - SetChartCountData(result, currentReader); - } - - if (comparisonTypes.HasValue && (comparisonTypes.Value == ComparisonTypes.DayBefore || comparisonTypes.Value == ComparisonTypes.WeekBefore)) - { - var day = comparisonTypes.Value == ComparisonTypes.DayBefore ? -1 : -7; - var paramStartTime = parameters.First(p => p.ParameterName == "startTime"); - paramStartTime.Value = ((DateTime)paramStartTime.Value!).AddDays(day); - - var paramEndTime = parameters.First(p => p.ParameterName == "endTime"); - paramEndTime.Value = ((DateTime)paramEndTime.Value!).AddDays(day); - - lock (lockObj) - { - using var previousReader = Query(sql, parameters); - SetChartCountData(result, previousReader, true); - } - } - - return result; - } - - private static void SetChartCountData(List result, IDataReader reader, bool isPrevious = false) - { - if (!reader.NextResult()) - return; - ChartLineCountDto? current = null; - while (reader.Read()) - { - var name = reader[0].ToString()!; - var time = new DateTimeOffset(Convert.ToDateTime(reader[0])).ToUnixTimeSeconds(); - if (current == null || current.Name != name) - { - if (isPrevious && result.Exists(item => item.Name == name)) - { - current = result.First(item => item.Name == name); - } - else - { - current = new ChartLineCountDto - { - Name = name, - Previous = new List(), - Currents = new List() - }; - result.Add(current); - } - } - - ((List)(isPrevious ? current.Previous : current.Currents)).Add( - new() - { - Value = reader[1], - Time = time - }); - } - } - - public Task> GetEndpointChartAsync(ApmEndpointRequestDto query) - { - query.IsServer = false; - var (where, parameters) = AppendWhere(query); - var groupby = "group by `time` order by `time`"; - var sql = $@"select -toStartOfInterval(`Timestamp` , INTERVAL {GetPeriod(query)} ) as `time`, -count(1) `total` -from {Constants.TraceTable} where {where} {groupby}"; - - return Task.FromResult(getChartCountData(sql, parameters, query.ComparisonType).AsEnumerable()); - } - - public Task> GetLogChartAsync(ApmEndpointRequestDto query) - { - query.IsServer = default; - query.IsLog = true; - var (where, parameters) = AppendWhere(query); - var groupby = "group by `time` order by `time`"; - var sql = $@"select -toStartOfInterval(`Timestamp` , INTERVAL {GetPeriod(query)} ) as `time`, -count(1) `total` -from {Constants.LogTableFull} where {where} {groupby}"; - return Task.FromResult(getChartCountData(sql, parameters, query.ComparisonType).AsEnumerable()); - } - - private static string GetPeriod(BaseApmRequestDto query) - { - var reg = new Regex(@"/d+", default, TimeSpan.FromSeconds(5)); - if (string.IsNullOrEmpty(query.Period) || !reg.IsMatch(query.Period)) - { - return GetDefaultPeriod(query.End - query.Start); - } - var unit = reg.Replace(query.Period, "").Trim().ToLower(); - var units = new List { "year", "month", "week", "day", "hour", "minute", "second" }; - var find = units.Find(s => s.StartsWith(unit)); - if (string.IsNullOrEmpty(find)) - find = "minute"; - return $"{reg.Match(query.Period).Result} {find}"; - } - - private static string GetDefaultPeriod(TimeSpan timeSpan) - { - if ((int)timeSpan.TotalMinutes < 1) - { - return "5 second"; - } - - if ((int)timeSpan.TotalHours < 1) - { - return "1 minute"; - } - - var days = (int)timeSpan.TotalDays; - if (days <= 0) - { - if ((int)timeSpan.TotalHours - 12 <= 0) - { - return "1 minute"; - } - return "30 minute"; - } - - if (days - 7 <= 0) - { - return "1 hour"; - } - - if (days - 30 <= 0) - { - return "1 day"; - } - - if (days - 365 <= 0) - { - return "1 week"; - } - - return "1 month"; - } - - public Task> GetTraceErrorsAsync(ApmEndpointRequestDto query) - { - query.IsServer = default; - query.IsLog = true; - var (where, parameters) = AppendWhere(query); - var groupby = "group by `SpanId` order by `SpanId`"; - var sql = $@"select -SpanId, -count(1) `total` -from {Constants.ErrorTableFull} where {where} {groupby}"; - var list = new List(); - lock (lockObj) - { - using var reader = Query(sql, parameters); - while (reader.NextResult()) - while (reader.Read()) - { - var item = new ChartPointDto() - { - X = reader[0].ToString()!, - Y = reader[1]?.ToString()! - }; - list.Add(item); - } - } - return Task.FromResult(list.AsEnumerable()); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Config/Constants.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Config/Constants.cs deleted file mode 100644 index e157eda06..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Config/Constants.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Config; - -internal static class Constants -{ - public static string Database { get; private set; } - - public static string TraceTableFull => $"{Database}.{TraceTable}"; - - public static string ErrorTableFull => $"{Database}.{ErrorTable}"; - - public static string LogTableFull => $"{Database}.{LogTable}"; - - public static string LogTable { get; private set; } - - public static string TraceTable { get; private set; } - - public static string ErrorTable { get; private set; } - - public static readonly int[] DefaultErrorStatus = new int[] { 500, 501, 502, 503, 504, 505 }; - - public static void Init(string database, string logTable, string traceTable, string errorTable) - { - Database = database; - LogTable = logTable; - TraceTable = traceTable; - ErrorTable = errorTable; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Interfaces/IAPMService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Interfaces/IAPMService.cs deleted file mode 100644 index b85f3373a..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Interfaces/IAPMService.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse; - -public interface IApmService : IDisposable -{ - /// - /// 服务列表页,服务详情页endpoints和instance公用 - /// - /// - /// - Task> ServicePageAsync(BaseApmRequestDto query); - - /// - /// trace列表 - /// - /// - /// - Task> EndpointPageAsync(BaseApmRequestDto query); - - /// - /// 可共用,service和endpoint公用 - /// - /// - /// - Task> ChartDataAsync(BaseApmRequestDto query); - - /// - /// endpoint 加载耗时分布 - /// - /// - /// - Task EndpointLatencyDistributionAsync(ApmEndpointRequestDto query); - - /// - /// tendpoint trace tree line - /// - /// - /// - Task> TraceLatencyDetailAsync(ApmTraceLatencyRequestDto query); - - /// - /// 错误列表 - /// - /// - /// - Task> ErrorMessagePageAsync(ApmEndpointRequestDto query); - - /// - /// 获取trace下的错误信息统计,按照spanId - /// - /// - /// - Task> GetTraceErrorsAsync(ApmEndpointRequestDto query); - - Task> GetErrorChartAsync(ApmEndpointRequestDto query); - - Task> GetEndpointChartAsync(ApmEndpointRequestDto query); - - Task> GetLogChartAsync(ApmEndpointRequestDto query); -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.csproj deleted file mode 100644 index 2e96e1e79..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.csproj +++ /dev/null @@ -1,15 +0,0 @@ - - - - enable - enable - 1.0-local - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/APMEnums.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/APMEnums.cs deleted file mode 100644 index 00c23676e..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/APMEnums.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models; - -public enum ComparisonTypes -{ - DayBefore = 1, - WeekBefore -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Request/ApmEndpointRequestDto.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Request/ApmEndpointRequestDto.cs deleted file mode 100644 index 6ec3e0178..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Request/ApmEndpointRequestDto.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models.Request; - -public class ApmEndpointRequestDto : BaseApmRequestDto -{ - public string Endpoint { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Request/ApmTraceLatencyRequestDto.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Request/ApmTraceLatencyRequestDto.cs deleted file mode 100644 index eef88f80b..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Request/ApmTraceLatencyRequestDto.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models.Request; - -public class ApmTraceLatencyRequestDto : ApmEndpointRequestDto -{ - /// - /// unit ms - /// - public long? LatMin { get; set; } - - /// - /// unit ms - /// - public long? LatMax { get; set; } - - public new int PageSize { get; } = 1; -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Request/BaseApmRequestDto.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Request/BaseApmRequestDto.cs deleted file mode 100644 index 7f39231e0..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Request/BaseApmRequestDto.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models.Request; - -public class BaseApmRequestDto : RequestPageBase -{ - public string? Env { get; set; } - - public ComparisonTypes? ComparisonType { get; set; } - - public DateTime Start { get; set; } - - public DateTime End { get; set; } - - public string Period { get; set; } - - public string? Service { get; set; } - - public string? Queries { get; set; } - - public string? OrderField { get; set; } - - public bool? IsDesc { get; set; } - - public string StatusCodes { get; set; } - - internal int[] GetErrorStatusCodes() => string.IsNullOrEmpty(StatusCodes) ? Constants.DefaultErrorStatus : StatusCodes.Split(',').Select(s => Convert.ToInt32(s)).Where(num => num != 0).ToArray(); - - internal bool? IsServer { get; set; } = true; - - internal bool? IsTrace { get; set; } - - internal bool? IsLog { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/EndpointChartDto.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/EndpointChartDto.cs deleted file mode 100644 index 9d32bb8de..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/EndpointChartDto.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models.Response; - -public class EndpointChartDto -{ - public IEnumerable P99s { get; set; } - - public IEnumerable P95s { get; set; } - - public IEnumerable Latencies { get; set; } - - public IEnumerable Throughputs { get; set; } - - public IEnumerable Fails { get; set; } -} - -public class ErrorMessageDto -{ - public string Type { get; set; } - - public string Message { get; set; } - - public DateTime LastTime { get; set; } - - public int Total { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/EndpointLatencyDistributionDto.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/EndpointLatencyDistributionDto.cs deleted file mode 100644 index 78146aa55..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/EndpointLatencyDistributionDto.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models.Response; - -public class EndpointLatencyDistributionDto -{ - public long? P95 { get; set; } - - public IEnumerable Latencies { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/EndpointListDto.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/EndpointListDto.cs deleted file mode 100644 index a3de5941c..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/EndpointListDto.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models.Response; - -public class EndpointListDto -{ - public string Name { get; set; } - - public string Method { get; set; } - - public string Service { get; set; } - - public string AgentType { get; set; } - - public long Latency { get; set; } - - public double Failed { get; set; } - - public double Throughput { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/ServiceListDto.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/ServiceListDto.cs deleted file mode 100644 index fffcabaa4..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/Models/Response/ServiceListDto.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models.Response; - -public class ServiceListDto -{ - public string Service { get; set; } - - public string Name { get; set; } - - public IEnumerable Envs { get; set; } - - public long Latency { get; set; } - - public double Throughput { get; set; } - - public double Failed { get; set; } -} - -public class ChartLineDto -{ - public string Name { get; set; } - - public IEnumerable Currents { get; set; } - - public IEnumerable Previous { get; set; } -} - -public class ChartLineCountDto -{ - public string Name { get; set; } - - public IEnumerable Currents { get; set; } - - public IEnumerable Previous { get; set; } -} - -public class ChartLineCountItemDto -{ - public long Time { get; set; } - - public object Value { get; set; } -} - -public class ChartLineItemDto -{ - public long Time { get; set; } - - public long Latency { get; set; } - - public double P99 { get; set; } - - public double P95 { get; set; } - - public double Throughput { get; set; } - - public double Failed { get; set; } -} - -public class ChartPointDto -{ - public string X { get; set; } - - public string Y { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/_Imports.cs deleted file mode 100644 index ff1b5ffc4..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse/_Imports.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using ClickHouse.Ado; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Model; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Service; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Trace; -global using Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse; -global using Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Cliclhouse; -global using Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Config; -global using Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models; -global using Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models.Request; -global using Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models.Response; -global using Masa.Contrib.StackSdks.Tsc.Clickhouse; -global using Masa.Utils.Models; -global using Microsoft.Extensions.Logging; -global using System.Data; -global using System.Data.Common; -global using System.Text; -global using System.Text.RegularExpressions; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Extensions/IDbConnectionExtensitions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Extensions/IDbConnectionExtensitions.cs deleted file mode 100644 index 72b35023f..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Extensions/IDbConnectionExtensitions.cs +++ /dev/null @@ -1,537 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. -[assembly: InternalsVisibleTo("Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse")] -namespace System.Data.Common; - -internal static class IDbConnectionExtensitions -{ - const string ATTRIBUTE_KEY = "Attributes."; - const string RESOURCE_KEY = "Resource."; - const string TIMSTAMP_KEY = "Timestamp"; - - public static PaginatedListBase QueryTrace(this IDbConnection connection, BaseRequestDto query) - { - var (where, parameters, ors) = AppendWhere(query); - var orderBy = AppendOrderBy(query, false); - var countSql = CombineOrs($"select count() as `total` from {MasaStackClickhouseConnection.TraceTable} where {where}", ors); - var total = Convert.ToInt64(ExecuteScalar(connection, $"select sum(`total`) from {countSql}", parameters?.ToArray())); - var start = (query.Page - 1) * query.PageSize; - var result = new PaginatedListBase() { Total = total, Result = new() }; - if (total > 0 && start - total < 0) - { - var querySql = CombineOrs($"select ServiceName,{TIMSTAMP_KEY},TraceId,SpanId,ParentSpanId,TraceState,SpanKind,Duration,SpanName,Spans,Resources from {MasaStackClickhouseConnection.TraceTable} where {where}", ors, orderBy); - result.Result = Query(connection, $"select * from {querySql} as t limit {start},{query.PageSize}", parameters?.ToArray(), ConvertTraceDto); - } - return result; - } - - public static PaginatedListBase QueryLog(this IDbConnection connection, BaseRequestDto query) - { - var (where, parameters, ors) = AppendWhere(query, false); - var orderBy = AppendOrderBy(query, true); - var countSql = CombineOrs($"select count() as `total` from {MasaStackClickhouseConnection.LogTable} where {where}", ors); - var total = Convert.ToInt64(ExecuteScalar(connection, $"select sum(`total`) from {countSql}", parameters?.ToArray())); - var start = (query.Page - 1) * query.PageSize; - var result = new PaginatedListBase() { Total = total, Result = new() }; - - - if (total > 0 && start - total < 0) - { - var querySql = CombineOrs($"select {TIMSTAMP_KEY},TraceId,SpanId,TraceFlags,SeverityText,SeverityNumber,ServiceName,Body,Resources,Logs from {MasaStackClickhouseConnection.LogTable} where {where}", ors, orderBy); - result.Result = Query(connection, $"select * from {querySql} as t limit {start},{query.PageSize}", parameters?.ToArray(), ConvertLogDto); - } - return result; - } - - private static string CombineOrs(string sql, IEnumerable ors, string? orderBy = null) - { - if (ors == null || !ors.Any()) - return $"({sql} {orderBy})"; - - var text = new StringBuilder(); - foreach (var or in ors) - { - text.AppendLine($" union all {sql}{or} {orderBy}"); - } - text.Remove(0, 11).Insert(0, '(').Append(')'); - return text.ToString(); - } - - public static List GetMapping(this IDbConnection dbConnection, bool isLog) - { - var type = isLog ? "log" : "trace"; - var result = dbConnection.Query($"select DISTINCT Name from otel_mapping Array join Name where `Type`='{type}_basic' order by Name", default, ConvertToMapping); - if (result == null || result.Count == 0) - return default!; - - var attributes = dbConnection.Query($"select DISTINCT concat('{ATTRIBUTE_KEY}',Name) from otel_mapping Array join Name where `Type`='{type}_attributes' order by Name", default, ConvertToMapping); - var resources = dbConnection.Query($"select DISTINCT concat('{RESOURCE_KEY}',Name) from otel_mapping Array join Name where `Type`='resource' order by Name", default, ConvertToMapping); - if (attributes != null && attributes.Count > 0) result.AddRange(attributes); - if (resources != null && resources.Count > 0) result.AddRange(resources); - - return result; - } - - public static List GetTraceByTraceId(this IDbConnection connection, string traceId) - { - string where = $"TraceId=@TraceId"; - return Query(connection, $"select * from (select {TIMSTAMP_KEY},TraceId,SpanId,ParentSpanId,TraceState,SpanKind,Duration,SpanName,Spans,Resources from {MasaStackClickhouseConnection.TraceTable} where {where}) as t limit 1000", new IDataParameter[] { new ClickHouseParameter { ParameterName = "TraceId", Value = traceId } }, ConvertTraceDto); - } - - public static string AppendOrderBy(BaseRequestDto query, bool isLog) - { - var field = TIMSTAMP_KEY; - var isDesc = query.Sort?.IsDesc ?? true; - if (isLog && query.Sort != null && !string.IsNullOrEmpty(query.Sort.Name)) - { - field = GetName(query.Sort.Name, isLog); - isDesc = query.Sort?.IsDesc ?? false; - } - return $" order by {field}{(isDesc ? " desc" : "")}"; - } - - public static (string where, List @parameters, List ors) AppendWhere(BaseRequestDto query, bool isTrace = true) - { - var sql = new StringBuilder(); - var @paramerters = new List(); - - if (query.Start > DateTime.MinValue && query.Start < DateTime.MaxValue - && query.End > DateTime.MinValue && query.End < DateTime.MaxValue - && query.End > query.Start) - { - sql.Append($" and {TIMSTAMP_KEY} BETWEEN @Start and @End"); - @paramerters.Add(new ClickHouseParameter() { ParameterName = "Start", Value = MasaStackClickhouseConnection.ToTimeZone(query.Start), DbType = DbType.DateTime2 }); - @paramerters.Add(new ClickHouseParameter() { ParameterName = "End", Value = MasaStackClickhouseConnection.ToTimeZone(query.End), DbType = DbType.DateTime2 }); - } - if (!string.IsNullOrEmpty(query.Service)) - { - sql.Append(" and ServiceName=@ServiceName"); - @paramerters.Add(new ClickHouseParameter() { ParameterName = "ServiceName", Value = query.Service }); - } - if (!string.IsNullOrEmpty(query.Instance)) - { - sql.Append($" and `{RESOURCE_KEY}service.instance.id`=@ServiceInstanceId"); - @paramerters.Add(new ClickHouseParameter() { ParameterName = "ServiceInstanceId", Value = query.Instance }); - } - if (isTrace && !string.IsNullOrEmpty(query.Endpoint)) - { - sql.Append($" and `{ATTRIBUTE_KEY}http.target`=@HttpTarget"); - @paramerters.Add(new ClickHouseParameter() { ParameterName = "HttpTarget", Value = query.Endpoint }); - } - var ors = AppendKeyword(query.Keyword, paramerters, isTrace); - AppendConditions(query.Conditions, paramerters, sql, isTrace); - - if (!string.IsNullOrEmpty(query.RawQuery)) - sql.Append($" and ({query.RawQuery})"); - - if (sql.Length > 0) - sql.Remove(0, 4); - return (sql.ToString(), @paramerters, ors); - } - - private static List AppendKeyword(string keyword, List @paramerters, bool isTrace = true) - { - var sqls = new List(); - if (string.IsNullOrEmpty(keyword)) - return sqls; - - //status_code - if (int.TryParse(keyword, out var num) && num != 0 && num - 1000 < 0 && isTrace) - { - sqls.Add($" and `{ATTRIBUTE_KEY}http.status_code`=@HttpStatusCode"); - sqls.Add($" and `{ATTRIBUTE_KEY}http.request_content_body` like @Keyword"); - paramerters.Add(new ClickHouseParameter() { ParameterName = "HttpStatusCode", Value = num }); - paramerters.Add(new ClickHouseParameter() { ParameterName = "Keyword", Value = $"%{keyword}%" }); - return sqls; - } - - if (isTrace) - { - sqls.Add($" and `{ATTRIBUTE_KEY}http.request_content_body` like @Keyword"); - sqls.Add($" and `{ATTRIBUTE_KEY}http.response_content_body` like @Keyword"); - sqls.Add($" and `{ATTRIBUTE_KEY}exception.message` like @Keyword"); - } - else - { - if (keyword.Equals("error", StringComparison.CurrentCultureIgnoreCase)) - sqls.Add(" and SeverityText='Error'"); - sqls.Add(" and Body like @Keyword"); - sqls.Add($" and `{ATTRIBUTE_KEY}exception.message` like @Keyword"); - } - paramerters.Add(new ClickHouseParameter() { ParameterName = "Keyword", Value = $"%{keyword}%" }); - return sqls; - } - - private static void AppendConditions(IEnumerable? conditions, List @paramerters, StringBuilder sql, bool isTrace = true) - { - if (conditions == null || !conditions.Any()) - return; - - foreach (var item in conditions) - { - var name = GetName(item.Name, !isTrace); - - if (item.Value is DateTime time) - { - item.Value = MasaStackClickhouseConnection.ToTimeZone(time); - } - if (item.Name.StartsWith(RESOURCE_KEY, StringComparison.CurrentCultureIgnoreCase)) - { - var filed = item.Name[RESOURCE_KEY.Length..]; - if (string.Equals(filed, "service.name")) - { - AppendField(item, @paramerters, sql, name, "ServiceName"); - } - else if (string.Equals(filed, "service.instance.id")) - { - AppendField(item, @paramerters, sql, name, "ServiceInstanceId"); - } - else if (string.Equals(filed, "service.namespace")) - { - AppendField(item, @paramerters, sql, name, "ServiceNameSpace"); - } - } - else if (item.Name.StartsWith(ATTRIBUTE_KEY, StringComparison.CurrentCultureIgnoreCase)) - { - var filed = item.Name[ATTRIBUTE_KEY.Length..]; - AppendField(item, @paramerters, sql, name, filed.Replace('.', '_')); - } - else - { - AppendField(item, @paramerters, sql, name, name); - } - } - } - - private static void AppendField(FieldConditionDto item, List @paramerters, StringBuilder sql, string fieldName, string paramName) - { - if (item.Value is string str && string.IsNullOrEmpty(str) || item.Value is IEnumerable collects && !collects.Any()) - return; - switch (item.Type) - { - case ConditionTypes.Equal: - { - if (@paramerters.Exists(p => p.ParameterName == paramName)) - break; - ParseWhere(sql, item.Value, paramerters, fieldName, paramName, "="); - } - break; - case ConditionTypes.NotIn: - { - ParseWhere(sql, item.Value, paramerters, fieldName, $"{paramName}s", "not in"); - } - break; - case ConditionTypes.In: - { - ParseWhere(sql, item.Value, paramerters, fieldName, $"{paramName}s", "in"); - } - break; - case ConditionTypes.LessEqual: - { - ParseWhere(sql, item.Value, paramerters, fieldName, $"lte_{paramName}", "<="); - } - break; - case ConditionTypes.GreatEqual: - { - ParseWhere(sql, item.Value, paramerters, fieldName, $"gte_{paramName}", ">="); - } - break; - case ConditionTypes.Less: - { - ParseWhere(sql, item.Value, paramerters, fieldName, $"lt_{paramName}", "<"); - } - break; - case ConditionTypes.Great: - { - ParseWhere(sql, item.Value, paramerters, fieldName, $"gt_{paramName}", ">"); - } - break; - } - } - - private static void ParseWhere(StringBuilder sql, object value, List @paramerters, string fieldName, string paramName, string compare) - { - DbType dbType = value is DateTime ? DbType.DateTime2 : DbType.AnsiString; - if (value is IEnumerable) - sql.Append($" and {fieldName} {compare} (@{paramName})"); - else - sql.Append($" and {fieldName} {compare} @{paramName}"); - @paramerters.Add(new ClickHouseParameter { ParameterName = $"{paramName}", Value = value, DbType = dbType }); - } - - public static object? ExecuteScalar(this IDbConnection dbConnection, string sql, IDataParameter[]? @parameters = null) - { - using var cmd = dbConnection.CreateCommand(); - cmd.CommandText = sql; - if (@parameters != null && @parameters.Length > 0) - foreach (var p in @parameters) - cmd.Parameters.Add(p); - OpenConnection(dbConnection); - try - { - return cmd.ExecuteScalar(); - } - catch (Exception ex) - { - MasaTscCliclhouseExtensitions.Logger?.LogError(ex, "execute sql error:{RawSql}, paramters:{Parameters}", sql, parameters); - throw; - } - } - - private static void OpenConnection(IDbConnection dbConnection) - { - if (dbConnection.State == ConnectionState.Closed) - dbConnection.Open(); - } - - public static List Query(this IDbConnection dbConnection, string sql, IDataParameter[]? @parameters, Func parse) - { - using var cmd = dbConnection.CreateCommand(); - cmd.CommandText = sql; - if (@parameters != null && @parameters.Length > 0) - foreach (var p in @parameters) - cmd.Parameters.Add(p); - OpenConnection(dbConnection); - try - { - using var reader = cmd.ExecuteReader(); - if (reader == null) - return new List(); - var list = new List(); - while (reader.NextResult()) - while (reader.Read()) - { - list.Add(parse.Invoke(reader)); - } - return list; - } - catch (Exception ex) - { - MasaTscCliclhouseExtensitions.Logger?.LogError(ex, "query sql error:{RawSql}, paramters:{Parameters}", sql, parameters); - throw; - } - } - - public static MappingResponseDto ConvertToMapping(IDataReader reader) - { - return new MappingResponseDto - { - Name = reader[0].ToString()!, - Type = "string" - }; - } - - public static TraceResponseDto ConvertTraceDto(IDataReader reader) - { - var startTime = Convert.ToDateTime(reader[TIMSTAMP_KEY]); - long ns = Convert.ToInt64(reader["Duration"]); - string resource = reader["Resources"].ToString()!, spans = reader["Spans"].ToString()!; - var result = new TraceResponseDto - { - TraceId = reader["TraceId"].ToString()!, - EndTimestamp = startTime.AddMilliseconds(ns / 1e6), - Kind = reader["SpanKind"].ToString()!, - Name = reader["SpanName"].ToString()!, - ParentSpanId = reader["ParentSpanId"].ToString()!, - SpanId = reader["SpanId"].ToString()!, - Timestamp = startTime - }; - if (!string.IsNullOrEmpty(resource)) - result.Resource = JsonSerializer.Deserialize>(resource)!; - if (!string.IsNullOrEmpty(spans)) - result.Attributes = JsonSerializer.Deserialize>(spans)!; - return result; - } - - public static LogResponseDto ConvertLogDto(IDataReader reader) - { - string resource = reader["Resources"].ToString()!, logs = reader["Logs"].ToString()!; - var result = new LogResponseDto - { - TraceId = reader["TraceId"].ToString()!, - Body = reader["Body"].ToString()!, - SeverityNumber = Convert.ToInt32(reader["SeverityNumber"]), - SeverityText = reader["SeverityText"].ToString()!, - TraceFlags = Convert.ToInt32(reader["TraceFlags"]), - SpanId = reader["SpanId"].ToString()!, - Timestamp = Convert.ToDateTime(reader[TIMSTAMP_KEY]), - }; - if (!string.IsNullOrEmpty(resource)) - result.Resource = JsonSerializer.Deserialize>(resource)!; - if (!string.IsNullOrEmpty(logs)) - result.Attributes = JsonSerializer.Deserialize>(logs)!; - return result; - } - - public static object AggregationQuery(this IDbConnection dbConnection, SimpleAggregateRequestDto requestDto, bool isLog = true) - { - var sql = new StringBuilder("select "); - var append = new StringBuilder(); - var appendWhere = new StringBuilder(); - var name = GetName(requestDto.Name, isLog); - AppendAggtype(requestDto, sql, append, name, out var isScalar); - sql.AppendFormat(" from {0} ", isLog ? MasaStackClickhouseConnection.LogTable : MasaStackClickhouseConnection.TraceTable); - var (where, @paremeters, _) = AppendWhere(requestDto, !isLog); - sql.Append($" where {appendWhere} {where}"); - sql.Append(append); - var paramArray = @paremeters?.ToArray()!; - - if (isScalar) - { - return dbConnection.ExecuteScalar(sql.ToString(), paramArray)!; - } - else - { - return AggTerm(dbConnection, sql.ToString(), paramArray, requestDto.Type, requestDto.AllValue); - } - } - - private static object AggTerm(IDbConnection dbConnection, string sql, IDataParameter[] paramArray, AggregateTypes aggregateTypes, bool isAllValue) - { - var result = dbConnection.Query(sql, paramArray, reader => - { - if (aggregateTypes == AggregateTypes.GroupBy) - { - if (isAllValue) - return KeyValuePair.Create(reader[0].ToString(), Convert.ToInt64(reader[1])); - else - return reader[0]; - } - else - { - var time = Convert.ToDateTime(reader[0]); - var timestamp = new DateTimeOffset(time).ToUnixTimeMilliseconds(); - return KeyValuePair.Create(timestamp, Convert.ToInt64(reader[1])); - } - }); - if (aggregateTypes == AggregateTypes.GroupBy) - { - if (isAllValue) - return result.Select(item => (KeyValuePair)item).ToList(); - else - return result.Select(item => item.ToString()).ToList(); - } - return result; - } - - private static void AppendAggtype(SimpleAggregateRequestDto requestDto, StringBuilder sql, StringBuilder append, string name, out bool isScalar) - { - isScalar = false; - switch (requestDto.Type) - { - case AggregateTypes.Avg: - sql.Append($"AVG({name}) as a"); - isScalar = true; - break; - case AggregateTypes.Count: - sql.Append($"Count({name}) as a"); - isScalar = true; - break; - case AggregateTypes.DistinctCount: - sql.Append($"Count(DISTINCT {name}) as a"); - isScalar = true; - break; - case AggregateTypes.Sum: - sql.Append($"SUM({name}) as a"); - isScalar = true; - break; - case AggregateTypes.GroupBy: - sql.Append($"{name} as a,Count({name}) as b"); - append.Append($" and a<>'' Group By a order by b desc"); - break; - case AggregateTypes.DateHistogram: - sql.Append($"toStartOfInterval({name}, INTERVAL {ConvertInterval(requestDto.Interval)} minute ) as `time`,count() as `count`"); - append.Append($" Group by `time` order by `time`"); - break; - } - } - - private static string GetName(string name, bool isLog) - { - if (name.Equals("@timestamp", StringComparison.CurrentCultureIgnoreCase)) - return TIMSTAMP_KEY; - - if (!isLog && name.Equals("duration", StringComparison.CurrentCultureIgnoreCase)) - return "Duration"; - - if (!isLog && name.Equals("kind", StringComparison.InvariantCultureIgnoreCase)) - return "SpanKind"; - - if (name.StartsWith(RESOURCE_KEY, StringComparison.CurrentCultureIgnoreCase)) - return GetResourceName(name); - - if (name.StartsWith(ATTRIBUTE_KEY, StringComparison.CurrentCultureIgnoreCase)) - return GetAttributeName(name, isLog); - - return name; - } - - private static string GetResourceName(string name) - { - var field = name[(RESOURCE_KEY.Length)..]; - if (field.Equals("service.name", StringComparison.CurrentCultureIgnoreCase)) - return "ServiceName"; - - if (field.Equals("service.namespace", StringComparison.CurrentCultureIgnoreCase) || field.Equals("service.instance.id", StringComparison.CurrentCultureIgnoreCase)) - return $"{RESOURCE_KEY}{field}"; - - return $"ResourceAttributesValues[indexOf(ResourceAttributesKeys,'{field}')]"; - } - - private static string GetAttributeName(string name, bool isLog) - { - var pre = isLog ? "Log" : "Span"; - var field = name[(ATTRIBUTE_KEY.Length)..]; - if (isLog && (field.Equals("exception.message", StringComparison.CurrentCultureIgnoreCase))) - return $"{ATTRIBUTE_KEY}{field}"; - - if (!isLog && (field.Equals("http.status_code", StringComparison.CurrentCultureIgnoreCase) - || field.Equals("http.request_content_body", StringComparison.CurrentCultureIgnoreCase) - || field.Equals("http.response_content_body", StringComparison.CurrentCultureIgnoreCase) - || field.Equals("exception.message", StringComparison.CurrentCultureIgnoreCase) - || field.Equals("http.target", StringComparison.CurrentCultureIgnoreCase)) - ) - return $"{ATTRIBUTE_KEY}{field}"; - - return $"{pre}AttributesValues[indexOf({pre}AttributesKeys,'{field}')]"; - } - - public static int ConvertInterval(string s) - { - var unit = Regex.Replace(s, @"\d+", "", RegexOptions.IgnoreCase, TimeSpan.FromSeconds(5)); - int t = 1; - switch (unit) - { - case "s": - t = 1; - break; - case "m": - t = 60; - break; - case "h": - t = 3600; - break; - case "d": - t = 3600 * 24; - break; - case "w": - t = 3600 * 24 * 7; - break; - case "month": - t = 3600 * 24 * 30; - break; - } - var num = Convert.ToInt64(s.Replace(unit, "")); - num *= t; - if (num - 60 < 0) - return 1; - return (int)(num / 60); - } - - public static string GetMaxDelayTraceId(this IDbConnection dbConnection, BaseRequestDto requestDto) - { - var (where, parameters, _) = AppendWhere(requestDto); - var text = $"select * from( TraceId from {MasaStackClickhouseConnection.TraceTable} where {where} order by Duration desc) as t limit 1"; - return dbConnection.ExecuteScalar(text, parameters?.ToArray())?.ToString()!; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Extensions/MasaTscCliclhouseExtensitions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Extensions/MasaTscCliclhouseExtensitions.cs deleted file mode 100644 index 9c7f28cdc..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Extensions/MasaTscCliclhouseExtensitions.cs +++ /dev/null @@ -1,274 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Microsoft.Extensions.DependencyInjection; - -public static class MasaTscCliclhouseExtensitions -{ - internal static ILogger? Logger { get; private set; } - - public static IServiceCollection AddMASAStackClickhouse(this IServiceCollection services, string connectionStr, string logTable, string traceTable, string? logSourceTable = null, string? traceSourceTable = null, Action? configer = null) - { - services.AddScoped(services => new MasaStackClickhouseConnection(connectionStr, logTable, traceTable, logSourceTable, traceSourceTable)) - .AddScoped() - .AddScoped(); - Init(services); - configer?.Invoke(services.BuildServiceProvider().GetRequiredService()!); - return services; - } - - private static void Init(IServiceCollection services, bool createTable = true) - { - var serviceProvider = services.BuildServiceProvider(); - var logfactory = serviceProvider.GetService(); - Logger = logfactory?.CreateLogger("Masa.Contrib.StackSdks.Tsc.Clickhouse"); - var connection = serviceProvider.GetRequiredService(); - if (createTable) - InitTable(connection); - InitMappingTable(connection); - - var timezoneStr = GetTimezone(connection); - MasaStackClickhouseConnection.TimeZone = TZConvert.GetTimeZoneInfo(timezoneStr); - } - - private static void InitTable(MasaStackClickhouseConnection connection) - { - var database = connection.ConnectionSettings?.Database; - database ??= new ClickHouseConnectionSettings(connection.ConnectionString).Database; - - if (Convert.ToInt32(connection.ExecuteScalar($"select count() from system.tables where database ='{database}' and name in ['{MasaStackClickhouseConnection.TraceTable.Split('.')[1]}','{MasaStackClickhouseConnection.LogTable.Split('.')[1]}']")) > 0) - return; - - var createTableSqls = new string[]{ - - @$"CREATE TABLE {MasaStackClickhouseConnection.LogTable} -( - `Timestamp` DateTime64(9) CODEC(Delta(8), ZSTD(1)), - `TraceId` String CODEC(ZSTD(1)), - `SpanId` String CODEC(ZSTD(1)), - `TraceFlags` UInt32 CODEC(ZSTD(1)), - `SeverityText` LowCardinality(String) CODEC(ZSTD(1)), - `SeverityNumber` Int32 CODEC(ZSTD(1)), - `ServiceName` LowCardinality(String) CODEC(ZSTD(1)), - `Body` String CODEC(ZSTD(1)), - `ResourceSchemaUrl` String CODEC(ZSTD(1)), - `Resources` String CODEC(ZSTD(1)), - `ScopeSchemaUrl` String CODEC(ZSTD(1)), - `ScopeName` String CODEC(ZSTD(1)), - `ScopeVersion` String CODEC(ZSTD(1)), - `Scopes` String CODEC(ZSTD(1)), - `Logs` String CODEC(ZSTD(1)), - - `Resource.service.namespace` String CODEC(ZSTD(1)), - `Resource.service.version` String CODEC(ZSTD(1)), - `Resource.service.instance.id` String CODEC(ZSTD(1)), - - `Attributes.TaskId` String CODEC(ZSTD(1)), - `Attributes.exception.message` String CODEC(ZSTD(1)), - - ResourceAttributesKeys Array(String) CODEC(ZSTD(1)), - ResourceAttributesValues Array(String) CODEC(ZSTD(1)), - LogAttributesKeys Array(String) CODEC(ZSTD(1)), - LogAttributesValues Array(String) CODEC(ZSTD(1)), - - INDEX idx_log_id TraceId TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_log_servicename ServiceName TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_log_serviceinstanceid `Resource.service.instance.id` TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_log_severitytext SeverityText TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_log_taskid `Attributes.TaskId` TYPE bloom_filter(0.001) GRANULARITY 1, - - INDEX idx_string_body Body TYPE tokenbf_v1(30720, 2, 0) GRANULARITY 1, - INDEX idx_string_exceptionmessage Attributes.exception.message TYPE tokenbf_v1(30720, 2, 0) GRANULARITY 1 -) -ENGINE = MergeTree -PARTITION BY toDate(Timestamp) -ORDER BY ( - Timestamp, - `Resource.service.namespace`, - ServiceName - ) -TTL toDateTime(Timestamp) + toIntervalDay(30) -SETTINGS index_granularity = 8192, - ttl_only_drop_parts = 1; -", -@$"CREATE TABLE {MasaStackClickhouseConnection.TraceTable} -( - `Timestamp` DateTime64(9) CODEC(Delta(8), ZSTD(1)), - `TraceId` String CODEC(ZSTD(1)), - `SpanId` String CODEC(ZSTD(1)), - `ParentSpanId` String CODEC(ZSTD(1)), - `TraceState` String CODEC(ZSTD(1)), - `SpanName` LowCardinality(String) CODEC(ZSTD(1)), - `SpanKind` LowCardinality(String) CODEC(ZSTD(1)), - `ServiceName` LowCardinality(String) CODEC(ZSTD(1)), - `Resources` String CODEC(ZSTD(1)), - `ScopeName` String CODEC(ZSTD(1)), - `ScopeVersion` String CODEC(ZSTD(1)), - `Spans` String CODEC(ZSTD(1)), - `Duration` Int64 CODEC(ZSTD(1)), - `StatusCode` LowCardinality(String) CODEC(ZSTD(1)), - `StatusMessage` String CODEC(ZSTD(1)), - `Events.Timestamp` Array(DateTime64(9)) CODEC(ZSTD(1)), - `Events.Name` Array(LowCardinality(String)) CODEC(ZSTD(1)), - `Events.Attributes` Array(Map(LowCardinality(String), String)) CODEC(ZSTD(1)), - `Links.TraceId` Array(String) CODEC(ZSTD(1)), - `Links.SpanId` Array(String) CODEC(ZSTD(1)), - `Links.TraceState` Array(String) CODEC(ZSTD(1)), - `Links.Attributes` Array(Map(LowCardinality(String), String)) CODEC(ZSTD(1)), - - `Resource.service.namespace` String CODEC(ZSTD(1)), - `Resource.service.version` String CODEC(ZSTD(1)), - `Resource.service.instance.id` String CODEC(ZSTD(1)), - - `Attributes.http.status_code` String CODEC(ZSTD(1)), - `Attributes.http.response_content_body` String CODEC(ZSTD(1)), - `Attributes.http.request_content_body` String CODEC(ZSTD(1)), - `Attributes.http.target` String CODEC(ZSTD(1)), - `Attributes.exception.message` String CODEC(ZSTD(1)), - - `ResourceAttributesKeys` Array(String) CODEC(ZSTD(1)), - `ResourceAttributesValues` Array(String) CODEC(ZSTD(1)), - `SpanAttributesKeys` Array(String) CODEC(ZSTD(1)), - `SpanAttributesValues` Array(String) CODEC(ZSTD(1)), - - INDEX idx_trace_id TraceId TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_trace_servicename ServiceName TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_trace_servicenamespace Resource.service.namespace TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_trace_serviceinstanceid Resource.service.instance.id TYPE bloom_filter(0.001) GRANULARITY 1, - INDEX idx_trace_statuscode Attributes.http.status_code TYPE bloom_filter(0.001) GRANULARITY 1, - - INDEX idx_string_requestbody Attributes.http.request_content_body TYPE tokenbf_v1(30720, 2, 0) GRANULARITY 1, - INDEX idx_string_responsebody Attributes.http.response_content_body TYPE tokenbf_v1(30720, 2, 0) GRANULARITY 1, - INDEX idx_string_exceptionmessage Attributes.exception.message TYPE tokenbf_v1(30720, 2, 0) GRANULARITY 1 -) -ENGINE = MergeTree -PARTITION BY toDate(Timestamp) -ORDER BY ( - Timestamp, - Resource.service.namespace, - ServiceName - ) -TTL toDateTime(Timestamp) + toIntervalDay(30) -SETTINGS index_granularity = 8192, - ttl_only_drop_parts = 1; -", -$@"CREATE MATERIALIZED VIEW {MasaStackClickhouseConnection.LogTable}_v TO {MasaStackClickhouseConnection.LogTable} -AS -SELECT -Timestamp,TraceId,SpanId,TraceFlags,SeverityText,SeverityNumber,ServiceName,Body,ResourceSchemaUrl,toJSONString(ResourceAttributes) as Resources, -ScopeSchemaUrl,ScopeName,ScopeVersion,toJSONString(ScopeAttributes) as Scopes,toJSONString(LogAttributes) as Logs, -ResourceAttributes['service.namespace'] as `Resource.service.namespace`,ResourceAttributes['service.version'] as `Resource.service.version`, -ResourceAttributes['service.instance.id'] as `Resource.service.instance.id`, -LogAttributes['TaskId'] as `Attributes.TaskId`,LogAttributes['exception.message'] as `Attributes.exception.message`, -mapKeys(ResourceAttributes) as ResourceAttributesKeys,mapValues(ResourceAttributes) as ResourceAttributesValues, -mapKeys(LogAttributes) as LogAttributesKeys,mapValues(LogAttributes) as LogAttributesValues -FROM {MasaStackClickhouseConnection.LogSourceTable} -", -$@"CREATE MATERIALIZED VIEW {MasaStackClickhouseConnection.TraceTable}_v TO {MasaStackClickhouseConnection.TraceTable} -AS -SELECT - Timestamp,TraceId,SpanId,ParentSpanId,TraceState,SpanName,SpanKind,ServiceName,toJSONString(ResourceAttributes) AS Resources, - ScopeName,ScopeVersion,toJSONString(SpanAttributes) AS Spans, - Duration,StatusCode,StatusMessage,Events.Timestamp,Events.Name,Events.Attributes, - Links.TraceId,Links.SpanId,Links.TraceState,Links.Attributes, - - ResourceAttributes['service.namespace'] as `Resource.service.namespace`,ResourceAttributes['service.version'] as `Resource.service.version`, - ResourceAttributes['service.instance.id'] as `Resource.service.instance.id`, - - SpanAttributes['http.status_code'] as `Attributes.http.status_code`, - SpanAttributes['http.response_content_body'] as `Attributes.http.response_content_body`, - SpanAttributes['http.request_content_body'] as `Attributes.http.request_content_body`, - SpanAttributes['http.target'] as `Attributes.http.target`, - SpanAttributes['exception.message'] as `Attributes.exception.message`, - - mapKeys(ResourceAttributes) AS ResourceAttributesKeys, - mapValues(ResourceAttributes) AS ResourceAttributesValues, - mapKeys(SpanAttributes) AS SpanAttributesKeys, - mapValues(SpanAttributes) AS SpanAttributesValues -FROM {MasaStackClickhouseConnection.TraceSourceTable} -" }; - - foreach (var sql in createTableSqls) - { - ExecuteSql(connection, sql); - } - } - - private static void InitMappingTable(MasaStackClickhouseConnection connection) - { - var database = connection.ConnectionSettings?.Database; - database ??= new ClickHouseConnectionSettings(connection.ConnectionString).Database; - - var list = MasaStackClickhouseConnection.MappingTable.Split('.'); - var mappingTable = list[list.Length - 1]; - if (Convert.ToInt32(connection.ExecuteScalar($"select count() from system.tables where database ='{database}' and name in ['{mappingTable}']")) > 0) - return; - - var initSqls = new string[]{ -$@" -CREATE TABLE {database}.otel_mapping -( - `Name` Array(String), - `Type` String -) -ENGINE = MergeTree -ORDER BY Name -SETTINGS index_granularity = 8192;", -@$"CREATE MATERIALIZED VIEW {database}.v_otel_traces_attribute_mapping to {MasaStackClickhouseConnection.MappingTable} -as -select DISTINCT arraySort(mapKeys(SpanAttributes)) as Name, 'trace_attributes' as Type -from {MasaStackClickhouseConnection.TraceSourceTable}", -$@"CREATE MATERIALIZED VIEW {database}.v_otel_traces_resource_mapping to {MasaStackClickhouseConnection.MappingTable} -as -select DISTINCT arraySort(mapKeys(ResourceAttributes)) as Name, 'trace_resource' as Type -from {MasaStackClickhouseConnection.TraceSourceTable}", -$@"CREATE MATERIALIZED VIEW {database}.v_otel_logs_attribute_mapping to {MasaStackClickhouseConnection.MappingTable} -as -select DISTINCT arraySort(mapKeys(LogAttributes)) as Name, 'log_attributes' as Type -from {MasaStackClickhouseConnection.LogSourceTable}", -$@"CREATE MATERIALIZED VIEW {database}.v_otel_logs_resource_mapping to {MasaStackClickhouseConnection.MappingTable} -as -select DISTINCT arraySort(mapKeys(ResourceAttributes)) as Name, 'log_resource' as Type -from {MasaStackClickhouseConnection.LogSourceTable}", -$@"insert into {MasaStackClickhouseConnection.MappingTable} -values (['Timestamp','TraceId','SpanId','TraceFlag','SeverityText','SeverityNumber','Body'],'log_basic'), -(['Timestamp','TraceId','SpanId','ParentSpanId','TraceState','SpanKind','Duration'],'trace_basic'); -" }; - foreach (var sql in initSqls) - connection.ExecuteSql(sql); - } - - internal static void ExecuteSql(this IDbConnection connection, string sql) - { - using var cmd = connection.CreateCommand(); - if (connection.State != ConnectionState.Open) - connection.Open(); - cmd.CommandText = sql; - try - { - cmd.ExecuteNonQuery(); - } - catch (Exception ex) - { - Logger?.LogError(ex, "ExecuteSql {RawSql} error", sql); - } - } - - private static string GetTimezone(MasaStackClickhouseConnection connection) - { - using var cmd = connection.CreateCommand(); - if (connection.State != ConnectionState.Open) - connection.Open(); - var sql = "select timezone()"; - cmd.CommandText = sql; - try - { - return cmd.ExecuteScalar()?.ToString()!; - } - catch (Exception ex) - { - Logger?.LogError(ex, "ExecuteSql {RawSql} error", sql); - throw; - } - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/LogService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/LogService.cs deleted file mode 100644 index 672a45da2..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/LogService.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Clickhouse; - -internal class LogService : ILogService -{ - private readonly IDbConnection _dbConnection; - public LogService(MasaStackClickhouseConnection connection) - { - _dbConnection = connection; - } - - public Task AggregateAsync(SimpleAggregateRequestDto query) - { - return Task.FromResult(_dbConnection.AggregationQuery(query)); - } - - public Task> ListAsync(BaseRequestDto query) - { - return Task.FromResult(_dbConnection.QueryLog(query)); - } - - public Task> GetMappingAsync() - { - return Task.FromResult(_dbConnection.GetMapping(true).AsEnumerable()); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Masa.Contrib.StackSdks.Tsc.Clickhouse.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Masa.Contrib.StackSdks.Tsc.Clickhouse.csproj deleted file mode 100644 index 2ca7d8fef..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Masa.Contrib.StackSdks.Tsc.Clickhouse.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - enable - enable - 1.0-local - - - - - - - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Model/MASAStackClickhouseConnection.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Model/MASAStackClickhouseConnection.cs deleted file mode 100644 index 939d59a75..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Model/MASAStackClickhouseConnection.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. -[assembly: InternalsVisibleTo("Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse")] -[assembly: InternalsVisibleTo("Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests")] -[assembly: InternalsVisibleTo("Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests")] -namespace Masa.Contrib.StackSdks.Tsc.Clickhouse; - -internal sealed class MasaStackClickhouseConnection : ClickHouseConnection -{ - public static string LogSourceTable { get; private set; } - - public static string TraceSourceTable { get; private set; } - - public static string LogTable { get; private set; } - - public static string TraceTable { get; private set; } - - public static string MappingTable { get; private set; } - - public static TimeZoneInfo TimeZone { get; set; } - - public static DateTime ToTimeZone(DateTime time) - { - var newTime = time.Kind == DateTimeKind.Unspecified ? time : DateTime.SpecifyKind(time, DateTimeKind.Unspecified); - return new DateTimeOffset(newTime + TimeZone.BaseUtcOffset, TimeZone.BaseUtcOffset).DateTime; - } - - public object LockObj { get; init; } = new(); - - public MasaStackClickhouseConnection(string connection, string logTable, string traceTable, string? logSourceTable = null, string? traceSourceTable = null) - { - ArgumentNullException.ThrowIfNull(connection); - ArgumentNullException.ThrowIfNull(logTable); - ArgumentNullException.ThrowIfNull(traceTable); - ConnectionString = connection; - logSourceTable ??= "otel_logs"; - traceSourceTable ??= "otel_traces"; - - if (!string.IsNullOrEmpty(ConnectionSettings.Database)) - { - LogTable = $"{ConnectionSettings.Database}.{logTable}"; - TraceTable = $"{ConnectionSettings.Database}.{traceTable}"; - TraceSourceTable = $"{ConnectionSettings.Database}.{traceSourceTable}"; - LogSourceTable = $"{ConnectionSettings.Database}.{logSourceTable}"; - MappingTable = $"{ConnectionSettings.Database}.otel_mapping"; - } - else - { - LogTable = logTable; - TraceTable = traceTable; - TraceSourceTable = traceSourceTable; - LogSourceTable = logSourceTable; - MappingTable = "otel_mapping"; - } - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Properties/PublishProfiles/FolderProfile.pubxml b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Properties/PublishProfiles/FolderProfile.pubxml deleted file mode 100644 index 154e03532..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/Properties/PublishProfiles/FolderProfile.pubxml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - Release - Any CPU - bin\Release\net6.0\publish\ - FileSystem - <_TargetId>Folder - - \ No newline at end of file diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/TraceService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/TraceService.cs deleted file mode 100644 index 8742c5d2e..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/TraceService.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Clickhouse; - -internal class TraceService : ITraceService -{ - private readonly IDbConnection _dbConnection; - - public TraceService(MasaStackClickhouseConnection connection) - { - _dbConnection = connection; - } - - public Task AggregateAsync(SimpleAggregateRequestDto query) - { - return Task.FromResult(_dbConnection.AggregationQuery(query, false)); - } - - public Task> GetAsync(string traceId) - { - return Task.FromResult(_dbConnection.GetTraceByTraceId(traceId).AsEnumerable()); - } - - public Task GetMaxDelayTraceIdAsync(BaseRequestDto query) - { - return Task.FromResult(_dbConnection.GetMaxDelayTraceId(query)); - } - - public Task> ListAsync(BaseRequestDto query) - { - return Task.FromResult(_dbConnection.QueryTrace(query)); - } - - public Task> ScrollAsync(BaseRequestDto query) - { - return Task.FromResult(_dbConnection.QueryTrace(query)); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/_Imports.cs deleted file mode 100644 index 51f1b7ee3..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Clickhouse/_Imports.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using ClickHouse.Ado; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Log; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Model; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Model.Aggregate; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Service; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Trace; -global using Masa.Contrib.StackSdks.Tsc.Clickhouse; -global using Masa.Utils.Models; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.Extensions.Logging; -global using System.Collections; -global using System.Data; -global using System.Data.Common; -global using System.Runtime.CompilerServices; -global using System.Text; -global using System.Text.Json; -global using System.Text.RegularExpressions; -global using TimeZoneConverter; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Constants/ElasticConstant.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Constants/ElasticConstant.cs deleted file mode 100644 index 4d8bf89bf..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Constants/ElasticConstant.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Constants; - -public static class ElasticConstant -{ - internal const string LOG_CALLER_CLIENT_NAME = "masa.contrib.stacksdks.tsc.log.elasticseach.log"; - internal const string TRACE_CALLER_CLIENT_NAME = "masa.contrib.stacksdks.tsc.log.elasticseach.trace"; - internal const string DEFAULT_CALLER_CLIENT_NAME = "masa.contrib.stacksdks.tsc.log.elasticseach.all"; - - private const string TIMESTAMP = "@timestamp"; - public static string TraceId => "TraceId"; - public static string ParentId => "ParentSpanId"; - public static string SpanId => "SpanId"; - public static string ServiceName => "Resource.service.name"; - public static string ServiceInstance => "Resource.service.instance.id"; - public static string NameSpace => "Resource.service.namespace"; - public static string Endpoint => "Attributes.http.url"; - - internal static int MaxRecordCount { get; private set; } = 10000; - - public static LogTraceSetting Log { get; private set; } - - public static LogTraceSetting Trace { get; private set; } - - internal static void InitLog(string indexName, bool isIndependent = false) - { - if (string.IsNullOrEmpty(indexName)) - return; - Log = new LogTraceSetting(indexName, isIndependent, TIMESTAMP); - } - - internal static void InitTrace(string indexName, bool isIndependent = false) - { - if (string.IsNullOrEmpty(indexName)) - return; - Trace = new LogTraceSetting(indexName, isIndependent, TIMESTAMP); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Constants/LogTraceSetting.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Constants/LogTraceSetting.cs deleted file mode 100644 index 076ab002f..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Constants/LogTraceSetting.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Constants; - -public class LogTraceSetting -{ - internal string IndexName { get; private set; } - - public string Timestamp { get; private set; } - - internal bool IsIndependent { get; private set; } - - internal Lazy Mappings { get; set; } - - internal LogTraceSetting(string indexName, bool isIndependent = false, string timestamp = "@timestamp") - { - if (!string.IsNullOrEmpty(IndexName) || string.IsNullOrEmpty(indexName)) - return; - - IndexName = indexName; - Timestamp = timestamp; - IsIndependent = isIndependent; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Constants/MappingConstant.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Constants/MappingConstant.cs deleted file mode 100644 index 9e804a8c6..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Constants/MappingConstant.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Constants; - -internal static class MappingConstant -{ - public const string PROPERTY = "properties"; - public const string TYPE = "type"; - public const string FIELD = "fields"; - /// - /// when field is keyword, the maximum field value length, fields beyond this length will not be indexed, but will be stored - /// - public const string MAXLENGTH = "ignore_above"; - public const string KEYWORD = "keyword"; -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Converters/LogResponseDtoConverter.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Converters/LogResponseDtoConverter.cs deleted file mode 100644 index e9ab73e8d..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Converters/LogResponseDtoConverter.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. -[assembly: InternalsVisibleTo("Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests")] -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Converters; - -internal class LogResponseDtoConverter : JsonConverter -{ - public override LogResponseDto? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - if (JsonDocument.TryParseValue(ref reader, out var doc)) - { - var jsonObject = doc.RootElement; - var rootText = jsonObject.GetRawText(); - var result= JsonSerializer.Deserialize(rootText); - if (result == null) - return default; - if (result.Timestamp == DateTime.MinValue || result.Timestamp == DateTime.MaxValue) - return default; - if (result.Body == null) - return default; - - result.Attributes = jsonObject.ConvertToKeyValuePairs()?.ToDictionary(kv => kv.Key, kv => kv.Value)?.GroupByKeyPrefix("Attributes.")!; - result.Resource = jsonObject.ConvertToKeyValuePairs()?.ToDictionary(kv => kv.Key, kv => kv.Value)?.GroupByKeyPrefix("Resource.")!; - - return result; - } - - throw new NotImplementedException(); - } - - public override void Write(Utf8JsonWriter writer, LogResponseDto value, JsonSerializerOptions options) - { - JsonSerializer.Serialize(writer, value, options); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Converters/TraceResponseDtoConverter.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Converters/TraceResponseDtoConverter.cs deleted file mode 100644 index e1d6bd87b..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Converters/TraceResponseDtoConverter.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. -[assembly: InternalsVisibleTo("Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests")] -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Converters; - -internal class TraceResponseDtoConverter : JsonConverter -{ - public override TraceResponseDto? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - if (JsonDocument.TryParseValue(ref reader, out var doc)) - { - var jsonObject = doc.RootElement; - var rootText = jsonObject.GetRawText(); - var result = JsonSerializer.Deserialize(rootText); - if (result == null) - return default; - if (result.Timestamp == DateTime.MinValue || result.Timestamp == DateTime.MaxValue) - return default; - if (string.IsNullOrEmpty(result.TraceId)) - return default; - - result.Attributes = jsonObject.ConvertToKeyValuePairs().ToDictionary(kv => kv.Key, kv => kv.Value).GroupByKeyPrefix("Attributes."); - result.Resource = jsonObject.ConvertToKeyValuePairs().ToDictionary(kv => kv.Key, kv => kv.Value).GroupByKeyPrefix("Resource."); - - return result; - } - - throw new NotImplementedException(); - } - - public override void Write(Utf8JsonWriter writer, TraceResponseDto value, JsonSerializerOptions options) - { - JsonSerializer.Serialize(writer, value, options); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Extenistions/IElasticClientExtenstion.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Extenistions/IElasticClientExtenstion.cs deleted file mode 100644 index 66f112672..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Extenistions/IElasticClientExtenstion.cs +++ /dev/null @@ -1,504 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Nest; - -internal static class IElasticClientExtenstion -{ - public static async Task SearchAsync(this IElasticClient client, - string indexName, - TQuery query, - Func, SearchDescriptor> searchDescriptorFunc, - Action, TQuery> resultFunc) where TResult : class where TQuery : class - { - try - { - if (resultFunc is null) return; - ISearchResponse searchResponse; - if (query is ElasticsearchScrollRequestDto scrollQuery) - searchResponse = string.IsNullOrEmpty(scrollQuery.ScrollId) ? - await client.SearchAsync(s => searchDescriptorFunc(s.Index(indexName)).Scroll(scrollQuery.Scroll)) : - await client.ScrollAsync(scrollQuery.Scroll, scrollQuery.ScrollId); - else - searchResponse = await client.SearchAsync(s => searchDescriptorFunc(s.Index(indexName))); - - searchResponse.FriendlyElasticException(); - if (searchResponse.IsValid) - resultFunc.Invoke(searchResponse, query); - } - catch (Exception ex) - { - throw new UserFriendlyException($"SearchAsync execute error", ex); - } - } - - #region mapping - - public static async Task> GetMappingAsync(this ICaller caller, string indexName, CancellationToken token = default) - { - var path = $"/{indexName}/_mapping"; - var result = await caller.GetAsync(path, token); - var json = (JsonElement)result!; - foreach (var item in json.EnumerateObject()) - { - JsonElement mapping; - if (item.Value.TryGetProperty("mappings", out mapping)) - { - var mappings = GetRepProperties(mapping, default!)!; - if (mappings != null && mappings.Any()) - return mappings; - } - } - - throw new UserFriendlyException($"can't find mapping for index: {indexName}"); - } - - private static IEnumerable? GetRepProperties(JsonElement node, string? parentName = default) - { - if (node.ValueKind != JsonValueKind.Object) - return default; - - var properties = GetProperties(node); - if (properties == null || properties.Value.ValueKind != JsonValueKind.Object) - return default; - - var result = new List(); - var obj = properties.Value.EnumerateObject(); - foreach (var item in obj) - { - var type = GetType(item.Value); - var name = $"{parentName}{item.Name}"; - if (string.IsNullOrEmpty(type)) - { - var children = GetRepProperties(item.Value, $"{name}."); - if (children != null && children.Any()) - result.AddRange(children); - } - else - { - var model = new ElasticseacherMappingResponseDto - { - Name = name, - Type = type - }; - SetKeyword(item.Value, model); - result.Add(model); - } - } - return result; - } - - private static JsonElement? GetProperties(JsonElement value) - { - if (value.TryGetProperty(MappingConstant.PROPERTY, out JsonElement result)) - return result; - return null; - } - - private static string? GetType(JsonElement value) - { - if (value.TryGetProperty(MappingConstant.TYPE, out JsonElement element)) - return element.ToString(); - return default; - } - - private static void SetKeyword(JsonElement value, ElasticseacherMappingResponseDto model) - { - if (value.TryGetProperty(MappingConstant.FIELD, out JsonElement fields) && - fields.TryGetProperty(MappingConstant.KEYWORD, out JsonElement element)) - { - if (element.TryGetProperty(MappingConstant.TYPE, out JsonElement type) && type.ToString() == MappingConstant.KEYWORD) - model.IsKeyword = true; - if (element.TryGetProperty(MappingConstant.MAXLENGTH, out JsonElement maxLength)) - model.MaxLenth = maxLength.GetInt32(); - } - } - - public static void FriendlyElasticException(this ISearchResponse response) where T : class - { - if (!response.IsValid) - throw new UserFriendlyException($"elastic query error: status: {response.ServerError?.Status}, message: {response.OriginalException?.Message ?? response.ServerError?.ToString()}, DebugInformation: {response.DebugInformation}"); - } - - #endregion - - #region log - - public static async Task> SearchLogAsync(this IElasticClient client, BaseRequestDto query) - { - PaginatedListBase result = default!; - await client.SearchAsync(ElasticConstant.Log.IndexName, query, - (SearchDescriptor searchDescriptor) => searchDescriptor.AddCondition(query, true) - .AddSort(query) - .AddPageSize(query, true), - (response, q) => result = SetLogResult(response)); - return result; - } - - public static async Task AggregateLogAsync(this IElasticClient client, SimpleAggregateRequestDto query) - { - object result = default!; - await client.SearchAsync(ElasticConstant.Log.IndexName, query, - (SearchDescriptor searchDescriptor) => searchDescriptor.AddCondition(query, true) - .AddSort(query) - .AddPageSize(query, false) - .AddAggregate(query, true), - (response, q) => result = SetAggregationResult(response, q)); - return result; - } - - #endregion - - #region trace - public static async Task> SearchTraceAsync(this IElasticClient client, BaseRequestDto query) - { - PaginatedListBase result = default!; - await client.SearchAsync(ElasticConstant.Trace.IndexName, query, - (SearchDescriptor searchDescriptor) => searchDescriptor.AddCondition(query, false) - .AddSort(query, false) - .AddPageSize(query, true), - (response, q) => - { - result = q is ElasticsearchScrollRequestDto ? SetTraceScrollResult(response) : SetTraceResult(response); - }); - return result; - } - - public static async Task AggregateTraceAsync(this IElasticClient client, SimpleAggregateRequestDto query) - { - object result = default!; - await client.SearchAsync(ElasticConstant.Trace.IndexName, query, - (SearchDescriptor searchDescriptor) => searchDescriptor.AddCondition(query, false) - .AddSort(query, false) - .AddPageSize(query, false) - .AddAggregate(query, false), - (response, q) => result = SetAggregationResult(response, q)); - return result; - } - - public static async Task GetMaxDelayTraceIdAsync(this IElasticClient client, BaseRequestDto query) - { - string traceId = default!; - await client.SearchAsync(ElasticConstant.Trace.IndexName, query, - (SearchDescriptor searchDescriptor) => searchDescriptor.AddCondition(query, false) - .Sort(sort => sort.Script(script => script.Order(SortOrder.Descending).Script(s => s.Source("doc['EndTimestamp'].value.toEpochSecond()-doc['@timestamp'].value.toEpochSecond()")).Type("number"))) - .Size(1), - (response, q) => - { - var result = SetTraceResult(response); - traceId = result.Result.FirstOrDefault()?.TraceId!; - }); - - return traceId; - } - #endregion - - #region set condition - - private static SearchDescriptor AddCondition(this SearchDescriptor searchDescriptor, TQuery query, bool isLog) where TQuery : BaseRequestDto where TResult : class - { - var list = new List, QueryContainer>>(); - string timestamp = isLog ? ElasticConstant.Log.Timestamp : ElasticConstant.Trace.Timestamp; - var mappings = isLog ? ElasticConstant.Log.Mappings.Value : ElasticConstant.Trace.Mappings.Value; - - if (!string.IsNullOrEmpty(query.RawQuery)) - { - list.Add(queryContainer => queryContainer.Raw(query.RawQuery)); - } - if (query.Start > DateTime.MinValue && query.End > DateTime.MinValue && query.Start < query.End) - { - list.Add(queryContainer => queryContainer.DateRange(dateRangeQuery => dateRangeQuery.GreaterThanOrEquals(query.Start).LessThanOrEquals(query.End).Field(timestamp))); - } - if (!string.IsNullOrEmpty(query.Keyword)) - { - list.Add(queryContainer => queryContainer.QueryString(queryString => queryString.Query(query.Keyword).DefaultOperator(Operator.And))); - } - - query.AppendConditions(); - var conditions = AddFilter(query); - if (conditions != null && conditions.Any()) - { - foreach (var item in conditions) - { - var mapping = mappings.FirstOrDefault(m => string.Equals(m.Name, item.Name, StringComparison.OrdinalIgnoreCase)); - list.Add(CompareCondition(mapping, item)); - } - } - - if (list.Any()) - { - return searchDescriptor.Query(container => container.Bool(boolQuery => boolQuery.Must(list))); - } - - return searchDescriptor; - } - - private static IEnumerable AddFilter(TQuery query) where TQuery : BaseRequestDto - { - var result = query.Conditions?.ToList() ?? new(); - if (!string.IsNullOrEmpty(query.Service)) - result.Add(new FieldConditionDto - { - Name = ElasticConstant.ServiceName, - Value = query.Service, - Type = ConditionTypes.Equal - }); - if (!string.IsNullOrEmpty(query.Instance)) - result.Add(new FieldConditionDto - { - Name = ElasticConstant.ServiceInstance, - Value = query.Instance, - Type = ConditionTypes.Equal - }); - if (!string.IsNullOrEmpty(query.Endpoint)) - result.Add(new FieldConditionDto - { - Name = ElasticConstant.Endpoint, - Value = $"*{query.Endpoint}*", - Type = ConditionTypes.Regex - }); - if (!string.IsNullOrEmpty(query.TraceId)) - result.Add(new FieldConditionDto - { - Name = ElasticConstant.TraceId, - Value = query.TraceId, - Type = ConditionTypes.Equal - }); - return result; - } - - private static Func, QueryContainer> CompareCondition(ElasticseacherMappingResponseDto? mapping, FieldConditionDto query) where TResult : class - { - CreateFieldKeyword(query.Name, mapping, out var fieldName, out var keyword); - var value = query.Value; - bool isDate = value is DateTime; - - switch (query.Type) - { - case ConditionTypes.Equal: - return (container) => container.Match(f => f.Field(keyword).Query(value?.ToString())); - case ConditionTypes.NotEqual: - return (container) => !container.Match(f => f.Field(keyword).Query(value?.ToString())); - case ConditionTypes.Great: - if (isDate) - return (container) => container.DateRange(f => f.Field(keyword).GreaterThan((DateTime)value)); - return (container) => container.Range(f => f.Field(keyword).GreaterThan(Convert.ToDouble(value))); - case ConditionTypes.Less: - if (isDate) - return (container) => container.DateRange(f => f.Field(keyword).LessThan((DateTime)value)); - return (container) => container.Range(f => f.Field(keyword).LessThan(Convert.ToDouble(value))); - case ConditionTypes.GreatEqual: - if (isDate) - return (container) => container.DateRange(f => f.Field(keyword).GreaterThanOrEquals((DateTime)value)); - return (container) => container.Range(f => f.Field(keyword).GreaterThanOrEquals(Convert.ToDouble(value))); - case ConditionTypes.LessEqual: - if (isDate) - return (container) => container.DateRange(f => f.Field(keyword).LessThanOrEquals((DateTime)value)); - return (container) => container.Range(f => f.Field(keyword).LessThanOrEquals(Convert.ToDouble(value))); - case ConditionTypes.In: - return (container) => container.Terms(f => f.Field(keyword).Terms((IEnumerable)value)); - case ConditionTypes.NotIn: - return (container) => !container.Terms(f => f.Field(keyword).Terms((IEnumerable)value)); - case ConditionTypes.Exists: - return (container) => container.Exists(f => f.Field(fieldName)); - case ConditionTypes.NotExists: - return (container) => !container.Exists(f => f.Field(fieldName)); - case ConditionTypes.Regex: - return (container) => container.Wildcard(f => f.Field(fieldName).Value(value?.ToString())); - case ConditionTypes.NotRegex: - return (container) => !container.Wildcard(f => f.Field(fieldName).Value(value?.ToString())); - } - return (container) => container; - } - - #endregion - - #region set page - - private static SearchDescriptor AddPageSize(this SearchDescriptor container, TQuery query, bool hasPage) where TResult : class where TQuery : BaseRequestDto - { - if (query.Page <= 0) - query.Page = 1; - if (query.PageSize <= 0) - query.PageSize = 20; - if (query is ElasticsearchScrollRequestDto || !hasPage) - return container.Size(query.PageSize); - - var start = (query.Page - 1) * query.PageSize; - if (ElasticConstant.MaxRecordCount - start - query.PageSize <= 0) - throw new UserFriendlyException($"elastic query data max count must be less {ElasticConstant.MaxRecordCount}, please input more condition to limit"); - return container.Size(query.PageSize).From(start); - - } - #endregion - - #region set sort - - private static SearchDescriptor AddSort(this SearchDescriptor searchDescriptor, TQuery query, bool isLog = true) where TQuery : BaseRequestDto where TResult : class - { - LogTraceSetting setting = isLog ? ElasticConstant.Log : ElasticConstant.Trace; - - if (query.Sort == null) - return searchDescriptor.Sort(sort => sort.Descending(setting.Timestamp)); - - var mapping = setting.Mappings.Value.FirstOrDefault(m => string.Equals(m.Name, query.Sort.Name, StringComparison.OrdinalIgnoreCase)); - CreateFieldKeyword(query.Sort.Name, mapping, out var field, out var keyword); - - Func, SortDescriptor> sortFunc; - if (query.Sort.IsDesc) - sortFunc = (sort) => sort.Descending(keyword); - else - sortFunc = (sort) => sort.Ascending(keyword); - - return searchDescriptor.Sort(sort => sortFunc(sort)); - } - - #endregion - - #region set result - private static PaginatedListBase SetLogResult(ISearchResponse response) - { - var options = new JsonSerializerOptions(); - options.Converters.Add(new LogResponseDtoConverter()); - var text = JsonSerializer.Serialize(response.Documents); - - return new PaginatedListBase { Total = response.Total, Result = JsonSerializer.Deserialize>(text, options)! }; - } - - private static PaginatedListBase SetTraceResult(ISearchResponse response) - { - var options = new JsonSerializerOptions(); - options.Converters.Add(new TraceResponseDtoConverter()); - var text = JsonSerializer.Serialize(response.Documents); - return new PaginatedListBase { Total = response.Total, Result = JsonSerializer.Deserialize>(text, options)! }; - } - - private static ElasticsearchScrollResponseDto SetTraceScrollResult(ISearchResponse response) - { - var options = new JsonSerializerOptions(); - options.Converters.Add(new TraceResponseDtoConverter()); - var text = JsonSerializer.Serialize(response.Documents); - return new ElasticsearchScrollResponseDto { Total = response.Total, Result = JsonSerializer.Deserialize>(text, options)!, ScrollId = response.ScrollId }; - } - - #endregion - - #region aggregate - - private static SearchDescriptor AddAggregate(this SearchDescriptor searchDescriptor, TQuery aggModel, bool isLog) where TResult : class where TQuery : SimpleAggregateRequestDto - { - Func, IAggregationContainer>? aggregateFunc = null; - var mappings = isLog ? ElasticConstant.Log.Mappings.Value : ElasticConstant.Trace.Mappings.Value; - var mapping = mappings.FirstOrDefault(m => string.Equals(m.Name, aggModel.Name, StringComparison.OrdinalIgnoreCase)); - CreateFieldKeyword(aggModel.Name, mapping, out var field, out var keyword); - string aliasName = aggModel.Alias ?? field; - - switch (aggModel.Type) - { - case AggregateTypes.Count: - { - aggregateFunc = (aggContainer) => aggContainer.ValueCount(aliasName, agg => agg.Field(keyword)); - } - break; - case AggregateTypes.Sum: - { - aggregateFunc = (aggContainer) => aggContainer.Sum(aliasName, agg => agg.Field(field)); - } - break; - case AggregateTypes.Avg: - { - aggregateFunc = (aggContainer) => aggContainer.Average(aliasName, agg => agg.Field(field)); - } - break; - case AggregateTypes.DistinctCount: - { - aggregateFunc = (aggContainer) => aggContainer.Cardinality(aliasName, agg => agg.Field(keyword)); - } - break; - case AggregateTypes.DateHistogram: - { - if (mapping != null && mapping.Type != "date") - { - throw new UserFriendlyException($"Field of type [{field}] is not supported for aggregation [date_histogram]"); - } - aggregateFunc = (aggContainer) => aggContainer.DateHistogram(aliasName, agg => agg.Field(keyword).FixedInterval(new Time(aggModel.Interval))); - } - break; - case AggregateTypes.GroupBy: - { - aggregateFunc = (aggContainer) => aggContainer.Terms(aliasName, agg => agg.Field(keyword).Size(aggModel.MaxCount)); - } - break; - } - if (aggregateFunc != null) - searchDescriptor = searchDescriptor.Aggregations(aggContainer => aggregateFunc(aggContainer)); - - return searchDescriptor; - } - - private static object SetAggregationResult(ISearchResponse response, SimpleAggregateRequestDto aggModel) - { - if (response.Aggregations == null || !response.Aggregations.Any()) - return default!; - - foreach (var item in response.Aggregations.Values) - { - if (item is ValueAggregate value) - { - return GetDouble(value); - } - else if (item is BucketAggregate bucketAggregate) - { - return GetBucketValue(bucketAggregate, aggModel.Type, aggModel.AllValue); - } - } - return default!; - } - - private static double GetDouble(ValueAggregate value) - { - return value.Value ?? default; - } - - private static object GetBucketValue(BucketAggregate value, AggregateTypes type, bool isAll) - { - if (type == AggregateTypes.GroupBy) - { - if (isAll) - return value.Items.Select(it => KeyValuePair.Create(((KeyedBucket)it).Key.ToString(), ((KeyedBucket)it).DocCount)).ToList(); - else - return value.Items.Select(it => ((KeyedBucket)it).Key.ToString()).ToList(); - } - - else if (type == AggregateTypes.DateHistogram) - { - var result = new List>(); - foreach (var bucket in value.Items) - { - var dateHistogramBucket = (DateHistogramBucket)bucket; - result.Add(KeyValuePair.Create(dateHistogramBucket.Key, (dateHistogramBucket.DocCount ?? 0))); - } - return result; - } - return default!; - } - - private static void CreateFieldKeyword(string name, ElasticseacherMappingResponseDto? mapping, out string field, out string keyword) - { - if (mapping == null) - { - field = name; - keyword = name; - } - else - { - field = mapping.Name; - if (mapping.Type == "text" && mapping.IsKeyword.HasValue && mapping.IsKeyword.Value) - keyword = $"{field}.keyword"; - else - keyword = field; - } - } - - #endregion -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Extenistions/JsonElementExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Extenistions/JsonElementExtensions.cs deleted file mode 100644 index 4ec310c14..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Extenistions/JsonElementExtensions.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. -[assembly: InternalsVisibleTo("Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests")] -namespace System; - -internal static class JsonElementExtensions -{ - public static IEnumerable> ConvertToKeyValuePairs(this JsonElement value) - { - if (value.ValueKind != JsonValueKind.Object) - return default!; - - return GetObject(value); - } - - public static object GetValue(this JsonElement value) - { - return value.ValueKind switch - { - JsonValueKind.Object => GetObject(value), - JsonValueKind.Array => GetArray(value), - JsonValueKind.String => value.GetString()!, - JsonValueKind.Number => GetNumber(value), - JsonValueKind.True or JsonValueKind.False => value.GetBoolean(), - _ => default!, - }; - } - -#pragma warning disable S6444 - private static object GetNumber(JsonElement value) - { - var str = value.GetRawText(); - - if (Regex.IsMatch(str, @"\.")) - { - return value.GetDouble(); - } - else - { - if (!value.TryGetInt32(out int num)) - return value.GetInt64(); - return num; - } - } -#pragma warning restore S6444 - - private static IEnumerable> GetObject(JsonElement value) - { - var result = new Dictionary(); - foreach (var item in value.EnumerateObject()) - { - var v = GetValue(item.Value); - if (v == null) - continue; - result.Add(item.Name, v); - } - if (result.Any()) - return result; - return default!; - } - - public static IEnumerable GetArray(this JsonElement value) - { - var temp = value.EnumerateArray(); - if (!temp.Any()) - return default!; - var list = new List(); - foreach (var item in temp) - { - var v = GetValue(item); - list.Add(v); - } - return list; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Extenistions/ServiceExtenistion.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Extenistions/ServiceExtenistion.cs deleted file mode 100644 index e95ad673e..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Extenistions/ServiceExtenistion.cs +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -// ReSharper disable once CheckNamespace - -namespace Microsoft.Extensions.DependencyInjection; - -public static class ServiceExtenistion -{ - public static IServiceCollection AddElasticClientLog(this IServiceCollection services, string[] nodes, string indexName) - { - ElasticConstant.InitLog(indexName, true); - if (services.BuildServiceProvider().GetService() == null) - AddElasticsearch(services, nodes, ElasticConstant.LOG_CALLER_CLIENT_NAME).AddScoped(); - ElasticConstant.Log.Mappings = GetLazyMapping(services, ElasticConstant.LOG_CALLER_CLIENT_NAME, indexName); - return services; - } - - public static IServiceCollection AddElasticClientLog(this IServiceCollection services, - Action elasearchConnectionAction, Action callerAction, string indexName) - { - ElasticConstant.InitLog(indexName, true); - if (services.BuildServiceProvider().GetService() == null) - AddElasticsearch(services, elasearchConnectionAction, callerAction, ElasticConstant.LOG_CALLER_CLIENT_NAME) - .AddScoped(); - ElasticConstant.Log.Mappings = GetLazyMapping(services, ElasticConstant.LOG_CALLER_CLIENT_NAME, indexName); - return services; - } - - public static IServiceCollection AddElasticClientTrace(this IServiceCollection services, string[] nodes, string indexName) - { - ElasticConstant.InitTrace(indexName, true); - if (services.BuildServiceProvider().GetService() == null) - AddElasticsearch(services, nodes, ElasticConstant.TRACE_CALLER_CLIENT_NAME).AddScoped(); - ElasticConstant.Trace.Mappings = GetLazyMapping(services, ElasticConstant.TRACE_CALLER_CLIENT_NAME, indexName); - return services; - } - - public static IServiceCollection AddElasticClientTrace(this IServiceCollection services, - Action elasearchConnectionAction, Action callerAction, string indexName) - { - ElasticConstant.InitTrace(indexName, true); - if (services.BuildServiceProvider().GetService() == null) - AddElasticsearch(services, elasearchConnectionAction, callerAction, ElasticConstant.TRACE_CALLER_CLIENT_NAME) - .AddScoped(); - ElasticConstant.Trace.Mappings = GetLazyMapping(services, ElasticConstant.TRACE_CALLER_CLIENT_NAME, indexName); - return services; - } - - public static IServiceCollection AddElasticClientLogAndTrace(this IServiceCollection services, string[] nodes, string logIndexName, - string traceIndexName) - { - ElasticConstant.InitLog(logIndexName); - ElasticConstant.InitTrace(traceIndexName); - if (services.BuildServiceProvider().GetService() == null || services.BuildServiceProvider().GetService() == null) - AddElasticsearch(services, nodes, ElasticConstant.DEFAULT_CALLER_CLIENT_NAME) - .AddScoped() - .AddScoped(); - ElasticConstant.Log.Mappings = GetLazyMapping(services, ElasticConstant.DEFAULT_CALLER_CLIENT_NAME, logIndexName); - ElasticConstant.Trace.Mappings = GetLazyMapping(services, ElasticConstant.DEFAULT_CALLER_CLIENT_NAME, traceIndexName); - return services; - } - - public static IServiceCollection AddElasticClientLogAndTrace(this IServiceCollection services, - Action elasearchConnectionAction, Action callerAction, string logIndexName, - string traceIndexName) - { - ElasticConstant.InitLog(logIndexName); - ElasticConstant.InitTrace(traceIndexName); - if (services.BuildServiceProvider().GetService() == null || services.BuildServiceProvider().GetService() == null) - AddElasticsearch(services, elasearchConnectionAction, callerAction, ElasticConstant.DEFAULT_CALLER_CLIENT_NAME) - .AddScoped() - .AddScoped(); - ElasticConstant.Log.Mappings = GetLazyMapping(services, ElasticConstant.DEFAULT_CALLER_CLIENT_NAME, logIndexName); - ElasticConstant.Trace.Mappings = GetLazyMapping(services, ElasticConstant.DEFAULT_CALLER_CLIENT_NAME, traceIndexName); - return services; - } - - private static IServiceCollection AddElasticsearch(IServiceCollection services, string[] nodes, string name) - { - return services.AddElasticsearch(name, options => - { - options.UseNodes(nodes).UseConnectionSettings(setting => setting.EnableApiVersioningHeader(false)); - - }) - .AddCaller(name, callerBuilder => - { - callerBuilder.UseHttpClient(builder => - { - builder.BaseAddress = nodes[0]; - }).UseAuthentication(); - }); - } - - private static IServiceCollection AddElasticsearch(IServiceCollection services, - Action elasticsearchConnectionAction, - Action callerAction, string name) - { - ArgumentNullException.ThrowIfNull(callerAction); - var factory = services.BuildServiceProvider().GetService(); - var callerFactory = services.BuildServiceProvider().GetService(); - - if (factory == null || factory.Create(name) == null || callerFactory == null || callerFactory.Create(name) == null) - services.AddElasticsearch(name, elasticsearchConnectionAction) - .AddCaller(name, option => option.UseHttpClient(callerAction).UseAuthentication()); - return services; - } - - internal static IElasticClient CreateElasticClient(this IElasticClientFactory elasticsearchFactory, bool isLog) - { - if (isLog) - return elasticsearchFactory.Create(ElasticConstant.Log.IsIndependent ? ElasticConstant.LOG_CALLER_CLIENT_NAME : - ElasticConstant.DEFAULT_CALLER_CLIENT_NAME); - else - return elasticsearchFactory.Create(ElasticConstant.Trace.IsIndependent ? ElasticConstant.TRACE_CALLER_CLIENT_NAME : - ElasticConstant.DEFAULT_CALLER_CLIENT_NAME); - } - - internal static ICaller Create(this ICallerFactory callerFactory, bool isLog) - { - if (isLog) - return callerFactory.Create(ElasticConstant.Log.IsIndependent ? ElasticConstant.LOG_CALLER_CLIENT_NAME : - ElasticConstant.DEFAULT_CALLER_CLIENT_NAME); - else - return callerFactory.Create(ElasticConstant.Trace.IsIndependent ? ElasticConstant.TRACE_CALLER_CLIENT_NAME : - ElasticConstant.DEFAULT_CALLER_CLIENT_NAME); - } - - private static Lazy GetLazyMapping(IServiceCollection services, string callerName, string indexName) - { - return new Lazy(() => - { - var callerFactory = services.BuildServiceProvider().GetRequiredService(); - var caller = callerFactory.Create(callerName); - var result = caller.GetMappingAsync(indexName).Result; - return result.Select(item => (ElasticseacherMappingResponseDto)item).ToArray(); - }); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/LogService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/LogService.cs deleted file mode 100644 index 5aa921376..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/LogService.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch; - -internal class LogService : ILogService -{ - private readonly IElasticClient _client; - private readonly ICallerFactory _callerFactory; - - public LogService(IElasticClientFactory elasticClientFactory, ICallerFactory callerFactory) - { - _client = elasticClientFactory.CreateElasticClient(true); - _callerFactory = callerFactory; - } - - public async Task AggregateAsync(SimpleAggregateRequestDto query) - { - return await _client.AggregateLogAsync(query); - } - - public async Task> ListAsync(BaseRequestDto query) - { - return await _client.SearchLogAsync(query); - } - - public async Task> GetMappingAsync() - { - return await _callerFactory.Create(true).GetMappingAsync(ElasticConstant.Log.IndexName); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Masa.Contrib.StackSdks.Tsc.Elasticsearch.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Masa.Contrib.StackSdks.Tsc.Elasticsearch.csproj deleted file mode 100644 index 04cf143cf..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Masa.Contrib.StackSdks.Tsc.Elasticsearch.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - enable - enable - - - - - - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/ElasticseachLogResponseDto.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/ElasticseachLogResponseDto.cs deleted file mode 100644 index 07122fd6e..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/ElasticseachLogResponseDto.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Model; - -internal class ElasticseachLogResponseDto : LogResponseDto -{ - [JsonPropertyName("@timestamp")] - public override DateTime Timestamp { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/ElasticseacherMappingResponse.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/ElasticseacherMappingResponse.cs deleted file mode 100644 index 733b78343..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/ElasticseacherMappingResponse.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Model; - -public class ElasticseacherMappingResponseDto : MappingResponseDto -{ - /// - /// if has keyword is true ,else false - /// - public bool? IsKeyword { get; set; } - - /// - /// keyword query max length - /// - public int? MaxLenth { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/Scroll/ElasticsearchScrollRequestDto.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/Scroll/ElasticsearchScrollRequestDto.cs deleted file mode 100644 index a01917c84..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/Scroll/ElasticsearchScrollRequestDto.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Model; - -public class ElasticsearchScrollRequestDto : BaseRequestDto -{ - public string Scroll { get; set; } - - public string ScrollId { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/Scroll/ElasticsearchScrollResponseDto.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/Scroll/ElasticsearchScrollResponseDto.cs deleted file mode 100644 index 042418a1e..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/Scroll/ElasticsearchScrollResponseDto.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Model; - -public class ElasticsearchScrollResponseDto: PaginatedListBase where TResult : class -{ - public string ScrollId { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/Trace/ElasticseachTraceResponseDto.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/Trace/ElasticseachTraceResponseDto.cs deleted file mode 100644 index 27e9e4b60..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/Model/Trace/ElasticseachTraceResponseDto.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Model; - -internal class ElasticseachTraceResponseDto : TraceResponseDto -{ - [JsonPropertyName("@timestamp")] - public override DateTime Timestamp { get; set; } - - [JsonPropertyName("EndTimestamp")] - public override DateTime EndTimestamp { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/TraceService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/TraceService.cs deleted file mode 100644 index c56164656..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/TraceService.cs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch; - -internal class TraceService : ITraceService -{ - private readonly IElasticClient _client; - - public TraceService(IElasticClientFactory elasticClientFactory) - { - _client = elasticClientFactory.CreateElasticClient(false); - } - - public async Task AggregateAsync(SimpleAggregateRequestDto query) - { - return await _client.AggregateTraceAsync(query); - } - - public async Task> GetAsync(string traceId) - { - return (await _client.SearchTraceAsync(new BaseRequestDto { TraceId = traceId, Page = 1, PageSize = ElasticConstant.MaxRecordCount - 1 })).Result; - } - - public Task GetMaxDelayTraceIdAsync(BaseRequestDto query) - { - return _client.GetMaxDelayTraceIdAsync(query); - } - - public Task> ListAsync(BaseRequestDto query) - { - return _client.SearchTraceAsync(query); - } - - public Task> ScrollAsync(BaseRequestDto query) - { - if (query is not ElasticsearchScrollRequestDto) - throw new UserFriendlyException("parameter: query must is type: ElasticsearchScrollRequestDto"); - return _client.SearchTraceAsync(query); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/_Imports.cs deleted file mode 100644 index 07579054b..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.Elasticsearch/_Imports.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Log; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Model; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Model.Aggregate; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Service; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Trace; -global using Masa.Contrib.Service.Caller.HttpClient; -global using Masa.Contrib.StackSdks.Tsc.Elasticsearch; -global using Masa.Contrib.StackSdks.Tsc.Elasticsearch.Constants; -global using Masa.Contrib.StackSdks.Tsc.Elasticsearch.Converters; -global using Masa.Contrib.StackSdks.Tsc.Elasticsearch.Model; -global using Masa.Utils.Data.Elasticsearch; -global using Masa.Utils.Models; -global using Microsoft.Extensions.DependencyInjection; -global using Nest; -global using System.Runtime.CompilerServices; -global using System.Text.Json; -global using System.Text.Json.Serialization; -global using System.Text.RegularExpressions; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Extensions/ServiceExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Extensions/ServiceExtensions.cs deleted file mode 100644 index f5c8003e9..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Extensions/ServiceExtensions.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -[assembly: InternalsVisibleTo("Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests")] - -namespace Microsoft.Extensions.DependencyInjection; - -public static partial class ServiceExtensions -{ - public static IServiceCollection AddObservable(this IServiceCollection services, - ILoggingBuilder loggingBuilder, - IConfiguration configuration, - bool isBlazor = false, - bool isInterruptSignalRTracing = true) - { - return services.AddObservable(loggingBuilder, - configuration.GetSection("Masa:Observable").Get(), - configuration.GetSection("Masa:Observable:OtlpUrl").Get(), - isBlazor, - isInterruptSignalRTracing); - } - - public static IServiceCollection AddObservable(this IServiceCollection services, - ILoggingBuilder loggingBuilder, - Func optionsConfigure, - Func? otlpUrlConfigure = null, - bool isBlazor = false, - bool isInterruptSignalRTracing = true) - { - ArgumentNullException.ThrowIfNull(optionsConfigure); - var options = optionsConfigure(); - var otlpUrl = otlpUrlConfigure?.Invoke() ?? string.Empty; - return services.AddObservable(loggingBuilder, options, otlpUrl, isBlazor, isInterruptSignalRTracing); - } - - public static IServiceCollection AddObservable(this IServiceCollection services, - ILoggingBuilder loggingBuilder, - MasaObservableOptions option, - string? otlpUrl = null, - bool isBlazor = false, - bool isInterruptSignalRTracing = true) - { - ArgumentNullException.ThrowIfNull(option); - - Uri? uri = null; - if (!string.IsNullOrEmpty(otlpUrl) && !Uri.TryCreate(otlpUrl, UriKind.Absolute, out uri)) - throw new UriFormatException($"{nameof(otlpUrl)}:{otlpUrl} is invalid url"); - services.AddOpenTelemetry() - .ConfigureResource(resource => resource.AddMasaService(option)) - .AddMasaTracing(services, builder => builder.AddOtlpExporter(options => options.Endpoint = uri), - builder => - { - if (isBlazor) - builder.AspNetCoreInstrumentationOptions.AppendBlazorFilter(builder, isInterruptSignalRTracing); - else - builder.AspNetCoreInstrumentationOptions.AppendDefaultFilter(builder, isInterruptSignalRTracing); - }) - .AddMasaMetrics(builder => builder.AddOtlpExporter(otlp => otlp.Endpoint = uri)); - - var resources = ResourceBuilder.CreateDefault().AddMasaService(option); - loggingBuilder.AddMasaOpenTelemetry(builder => - { - builder.SetResourceBuilder(resources); - builder.AddOtlpExporter(otlp => otlp.Endpoint = uri); - }); - - return services; - } - - public static IApplicationBuilder UseMASAHttpReponseLog(this IApplicationBuilder app) - { - return app.UseMiddleware(); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Extensions/StreamExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Extensions/StreamExtensions.cs deleted file mode 100644 index 13c86d393..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Extensions/StreamExtensions.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the Apache License. See LICENSE.txt in the project root for license information. - -namespace System.IO; - -internal static class StreamExtensions -{ - private static readonly Encoding _defaultEncoding = Encoding.UTF8; - - public static async Task<(long, string?)> ReadAsStringAsync(this Stream stream, Encoding? encoding = null, int bufferSize = 4096) - { - if (stream == null || !stream.CanRead || !stream.CanSeek) - return (-1, null); - - var start = stream.Position; - - try - { - List data = new(); - var buffer = new byte[bufferSize]; - stream.Seek(0, SeekOrigin.Begin); - - do - { - var count = await stream.ReadAsync(buffer.AsMemory(0, bufferSize)); - if (count <= 0) - break; - - if (bufferSize - count > 0) - { - data.AddRange(buffer[0..count]); - break; - } - - data.AddRange(buffer); - } while (true); - - if (data.Count > 0) - { - if (data.Count - OpenTelemetryInstrumentationOptions.MaxBodySize > 0) - return (data.Count, Convert.ToBase64String(data.ToArray())); - - return (data.Count, (encoding ?? _defaultEncoding).GetString(data.ToArray())); - } - } - catch (Exception ex) - { - OpenTelemetryInstrumentationOptions.Logger?.LogError(ex, "ReadAsStringAsync Error"); - } - finally - { - stream.Seek(start, SeekOrigin.Begin); - } - - return (-1, null); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Logging/ServiceExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Logging/ServiceExtensions.cs deleted file mode 100644 index b2f7e78f6..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Logging/ServiceExtensions.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the Apache License. See LICENSE.txt in the project root for license information. - -namespace Microsoft.Extensions.Logging; - -public static class ServiceExtensions -{ - public static ILoggingBuilder AddMasaOpenTelemetry(this ILoggingBuilder builder, Action configure) - { - return builder.AddOpenTelemetry(options => - { - options.IncludeScopes = true; - options.IncludeFormattedMessage = true; - options.ParseStateValues = true; - if (configure != null) - configure.Invoke(options); - }); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.csproj deleted file mode 100644 index 87895e30a..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.csproj +++ /dev/null @@ -1,22 +0,0 @@ - - - - disable - enable - false - - - - - - - - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Metric/Instrumentation/Http/HttpResponseMeter.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Metric/Instrumentation/Http/HttpResponseMeter.cs deleted file mode 100644 index 9c821e15d..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Metric/Instrumentation/Http/HttpResponseMeter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Metric.Instrumentation.Http; - -public class HttpResponseMeter : IHttpResponseMetric -{ - private readonly Histogram responseHistogram; - - public HttpResponseMeter(Meter meter) - { - responseHistogram = meter.CreateHistogram("http.response", "ms", "http response duration"); - } - - public void Handle(HttpResponse httpResponse) - { - var httpRequest = httpResponse.HttpContext.Request; - var path = httpRequest.Path; - if (string.IsNullOrEmpty(path)) - return; - - var tags = new KeyValuePair[] - { - new KeyValuePair("http.status_code", httpResponse.StatusCode), - new KeyValuePair("http.method", httpResponse.HttpContext.Request.Method), - new KeyValuePair("http.scheme", httpResponse.HttpContext.Request.Scheme), - new KeyValuePair("http.target", httpResponse.HttpContext.Request.Path) - }; - responseHistogram.Record(Activity.Current!.Duration.TotalMilliseconds, tags.ToArray()); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Metric/Instrumentation/Http/IHttpMetric.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Metric/Instrumentation/Http/IHttpMetric.cs deleted file mode 100644 index e4629c2dd..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Metric/Instrumentation/Http/IHttpMetric.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Metric.Instrumentation.Http; - -public interface IHttpRequestMetric -{ - void Handle(HttpRequest httpRequest); -} - -public interface IHttpResponseMetric -{ - void Handle(HttpResponse httpResponse); -} - -public interface IHttpRequestMessageMetric -{ - void Handle(HttpRequestMessage httpRequestMessage); -} - -public interface IHttpResponseMessageMetric -{ - void Handle(HttpResponseMessage httpResponseMessage); -} - -public interface IHttpWebRequestMetric -{ - void Handle(HttpWebRequest httpWebRequest); -} - -public interface IHttpWebResponseMetric -{ - void Handle(HttpWebResponse httpWebResponse); -} - -public interface ICustomMetrics -{ - void Handle(string name, object payload); -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Metric/ServiceExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Metric/ServiceExtensions.cs deleted file mode 100644 index ae025b4c7..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Metric/ServiceExtensions.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the Apache License. See LICENSE.txt in the project root for license information. - -namespace Microsoft.Extensions.DependencyInjection; - -public static partial class ServiceExtensions -{ - public static IServiceCollection AddMasaMetrics(this IServiceCollection services, Action? configure = null) - { - services.AddOpenTelemetry().AddMasaMetrics(configure); - return services; - } - - internal static OpenTelemetryBuilder AddMasaMetrics(this OpenTelemetryBuilder builder, Action? configure = null) - { - return builder.WithMetrics(builder => - { - configure?.Invoke(builder); - builder.AddRuntimeInstrumentation() - .AddAspNetCoreInstrumentation() - .AddHttpClientInstrumentation() - .AddMeter(HttpMetricProviders.Meter.Name); - }); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Middleware/HttpResponseMiddleware.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Middleware/HttpResponseMiddleware.cs deleted file mode 100644 index a80eb4afb..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Middleware/HttpResponseMiddleware.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry; - -internal class HttpResponseMiddleware -{ - private readonly RequestDelegate _next; - - public HttpResponseMiddleware(RequestDelegate next) - { - _next = next; - } - - public async Task InvokeAsync(HttpContext httpContext) - { - var httpResponse = httpContext.Response; - using var ms = new MemoryStream(); - var rawStream = httpResponse.Body; - httpResponse.Body = ms; - await _next(httpContext); - ms.Seek(0, SeekOrigin.Begin); - var responseResult = new StreamReader(ms).ReadToEnd(); - ms.Seek(0, SeekOrigin.Begin); - ms.CopyTo(rawStream); - httpResponse.Body = rawStream; - - if (httpResponse.StatusCode - 299 == 0 || httpResponse.StatusCode - 500 >= 0) - { - Activity.Current?.SetTag(OpenTelemetryAttributeName.Http.RESPONSE_CONTENT_BODY, responseResult); - } - else - { - OpenTelemetryInstrumentationOptions.Logger.LogInformation("response length: {length}, context: {context}", responseResult.Length, responseResult); - } - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Options/MasaObservableOptions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Options/MasaObservableOptions.cs deleted file mode 100644 index 68952f837..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Options/MasaObservableOptions.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the Apache License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc; - -public class MasaObservableOptions -{ - public string ProjectName { get; set; } - - public string ServiceName { get; set; } - - public string ServiceNameSpace { get; set; } - - public string ServiceInstanceId { get; set; } - - public string ServiceVersion { get; set; } - - public string Layer { get; set; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Options/OpenTelemetryAttributeName.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Options/OpenTelemetryAttributeName.cs deleted file mode 100644 index 953d4becd..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Options/OpenTelemetryAttributeName.cs +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the Apache License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry; - -/// -/// Constants for semantic attribute names outlined by the OpenTelemetry specifications. -/// . -/// -internal static class OpenTelemetryAttributeName -{ - /// - /// Constants for deployment semantic attribute names outlined by the OpenTelemetry specifications. - /// . - /// - internal static class Deployment - { - /// - /// The name of the deployment environment (aka deployment tier). - /// - /// staging; production. - public const string ENVIRONMENT = "deployment.environment"; - } - - /// - /// Constants for end user semantic attribute names outlined by the OpenTelemetry specifications. - /// . - /// - internal static class EndUser - { - /// - /// Username or client_id extracted from the access token or Authorization header in the inbound request from outside the system. - /// - /// E.g. username. - public const string ID = "enduser.id"; - - /// - /// Actual/assumed role the client is making the request under extracted from token or application security context. - /// - /// E.g. admin. - public const string ROLE = "enduser.role"; - - /// - /// Scopes or granted authorities the client currently possesses extracted from token or application security context. - /// The value would come from the scope associated with an OAuth 2.0 Access Token or an attribute value in a SAML 2.0 Assertion. - /// - /// E.g. read:message,write:files. - public const string SCOPE = "enduser.scope"; - - /// - /// custom attr - /// - public const string USER_NICK_NAME = "enduser.nick_name"; - } - - /// - /// Constants for HTTP semantic attribute names outlined by the OpenTelemetry specifications. - /// . - /// - internal static class Http - { - public const string STATUS_CODE = "status_code"; - - /// - /// The URI scheme identifying the used protocol. - /// - /// E.g. http or https. - public const string SCHEME = "http.scheme"; - - /// - /// Kind of HTTP protocol used. - /// - /// E.g. 1.0, 1.1, 2.0, SPDY or QUIC. - public const string FLAVOR = "http.flavor"; - - /// - /// The IP address of the original client behind all proxies, if known (e.g. from X-Forwarded-For). - /// - /// E.g. 83.164.160.102. - public const string CLIENT_IP = "http.client_ip"; - - /// - /// The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, - /// but not always, present as the Content-Length header. For requests using transport encoding, this should be the - /// compressed size. - /// - /// E.g. 3495. - public const string REQUEST_CONTENT_LENGTH = "http.request_content_length"; - - /// - /// custom attr - /// - public const string REQUEST_CONTENT_BODY = "http.request_content_body"; - - /// - /// The content type of the request body. - /// - /// E.g. application/json. - public const string REQUEST_CONTENT_TYPE = "http.request_content_type"; - - /// - /// The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, - /// but not always, present as the Content-Length header. For requests using transport encoding, this should be the - /// compressed size. - /// - /// E.g. 3495. - public const string RESPONSE_CONTENT_LENGTH = "http.response_content_length"; - - /// - /// The content type of the response body. - /// - /// E.g. application/json. - public const string RESPONSE_CONTENT_TYPE = "http.response_content_type"; - - /// - /// custom attr - /// - public const string RESPONSE_CONTENT_BODY = "http.response_content_body"; - - /// - /// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#common-attributes - /// - public const string REQUEST_USER_AGENT = "user_agent.original"; - - public const string REQUEST_AUTHORIZATION = "authorization"; - } - - /// - /// Constants for host semantic attribute names outlined by the OpenTelemetry specifications. - /// . - /// - internal static class Host - { - /// - /// Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, - /// or another name specified by the user. - /// - /// E.g. opentelemetry-test. - public const string NAME = "host.name"; - } - - /// - /// Constants for service semantic attribute names outlined by the OpenTelemetry specifications. - /// . - /// - internal static class Service - { - public const string NAME = "service.name"; - - /// - /// custom attr - /// - public const string PROJECT_NAME = "service.project.name"; - - public const string LAYER = "service.layer"; - } - - internal static class ExceptionAttributeName - { - public const string TYPE = "exception.type"; - - public const string MESSAGE = "exception.message"; - - public const string STACKTRACE = "exception.stacktrace"; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/ResourceBuilder/ResourceBuilderExtenstions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/ResourceBuilder/ResourceBuilderExtenstions.cs deleted file mode 100644 index 8296a6bb3..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/ResourceBuilder/ResourceBuilderExtenstions.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the Apache License. See LICENSE.txt in the project root for license information. - -namespace OpenTelemetry.Resources; - -public static class ResourceBuilderExtenstions -{ - public static ResourceBuilder AddMasaService( - this ResourceBuilder resourceBuilder, - MasaObservableOptions options, Action? action = null) - { - ArgumentNullException.ThrowIfNull(options); - - resourceBuilder = resourceBuilder.AddService(options.ServiceName, options.ServiceNameSpace, options.ServiceVersion, true, options.ServiceInstanceId); - - if (string.IsNullOrEmpty(options.Layer)) - options.Layer = "General"; - - var dic = new Dictionary() { { OpenTelemetryAttributeName.Service.LAYER, options.Layer } }; - if (!string.IsNullOrEmpty(options.ProjectName)) - dic.Add(OpenTelemetryAttributeName.Service.PROJECT_NAME, options.ProjectName); - - resourceBuilder.AddAttributes(dic); - resourceBuilder.AddTelemetrySdk(); - - action?.Invoke(resourceBuilder); - - return resourceBuilder; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/ActivityExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/ActivityExtensions.cs deleted file mode 100644 index a5b44fb35..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/ActivityExtensions.cs +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the Apache License. See LICENSE.txt in the project root for license information. - -namespace System.Diagnostics; - -public static class ActivityExtension -{ - public static Activity AddMasaSupplement(this Activity activity, HttpRequest httpRequest) - { - activity.SetTag(OpenTelemetryAttributeName.Http.FLAVOR, httpRequest.Protocol); - activity.SetTag(OpenTelemetryAttributeName.Http.SCHEME, httpRequest.Scheme); - activity.SetTag(OpenTelemetryAttributeName.Http.REQUEST_CONTENT_LENGTH, httpRequest.ContentLength); - activity.SetTag(OpenTelemetryAttributeName.Http.REQUEST_CONTENT_TYPE, httpRequest.ContentType); - if (httpRequest.Headers != null) - { - activity.SetTag(OpenTelemetryAttributeName.Http.REQUEST_AUTHORIZATION, httpRequest.Headers.Authorization); - activity.SetTag(OpenTelemetryAttributeName.Http.REQUEST_USER_AGENT, httpRequest.Headers.UserAgent); - var realIP = httpRequest.Headers["X-Real-IP"].ToString(); - realIP ??= httpRequest.HttpContext!.Connection.RemoteIpAddress!.ToString(); - activity.SetTag(OpenTelemetryAttributeName.Http.CLIENT_IP, realIP); - } - - if ((httpRequest.HttpContext.User?.Claims.Count() ?? 0) > 0) - { - activity.AddTag(OpenTelemetryAttributeName.EndUser.ID, httpRequest.HttpContext.User?.FindFirst("sub")?.Value ?? string.Empty); - activity.AddTag(OpenTelemetryAttributeName.EndUser.USER_NICK_NAME, httpRequest.HttpContext.User?.FindFirst("https://masastack.com/security/authentication/MasaNickName")?.Value ?? string.Empty); - } - if (httpRequest.Body != null) - { - if (!httpRequest.Body.CanSeek) - httpRequest.EnableBuffering(); - SetActivityBody(activity, httpRequest.Body, GetHttpRequestEncoding(httpRequest)).ConfigureAwait(false).GetAwaiter().GetResult(); - } - activity.SetTag(OpenTelemetryAttributeName.Host.NAME, Dns.GetHostName()); - return activity; - } - - public static Activity AddMasaSupplement(this Activity activity, HttpRequestMessage httpRequest) - { - activity.SetTag(OpenTelemetryAttributeName.Http.SCHEME, httpRequest.RequestUri?.Scheme); - activity.SetTag(OpenTelemetryAttributeName.Host.NAME, Dns.GetHostName()); - if (httpRequest.Headers != null) - { - activity.SetTag(OpenTelemetryAttributeName.Http.REQUEST_AUTHORIZATION, httpRequest.Headers.Authorization); - activity.SetTag(OpenTelemetryAttributeName.Http.REQUEST_USER_AGENT, httpRequest.Headers.UserAgent); - } - if (httpRequest.Content != null) - { - SetActivityBody(activity, - httpRequest.Content.ReadAsStreamAsync().ConfigureAwait(false).GetAwaiter().GetResult(), - GetHttpRequestMessageEncoding(httpRequest)).ConfigureAwait(false).GetAwaiter().GetResult(); - } - - return activity; - } - - public static Activity AddMasaSupplement(this Activity activity, HttpResponse httpResponse) - { - activity.SetTag(OpenTelemetryAttributeName.Http.RESPONSE_CONTENT_LENGTH, httpResponse.ContentLength); - activity.SetTag(OpenTelemetryAttributeName.Http.RESPONSE_CONTENT_TYPE, httpResponse.ContentType); - activity.SetTag(OpenTelemetryAttributeName.Host.NAME, Dns.GetHostName()); - - if ((httpResponse.HttpContext.User?.Claims.Count() ?? 0) > 0) - { - activity.AddTag(OpenTelemetryAttributeName.EndUser.ID, httpResponse.HttpContext.User?.FindFirst("sub")?.Value ?? string.Empty); - activity.AddTag(OpenTelemetryAttributeName.EndUser.USER_NICK_NAME, httpResponse.HttpContext.User?.FindFirst("https://masastack.com/security/authentication/MasaNickName")?.Value ?? string.Empty); - } - if (httpResponse.HttpContext.Request != null && httpResponse.HttpContext.Request.Headers != null) - { - var realIP = httpResponse.HttpContext.Request.Headers["X-Real-IP"].ToString(); - realIP ??= httpResponse.HttpContext!.Connection.RemoteIpAddress!.ToString(); - activity.SetTag(OpenTelemetryAttributeName.Http.CLIENT_IP, realIP); - } - return activity; - } - - public static Activity AddMasaSupplement(this Activity activity, HttpResponseMessage httpResponse) - { - activity.SetTag(OpenTelemetryAttributeName.Host.NAME, Dns.GetHostName()); - return activity; - } - - private static Encoding? GetHttpRequestEncoding(HttpRequest httpRequest) - { - if (httpRequest.Body != null) - { - var contentType = httpRequest.ContentType; - if (!string.IsNullOrEmpty(contentType) - && MediaTypeHeaderValue.TryParse(contentType, out var attr) - && attr != null - && !string.IsNullOrEmpty(attr.CharSet)) - return Encoding.GetEncoding(attr.CharSet); - } - - return null; - } - - private static Encoding? GetHttpRequestMessageEncoding(HttpRequestMessage httpRequest) - { - if (httpRequest.Content != null) - { - var encodeStr = httpRequest.Content.Headers?.ContentType?.CharSet; - - if (!string.IsNullOrEmpty(encodeStr)) - { - return Encoding.GetEncoding(encodeStr); - } - } - - return null; - } - - private static async Task SetActivityBody(Activity activity, Stream inputSteam, Encoding? encoding = null) - { - (long length, string? body) = await inputSteam.ReadAsStringAsync(encoding); - - if (length <= 0) - return; - if (length - OpenTelemetryInstrumentationOptions.MaxBodySize > 0) - { - OpenTelemetryInstrumentationOptions.Logger?.LogInformation("Request body in base64 encode: {Body}", body); - } - else - { - activity.SetTag(OpenTelemetryAttributeName.Http.REQUEST_CONTENT_BODY, body); - } - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/AspNetCoreInstrumentationOptionsExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/AspNetCoreInstrumentationOptionsExtensions.cs deleted file mode 100644 index 8bc9ff29e..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/AspNetCoreInstrumentationOptionsExtensions.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the Apache License. See LICENSE.txt in the project root for license information. - -namespace Microsoft.Extensions.DependencyInjection; - -public static class AspNetCoreInstrumentationOptionsExtensions -{ - private static readonly List _CommonFilterIgnoreSuffix = new() - { - ".js", - ".css", - ".ico", - ".png", - ".woff", - ".icon" - }; - - private static readonly List _CommonFilterIgnorePrefix = new() - { - "/swagger", - "/healthz" - }; - - private static readonly List _BlazorFilterIgnorePrefix = new() - { - "/_blazor", - "/_content", - "/negotiate" - }; - - private static bool IsInterruptSignalrTracing = true; - - /// - /// The default filter ignore list includes swagger. - /// - /// - /// - /// - public static void AppendDefaultFilter(this Action options, - OpenTelemetryInstrumentationOptions openTelemetryInstrumentationOptions, - bool isInterruptSignalrTracing) - { - IsInterruptSignalrTracing = isInterruptSignalrTracing; - options += opt => - { - opt.Filter = IsDefaultFilter; - }; - openTelemetryInstrumentationOptions.AspNetCoreInstrumentationOptions += options; - } - - private static bool IsDefaultFilter(HttpContext httpContext) => !(IsInterruptSignalrTracing && IsWebsocket(httpContext) - || IsReuqestPathMatchPrefix(httpContext, _CommonFilterIgnorePrefix) - || IsReuqestPathMatchSuffix(httpContext, _CommonFilterIgnoreSuffix)); - - /// - /// The filter ignore list includes swagger and blazor and static files. - /// - /// - /// - /// - public static void AppendBlazorFilter(this Action options, - OpenTelemetryInstrumentationOptions openTelemetryInstrumentationOptions, - bool isInterruptSignalrTracing) - { - IsInterruptSignalrTracing = isInterruptSignalrTracing; - options += opt => - { - opt.Filter = httpContext => IsDefaultFilter(httpContext) && IsBlazorFilter(httpContext); - }; - openTelemetryInstrumentationOptions.AspNetCoreInstrumentationOptions += options; - } - - private static bool IsBlazorFilter(HttpContext httpContext) => !IsReuqestPathMatchPrefix(httpContext, _BlazorFilterIgnorePrefix); - - private static bool IsWebsocket(HttpContext httpContext) - { - if (httpContext.Request.Headers.ContainsKey("Connection") - && httpContext.Request.Headers.ContainsKey(httpContext.Request.Headers["Connection"])) - { - Activity.Current = null; - return true; - } - return false; - } - - private static bool IsReuqestPathMatchSuffix(HttpContext httpContext, List suffix) - { - return !string.IsNullOrEmpty(httpContext.Request.Path.Value) && suffix.Exists(str => httpContext.Request.Path.Value.EndsWith(str)); - } - - private static bool IsReuqestPathMatchPrefix(HttpContext httpContext, List prefix) - { - return !string.IsNullOrEmpty(httpContext.Request.Path.Value) && prefix.Exists(str => httpContext.Request.Path.Value.StartsWith(str)); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/AspNetCoreInstrumentationHandler.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/AspNetCoreInstrumentationHandler.cs deleted file mode 100644 index 28d26fb2a..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/AspNetCoreInstrumentationHandler.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tracing.Handler; - -public class AspNetCoreInstrumentationHandler : ExceptionHandler -{ - public virtual void OnHttpRequest(Activity activity, HttpRequest httpRequest) - { - activity.AddMasaSupplement(httpRequest); - HttpMetricProviders.AddHttpRequestMetric(httpRequest); - } - - public virtual void OnHttpResponse(Activity activity, HttpResponse httpResponse) - { - activity.AddMasaSupplement(httpResponse); - HttpMetricProviders.AddHttpResponseMetric(httpResponse); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/ExceptionHandler.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/ExceptionHandler.cs deleted file mode 100644 index 2271edfb3..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/ExceptionHandler.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tracing.Handler; - -public class ExceptionHandler -{ - public virtual void OnException(Activity activity, Exception exception) - { - if (exception != null) - { - activity.SetTag(OpenTelemetryAttributeName.ExceptionAttributeName.MESSAGE, exception.Message); - activity.SetTag(OpenTelemetryAttributeName.ExceptionAttributeName.STACKTRACE, exception.ToString()); - } - } - - public virtual bool IsRecordException { get; set; } = true; -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/HttpClientInstrumentHandler.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/HttpClientInstrumentHandler.cs deleted file mode 100644 index 95efd633f..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/HttpClientInstrumentHandler.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tracing.Handler; - -public class HttpClientInstrumentHandler : ExceptionHandler -{ - public virtual void OnHttpRequestMessage(Activity activity, HttpRequestMessage httpRequestMessage) - { - activity.AddMasaSupplement(httpRequestMessage); - HttpMetricProviders.AddHttpRequestMessageMetric(httpRequestMessage); - } - - public virtual void OnHttpResponseMessage(Activity activity, HttpResponseMessage httpResponseMessage) - { - activity.AddMasaSupplement(httpResponseMessage); - HttpMetricProviders.AddHttpResponseMessageMetric(httpResponseMessage); - } - - public virtual void OnHttpWebRequest(Activity activity, HttpWebRequest httpWebRequest) - { - - } - - public virtual void OnHttpWebResponse(Activity activity, HttpWebResponse httpWebResponse) - { - - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/HttpMetricProviders.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/HttpMetricProviders.cs deleted file mode 100644 index 18b633806..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/Handler/HttpMetricProviders.cs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tracing.Handler; - -public sealed class HttpMetricProviders -{ - private HttpMetricProviders() { } - - static HttpMetricProviders() - { - Meter = new Meter("masa stack metrics", "1.0.0"); - RegisterProvider(typeof(HttpResponseMeter)); - } - - internal static Meter Meter { get; private set; } - - private readonly static List _httpRequestMetricProviders = new(); - - private readonly static List _httpResponseMetricProviders = new(); - - private readonly static List _httpRequestMessageMetricProviders = new(); - - private readonly static List _httpResponseMessageMetricProviders = new(); - - private readonly static List _httpWebRequestMetricProviders = new(); - - private readonly static List _httpWebResponseMetricProviders = new(); - - public static void RegisterProvider(params Type[] types) - { - foreach (var type in types) - { - var interfaces = type.GetInterfaces(); - var constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, - Type.DefaultBinder, - new Type[] { typeof(Meter) }, - new ParameterModifier[] { new ParameterModifier(1) }); - if (constructor == null) - continue; - object instance = constructor.Invoke(new object[] { Meter }); - - if (Array.Exists(interfaces, i => i == typeof(IHttpRequestMetric))) - { - Add(_httpRequestMetricProviders, instance, type); - } - if (Array.Exists(interfaces, i => i == typeof(IHttpResponseMetric))) - { - Add(_httpResponseMetricProviders, instance, type); - } - if (Array.Exists(interfaces, i => i == typeof(IHttpRequestMessageMetric))) - { - Add(_httpRequestMessageMetricProviders, instance, type); - } - if (Array.Exists(interfaces, i => i == typeof(IHttpResponseMessageMetric))) - { - Add(_httpResponseMessageMetricProviders, instance, type); - } - if (Array.Exists(interfaces, i => i == typeof(IHttpWebRequestMetric))) - { - Add(_httpWebRequestMetricProviders, instance, type); - } - if (Array.Exists(interfaces, i => i == typeof(IHttpWebResponseMetric))) - { - Add(_httpWebResponseMetricProviders, instance, type); - } - } - } - - private static void Add(List list, object obj, Type type) where T : class - { - if (list.Exists(t => t.GetType() == type)) - return; - list.Add((T)obj); - } - - internal static void AddHttpRequestMetric(HttpRequest httpRequest) - { - _httpRequestMetricProviders.ForEach(p => p.Handle(httpRequest)); - } - - internal static void AddHttpResponseMetric(HttpResponse httpResponse) - { - _httpResponseMetricProviders.ForEach(p => p.Handle(httpResponse)); - } - - internal static void AddHttpRequestMessageMetric(HttpRequestMessage httpRequestMessage) - { - _httpRequestMessageMetricProviders.ForEach(p => p.Handle(httpRequestMessage)); - } - - internal static void AddHttpResponseMessageMetric(HttpResponseMessage httpResponseMessage) - { - _httpResponseMessageMetricProviders.ForEach(p => p.Handle(httpResponseMessage)); - } - - internal static void AddHttpWebRequestMetric(HttpWebRequest httpWebRequest) - { - _httpWebRequestMetricProviders.ForEach(p => p.Handle(httpWebRequest)); - } - - internal static void AddHttpWebResponseMetric(HttpWebResponse httpWebResponse) - { - _httpWebResponseMetricProviders.ForEach(p => p.Handle(httpWebResponse)); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/OpenTelemetryInstrumentationOptions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/OpenTelemetryInstrumentationOptions.cs deleted file mode 100644 index 4edbb2d11..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/OpenTelemetryInstrumentationOptions.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the Apache License. See LICENSE.txt in the project root for license information. - -namespace Microsoft.Extensions.DependencyInjection; - -public class OpenTelemetryInstrumentationOptions -{ - public OpenTelemetryInstrumentationOptions(IServiceProvider serviceProvider) - { - if (Logger == null) - { - var loggerFactory = serviceProvider.GetRequiredService(); - Logger = loggerFactory.CreateLogger("Masa.Contrib.StackSdks.Tsc.OpenTelemetry"); - } - } - - private readonly static AspNetCoreInstrumentationHandler aspNetCoreInstrumentationHandler = new(); - private readonly static HttpClientInstrumentHandler httpClientInstrumentHandler = new(); - - internal static ILogger Logger { get; private set; } - internal static long MaxBodySize { get; private set; } = 200 * 1 << 10; - - /// - /// Default record all data. You can replace it or set null - /// - public Action AspNetCoreInstrumentationOptions { get; set; } = options => - { - options.EnrichWithHttpRequest = aspNetCoreInstrumentationHandler.OnHttpRequest; - options.EnrichWithHttpResponse = aspNetCoreInstrumentationHandler.OnHttpResponse; - options.EnrichWithException = aspNetCoreInstrumentationHandler.OnException; - }; - - /// - /// Default record all data. You can replace it or set null - /// - public Action HttpClientInstrumentationOptions { get; set; } = options => - { - options.EnrichWithException = httpClientInstrumentHandler.OnException; - options.EnrichWithHttpRequestMessage = httpClientInstrumentHandler.OnHttpRequestMessage; - options.EnrichWithHttpResponseMessage = httpClientInstrumentHandler.OnHttpResponseMessage; - options.EnrichWithHttpWebResponse = httpClientInstrumentHandler.OnHttpWebResponse; - options.EnrichWithHttpWebRequest = httpClientInstrumentHandler.OnHttpWebRequest; - }; - - /// - /// Default record db statement for text. You can replace it or set null - /// - public Action EntityFrameworkInstrumentationOptions { get; set; } = options => - { - options.SetDbStatementForText = true; - }; - - public Action ElasticsearchClientInstrumentationOptions { get; set; } = options => - { - options.ParseAndFormatRequest = true; - }; - - public Func ConnectionMultiplexerOptions { get; set; } - - public Action StackExchangeRedisInstrumentationOptions { get; set; } - - /// - /// Build trace callback, allow to supplement the build process - /// - public Action BuildTraceCallback { get; set; } - - public static void SetMaxBodySize(string maxValue) - { - var regex = new Regex(@"\s+", RegexOptions.None, TimeSpan.FromSeconds(1)); - if (maxValue != null) - maxValue = regex.Replace(maxValue, ""); - - if (string.IsNullOrEmpty(maxValue)) - return; - var unit = maxValue[^1]; - var isNum = int.TryParse(maxValue[..(maxValue.Length - 1)], out int num); - if (!isNum || num <= 0) return; - switch (unit) - { - case 'k': - case 'K': - MaxBodySize = num * 1 << 10; - break; - case 'm': - case 'M': - MaxBodySize = num * 1 << 20; - break; - default: - MaxBodySize = num; - break; - } - } - - public static void SetMaxBodySize(long maxByteValue) - { - if (maxByteValue > 0) - MaxBodySize = maxByteValue; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/ServiceExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/ServiceExtensions.cs deleted file mode 100644 index 6ba18572b..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/Traceing/ServiceExtensions.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the Apache License. See LICENSE.txt in the project root for license information. - -namespace Microsoft.Extensions.DependencyInjection; - -public static partial class ServiceExtensions -{ - public static IServiceCollection AddMasaTracing(this IServiceCollection services, - Action builderConfigure, - Action? configure = null) - { - services.AddOpenTelemetry().AddMasaTracing(services, builderConfigure, configure); - return services; - } - - internal static OpenTelemetryBuilder AddMasaTracing(this OpenTelemetryBuilder builder, - IServiceCollection services, - Action builderConfigure, - Action? openTelemetryInstrumentationOptions = null) - { - return builder.WithTracing(builder => - { - builder.SetSampler(new AlwaysOnSampler()); - var option = services.BuildServiceProvider().GetService(); - option ??= new OpenTelemetryInstrumentationOptions(services.BuildServiceProvider()); - openTelemetryInstrumentationOptions?.Invoke(option); - - if (option.AspNetCoreInstrumentationOptions != null) - builder.AddAspNetCoreInstrumentation(option.AspNetCoreInstrumentationOptions); - - if (option.HttpClientInstrumentationOptions != null) - builder.AddHttpClientInstrumentation(option.HttpClientInstrumentationOptions); - - if (option.EntityFrameworkInstrumentationOptions != null) - builder.AddEntityFrameworkCoreInstrumentation(option.EntityFrameworkInstrumentationOptions); - - if (option.ElasticsearchClientInstrumentationOptions != null) - builder.AddElasticsearchClientInstrumentation(option.ElasticsearchClientInstrumentationOptions); - - if (option.ConnectionMultiplexerOptions != null) - { - foreach (Delegate handle in option.ConnectionMultiplexerOptions.GetInvocationList()) - { - var obj = handle.DynamicInvoke(); - builder.AddRedisInstrumentation((IConnectionMultiplexer)obj!, options => - { - options.SetVerboseDatabaseStatements = true; - option.StackExchangeRedisInstrumentationOptions?.Invoke(options); - }); - } - } - - builderConfigure?.Invoke(builder); - option.BuildTraceCallback?.Invoke(builder); - }); - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/_Imports.cs deleted file mode 100644 index 00f147249..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc.OpenTelemetry/_Imports.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.Contrib.StackSdks.Tsc; -global using Masa.Contrib.StackSdks.Tsc.OpenTelemetry; -global using Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Metric.Instrumentation.Http; -global using Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tracing.Handler; -global using Microsoft.AspNetCore.Builder; -global using Microsoft.AspNetCore.Http; -global using Microsoft.Extensions.Configuration; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.Extensions.Logging; -global using OpenTelemetry; -global using OpenTelemetry.Instrumentation.AspNetCore; -global using OpenTelemetry.Instrumentation.ElasticsearchClient; -global using OpenTelemetry.Instrumentation.EntityFrameworkCore; -global using OpenTelemetry.Instrumentation.Http; -global using OpenTelemetry.Instrumentation.StackExchangeRedis; -global using OpenTelemetry.Logs; -global using OpenTelemetry.Metrics; -global using OpenTelemetry.Resources; -global using OpenTelemetry.Trace; -global using StackExchange.Redis; -global using System; -global using System.Collections.Generic; -global using System.Diagnostics; -global using System.Diagnostics.Metrics; -global using System.IO; -global using System.Linq; -global using System.Net; -global using System.Net.Http; -global using System.Net.Http.Headers; -global using System.Reflection; -global using System.Runtime.CompilerServices; -global using System.Text; -global using System.Text.RegularExpressions; -global using System.Threading.Tasks; diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Extensions/CallerProviderExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Extensions/CallerProviderExtensions.cs deleted file mode 100644 index d1b9376ec..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Extensions/CallerProviderExtensions.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -[assembly: InternalsVisibleTo("Masa.Contrib.StackSdks.Tsc.Tests")] -// ReSharper disable once CheckNamespace -namespace Masa.BuildingBlocks.Service.Caller; - -internal static class CallerProviderExtensions -{ - public static async Task GetByBodyAsync(this ICaller caller, string url, object? body) where TResult : class - { - var request = new HttpRequestMessage(HttpMethod.Get, url); - if (body is not null) - { - request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json"); - } - return (await caller.SendAsync(request))!; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Extensions/ServiceExtensions.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Extensions/ServiceExtensions.cs deleted file mode 100644 index 8a2493d5b..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Extensions/ServiceExtensions.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -[assembly: InternalsVisibleTo("Masa.Contrib.StackSdks.Tsc.Tests")] - -// ReSharper disable once CheckNamespace -namespace Microsoft.Extensions.DependencyInjection; - -public static partial class ServiceExtensions -{ - private const string DEFAULT_CLIENT_NAME = "masa.contrib.stacksdks.tsc"; - - public static IServiceCollection AddTscClient(this IServiceCollection services, string tscServiceBaseUrl) - { - ArgumentNullException.ThrowIfNull(tscServiceBaseUrl); - - if (services.Any(service => service.ServiceType == typeof(ITscClient))) - return services; - - services.AddCaller(DEFAULT_CLIENT_NAME, builder => - { - builder.UseHttpClient(options => - { - options.BaseAddress = tscServiceBaseUrl; - }).UseAuthentication(); - }); - - services.AddScoped(serviceProvider => - { - var caller = serviceProvider.GetRequiredService().Create(DEFAULT_CLIENT_NAME); - return new TscClient(caller); - }); - - MasaApp.TrySetServiceCollection(services); - return services; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Masa.Contrib.StackSdks.Tsc.csproj b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Masa.Contrib.StackSdks.Tsc.csproj deleted file mode 100644 index 6af569504..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Masa.Contrib.StackSdks.Tsc.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - enable - enable - - - - - - - - - diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/README.md b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/README.md deleted file mode 100644 index ec4fb286a..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/README.md +++ /dev/null @@ -1,56 +0,0 @@ -[中](README.zh-CN.md) | EN - -## Masa.Contrib.StackSdks.Tsc - -effect: - -The tracking telemetry data adopts the Opentelemetry standard and integrates the OpenTelemetry SDK to report the telemetry tracking data to the OpenTelemetry-Collector collector, and then export and store the collected data Logging, Tracing, and Metrics through the Exporter - -Example: - - -```C# -Install-Package Masa.Contrib.StackSdks.Tsc -``` - -how to use: - - -```c# -// create and config ResourceBuilder instance -var resources = ResourceBuilder.CreateDefault(); -resources.AddMasaService(new MasaObservableOptions -{ - ServiceName = "example.api" -}); - -//metrics -builder.Services.AddMasaMetrics(builder => { - builder.SetResourceBuilder(resources); - builder.AddOtlpExporter(); -}); - -//trcaing -builder.Services.AddMasaTracing(options => -{ - //api exclude swagger and healthy request - options.AspNetCoreInstrumentationOptions.AppendDefaultFilter(options); - - //blazor exclude blazor resources request - //options.AspNetCoreInstrumentationOptions.AppendBlazorFilter(options); - - options.BuildTraceCallback = builder => - { - builder.SetResourceBuilder(resources); - builder.AddOtlpExporter(); - }; -}); - -//logging -builder.Logging.AddMasaOpenTelemetry(builder => -{ - builder.SetResourceBuilder(resources); - builder.AddOtlpExporter(); -}); - -``` diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/README.zh-CN.md b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/README.zh-CN.md deleted file mode 100644 index 76f1c5a14..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/README.zh-CN.md +++ /dev/null @@ -1,56 +0,0 @@ -中 | [EN](README.md) - -## Masa.Contrib.StackSdks.Tsc - -作用: - -追踪遥测数据采用Opentelemetry标准,并集成了OpenTelemetry SDK,将遥测追踪数据上报到OpenTelemetry-Collector采集器, -再将采集数据Logging、Tracing和Metrics经过Exporter导出存储 - -用例: - -```C# -Install-Package Masa.Contrib.StackSdks.Tsc -``` - -如何使用: - -```c# - -// create and config ResourceBuilder instance -var resources = ResourceBuilder.CreateDefault(); -resources.AddMasaService(new MasaObservableOptions -{ - ServiceName = "example.api" -}); - -//metrics -builder.Services.AddMasaMetrics(builder => { - builder.SetResourceBuilder(resources); - builder.AddOtlpExporter(); -}); - -//trcaing -builder.Services.AddMasaTracing(options => -{ - //api exclude swagger and healthy request - options.AspNetCoreInstrumentationOptions.AppendDefaultFilter(options); - - //blazor exclude blazor resources request - //options.AspNetCoreInstrumentationOptions.AppendBlazorFilter(options); - - options.BuildTraceCallback = builder => - { - builder.SetResourceBuilder(resources); - builder.AddOtlpExporter(); - }; -}); - -//logging -builder.Logging.AddMasaOpenTelemetry(builder => -{ - builder.SetResourceBuilder(resources); - builder.AddOtlpExporter(); -}); - -``` diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Service/LogService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Service/LogService.cs deleted file mode 100644 index 06bd72690..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Service/LogService.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Service; - -public class LogService : ILogService -{ - private readonly ICaller _caller; - internal const string AGGREGATE_URI = "/api/log/aggregate"; - internal const string LATEST_URI = "/api/log/latest"; - internal const string MAPPING_URI = "/api/log/mapping"; - - public LogService(ICaller caller) - { - _caller = caller; - } - - public async Task GetAggregationAsync(SimpleAggregateRequestDto query) - { - var str = await _caller.GetByBodyAsync(AGGREGATE_URI, query); - if (string.IsNullOrEmpty(str)) - return default!; - if(str is TResult t) - return t; - return JsonSerializer.Deserialize(str)!; - } - - public async Task> GetMappingAsync() - { - return (await _caller.GetAsync>(MAPPING_URI))!; - } - - public async Task GetLatestAsync(LogLatestRequest query) - { - return (await _caller.GetByBodyAsync(LATEST_URI, query))!; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Service/MetricService.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Service/MetricService.cs deleted file mode 100644 index 329a236f2..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/Service/MetricService.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Service; - -internal class MetricService : IMetricService -{ - private readonly ICaller _caller; - internal const string RANGEVALUES_URL = "/api/metric/range-values"; - internal const string NAMES_URI = "/api/metric/names"; - internal const string LABELVALUES_URI = "/api/metric/label-values"; - - public MetricService(ICaller caller) - { - _caller = caller; - } - - public async Task> GetNamesAsync(IEnumerable? match = null) - { - string param = default!; - if (match != null && match.Any()) - { - param = string.Join(',', match); - } - return (await _caller.GetAsync>(NAMES_URI, new Dictionary { { "match", param } }))!; - } - - public async Task>> GetLabelValuesAsync(LableValuesRequest query) - { - var data = await _caller.GetByBodyAsync>>>(LABELVALUES_URI, query); - if (data == null || !data.ContainsKey(query.Match)) - return new Dictionary>(); - - return data[query.Match]; - } - - public async Task GetValuesAsync(ValuesRequest query) - { - if (query.Lables != null && !string.IsNullOrEmpty(query.Match)) - { - query.Match = $"{query.Match}{{{string.Join(',', query.Lables)}}}"; - } - - return (await _caller.GetByBodyAsync(RANGEVALUES_URL, query))!; - } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/TscClient.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/TscClient.cs deleted file mode 100644 index d207e21cb..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/TscClient.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -[assembly: InternalsVisibleTo("Masa.Contrib.StackSdks.Tsc.Tests")] -namespace Masa.Contrib.StackSdks.Tsc; - -internal class TscClient : ITscClient -{ - public TscClient(ICaller caller) - { - LogService = new LogService(caller); - MetricService = new MetricService(caller); - } - - public ILogService LogService { get; } - - public IMetricService MetricService { get; } -} diff --git a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/_Imports.cs b/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/_Imports.cs deleted file mode 100644 index e245c734d..000000000 --- a/src/Contrib/StackSdks/Masa.Contrib.StackSdks.Tsc/_Imports.cs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Data; -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Tsc; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Log; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Model; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Model.Aggregate; -global using Masa.BuildingBlocks.StackSdks.Tsc.Model; -global using Masa.BuildingBlocks.StackSdks.Tsc.Service; -global using Masa.Contrib.StackSdks.Tsc; -global using Masa.Contrib.StackSdks.Tsc.Service; -global using System.Runtime.CompilerServices; -global using System.Text; -global using System.Text.Json; diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/AlarmRuleServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/AlarmRuleServiceTest.cs deleted file mode 100644 index 5d3bdd31f..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/AlarmRuleServiceTest.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Alert.Tests; - -[TestClass] -public class AlarmRuleServiceTest -{ - [TestMethod] - public async Task TestCreateAsync() - { - var options = new AlarmRuleUpsertModel(); - var requestUri = $"api/v1/AlarmRules"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, options, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var messageTaskService = new Mock(caller.Object); - var result = await messageTaskService.Object.CreateAsync(options); - caller.Verify(provider => provider.PostAsync(requestUri, options, default), Times.Once); - Assert.AreNotEqual(Guid.Empty, result); - } - - [TestMethod] - public async Task TestUpdateAsync() - { - Guid id = Guid.NewGuid(); - var options = new AlarmRuleUpsertModel(); - var requestUri = $"api/v1/AlarmRules/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, options, true, default)).Verifiable(); - var service = new Mock(caller.Object); - await service.Object.UpdateAsync(id, options); - caller.Verify(provider => provider.PutAsync(requestUri, options, true, default), Times.Once); - } - - [TestMethod] - public async Task TestDeleteAsync() - { - Guid id = Guid.NewGuid(); - var requestUri = $"api/v1/AlarmRules/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.DeleteAsync(requestUri, null, true, default)).Verifiable(); - var service = new Mock(caller.Object); - await service.Object.DeleteAsync(id); - caller.Verify(provider => provider.DeleteAsync(requestUri, null, true, default), Times.Once); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/AlertClientTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/AlertClientTest.cs deleted file mode 100644 index 22b10dbf5..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/AlertClientTest.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Alert.Tests; - -[TestClass] -public class AlertClientTest -{ - [TestMethod] - public void TestAddAlertClient() - { - var services = new ServiceCollection(); - services.AddAlertClient("https://localhost:19701"); - var mcClient = services.BuildServiceProvider().GetRequiredService(); - - Assert.IsNotNull(mcClient); - } - - [TestMethod] - public void TestAddAlertClientShouldThrowArgumentNullException() - { - var services = new ServiceCollection(); - Assert.ThrowsException(() => services.AddAlertClient(alertServiceBaseAddress: null!)); - } - - [TestMethod] - public void TestAddAlertClientShouldThrowArgumentNullException2() - { - var services = new ServiceCollection(); - Assert.ThrowsException(() => services.AddAlertClient(callerBuilder: null!)); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/Masa.Contrib.StackSdks.Alert.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/Masa.Contrib.StackSdks.Alert.Tests.csproj deleted file mode 100644 index 6add55b28..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/Masa.Contrib.StackSdks.Alert.Tests.csproj +++ /dev/null @@ -1,28 +0,0 @@ - - - - enable - false - true - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/Usings.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/Usings.cs deleted file mode 100644 index e5d6f2da1..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/Usings.cs +++ /dev/null @@ -1,4 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Microsoft.VisualStudio.TestTools.UnitTesting; \ No newline at end of file diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/_Imports.cs deleted file mode 100644 index 1237e7b4f..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Alert.Tests/_Imports.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.StackSdks.Alert; -global using Masa.BuildingBlocks.StackSdks.Alert.Model; -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.Contrib.StackSdks.Alert.Service; -global using Microsoft.Extensions.DependencyInjection; -global using Moq; -global using System; -global using System.Threading.Tasks; diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/AuthClientTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/AuthClientTest.cs deleted file mode 100644 index 80febaaae..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/AuthClientTest.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Tests; - -[TestClass] -public class AuthClientTest -{ - [TestMethod] - public void TestAddAuthClient() - { - var services = new ServiceCollection(); - services.AddMasaIdentity(); - services.AddAuthClient("https://localhost:18102", new()); - var authClient = services.BuildServiceProvider().GetRequiredService(); - - Assert.IsNotNull(authClient); - } - - [TestMethod] - public void TestAddAuthClientNoAddMasaIdentity() - { - var services = new ServiceCollection(); - Assert.ThrowsException(() => services.AddAuthClient("https://localhost:18102", new()), - "Please add IMultiEnvironmentUserContext first."); - } - - [TestMethod] - public void TestAddAuthClientShouldThrowArgumentNullException() - { - var services = new ServiceCollection(); - Assert.ThrowsException(() => services.AddAuthClient(authServiceBaseAddress: null!, new())); - } -} - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/CustomLoginServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/CustomLoginServiceTest.cs deleted file mode 100644 index 59e2934fa..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/CustomLoginServiceTest.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Tests; - -[TestClass] -public class CustomLoginServiceTest -{ - [TestMethod] - public async Task TestGetCustomLoginByClientIdAsync() - { - var data = new CustomLoginModel(); - string clientId = Guid.NewGuid().ToString(); - var requestUri = $"api/sso/customLogin/getByClientId"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var customLoginService = new CustomLoginService(caller.Object); - var result = await customLoginService.GetCustomLoginByClientIdAsync("test", clientId); - caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/LoginServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/LoginServiceTest.cs deleted file mode 100644 index c63ba55ca..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/LoginServiceTest.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Tests; - -[TestClass] -public class LoginServiceTest -{ - private Mock _mockHandler = new(); - private LoginService? _loginService; - - [TestInitialize] - public void Initialized() - { - var httpClientFactory = new Mock(); - var httpClient = new HttpClient(_mockHandler.Object); - httpClient.BaseAddress = new Uri("http://localhost"); - httpClientFactory.Setup(provider => provider.CreateClient(Constants.DEFAULT_SSO_CLIENT_NAME)).Returns(httpClient); - _loginService = new LoginService(httpClientFactory.Object); - } - - [TestMethod] - public async Task TestLoginByPasswordAsync() - { - SetTestData(new { }); - var login = new LoginByPasswordModel - { - ClientId = "test_client_id", - ClientSecret = "test_client_secret", - Account = "guest", - Password = "guest123" - }; - - var result = await _loginService!.LoginByPasswordAsync(login); - Assert.IsNotNull(result); - } - - private void SetTestData(object result, HttpStatusCode httpStatusCode = HttpStatusCode.OK) - { - _mockHandler.Protected() - .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) - .ReturnsAsync(new HttpResponseMessage() - { - StatusCode = httpStatusCode, - Content = new StringContent(JsonSerializer.Serialize(result)) - }); - } -} - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/Masa.Contrib.StackSdks.Auth.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/Masa.Contrib.StackSdks.Auth.Tests.csproj deleted file mode 100644 index 3ee606062..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/Masa.Contrib.StackSdks.Auth.Tests.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - enable - enable - false - true - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/PermissionServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/PermissionServiceTest.cs deleted file mode 100644 index 61258ed1e..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/PermissionServiceTest.cs +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Tests; - -[TestClass] -public class PermissionServiceTest -{ - [TestMethod] - [DataRow("app1")] - public async Task TestGetMenusAsync(string appId) - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var data = new List(); - var requestUri = $"api/permission/menus?appId={appId}&userId={userId}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var permissionService = new PermissionService(caller.Object, userContext.Object); - var result = await permissionService.GetMenusAsync(appId); - userContext.Verify(user => user.GetUserId(), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - [DataRow("app1", "code")] - public async Task TestAuthorizedAsync(string appId, string code) - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var data = false; - var requestUri = $"api/permission/authorized?code={code}&userId={userId}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var permissionService = new PermissionService(caller.Object, userContext.Object); - var result = await permissionService.AuthorizedAsync(appId, code); - caller.Verify(provider => provider.GetAsync(It.IsAny(), default), Times.Once); - } - - [TestMethod] - [DataRow("app1")] - public async Task TestGetElementPermissionsAsync(string appId) - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var data = new List(); - var requestUri = $"api/permission/element-permissions?appId={appId}&userId={userId}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var permissionService = new PermissionService(caller.Object, userContext.Object); - var result = await permissionService.GetElementPermissionsAsync(appId); - caller.Verify(provider => provider.GetAsync>(It.IsAny(), default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - [DataRow("225082D3-CC88-48D2-3C27-08DA3ED8F4B7")] - public async Task TestGetFavoriteMenuListAsync(string menuId) - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var data = new List(); - var requestUri = $"api/permission/menu-favorite-list?userId={userId}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var permissionService = new PermissionService(caller.Object, userContext.Object); - var result = await permissionService.GetFavoriteMenuListAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - [DataRow("225082D3-CC88-48D2-3C27-08DA3ED8F4B7")] - public async Task TestAddFavoriteMenuAsync(string menuId) - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var requestUri = $"api/permission/addFavoriteMenu?permissionId={Guid.Parse(menuId)}&userId={userId}"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, null, true, default)).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var permissionService = new PermissionService(caller.Object, userContext.Object); - var result = await permissionService.AddFavoriteMenuAsync(Guid.Parse(menuId)); - caller.Verify(provider => provider.PutAsync(requestUri, null, true, default), Times.Once); - Assert.IsTrue(result); - } - - [TestMethod] - [DataRow("225082D3-CC88-48D2-3C27-08DA3ED8F4B7")] - public async Task TestRemoveFavoriteMenuAsync(string menuId) - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var requestUri = $"api/permission/removeFavoriteMenu?permissionId={Guid.Parse(menuId)}&userId={userId}"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, null, true, default)).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var permissionService = new PermissionService(caller.Object, userContext.Object); - var result = await permissionService.RemoveFavoriteMenuAsync(Guid.Parse(menuId)); - caller.Verify(provider => provider.PutAsync(requestUri, null, true, default), Times.Once); - Assert.IsTrue(result); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/ProjectServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/ProjectServiceTest.cs deleted file mode 100644 index 17e037fc4..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/ProjectServiceTest.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Tests; - -[TestClass] -public class ProjectServiceTest -{ - [TestMethod] - public async Task TestGetGlobalNavigationsAsync() - { - var data = new List() - { - new ProjectModel() - }; - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var requestUri = $"api/project/navigations?userId={userId}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - userContext.SetupGet(user => user.Environment).Returns("development"); - var projectService = new Mock(caller.Object, userContext.Object); - var result = await projectService.Object.GetGlobalNavigations(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - Assert.IsTrue(result.Count == 1); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/SsoClientTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/SsoClientTest.cs deleted file mode 100644 index 62fd52c49..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/SsoClientTest.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Tests; - -[TestClass] -public class SsoClientTest -{ - [TestMethod] - public void TestAddSsoClient() - { - var services = new ServiceCollection(); - services.AddSsoClient("https://localhost:18102"); - var ssoClient = services.BuildServiceProvider().GetRequiredService(); - - Assert.IsNotNull(ssoClient); - } -} - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/SubjectServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/SubjectServiceTest.cs deleted file mode 100644 index af8a50a3a..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/SubjectServiceTest.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Tests; - -[TestClass] -public class SubjectServiceTest -{ - [TestMethod] - public async Task TestGetListAsync() - { - var data = new List() - { - new SubjectModel() - }; - string filter = "test"; - var requestUri = $"api/subject/getList"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var subjectService = new Mock(caller.Object); - var result = await subjectService.Object.GetListAsync(filter); - caller.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result.Count == 1); - } -} - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/TeamServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/TeamServiceTest.cs deleted file mode 100644 index 9dd6bed8b..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/TeamServiceTest.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Tests; - -[TestClass] -public class TeamServiceTest -{ - [TestMethod] - public async Task TestGetDetailAsync() - { - var data = new TeamDetailModel(); - Guid teamId = Guid.NewGuid(); - var requestUri = $"api/team/detail"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userContext = new Mock(); - var teamService = new Mock(caller.Object, userContext.Object); - var result = await teamService.Object.GetDetailAsync(teamId); - caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestGetAllAsync() - { - var data = new List(); - var requestUri = $"api/team/list?{IsolationConsts.ENVIRONMENT}=test"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var userContext = new Mock(); - var teamService = new Mock(caller.Object, userContext.Object); - var result = await teamService.Object.GetAllAsync("test"); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestGetUserTeamsAsync() - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var data = new List(); - var requestUri = $"api/team/list?userId={userId}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var teamService = new Mock(caller.Object, userContext.Object); - var result = await teamService.Object.GetUserTeamsAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - Assert.IsTrue(result is not null); - } -} - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/ThirdPartyIdpServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/ThirdPartyIdpServiceTest.cs deleted file mode 100644 index be3414006..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/ThirdPartyIdpServiceTest.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Auth.Tests; - -[TestClass] -public class ThirdPartyIdpServiceTest -{ - [TestMethod] - public async Task TestGetAllAsync() - { - var data = new List(); - var requestUri = $"api/thirdPartyIdp/getAll"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var multilevelCacheClient = new Mock(); - var thirdPartyIdpService = new ThirdPartyIdpService(caller.Object, multilevelCacheClient.Object); - var result = await thirdPartyIdpService.GetAllAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - } - - [TestMethod] - public async Task TestGetAllFromCacheAsync() - { - var data = new List(); - var requestUri = $"api/thirdPartyIdp/getAll"; - var caller = new Mock(); - var multilevelCacheClient = new Mock(); - multilevelCacheClient.Setup(provider => provider.GetAsync>(CacheKeyConsts.ALL_THIRD_PARTY_IDP, default)).ReturnsAsync(data).Verifiable(); - var thirdPartyIdpService = new ThirdPartyIdpService(caller.Object, multilevelCacheClient.Object); - var result = await thirdPartyIdpService.GetAllFromCacheAsync(); - multilevelCacheClient.Verify(provider => provider.GetAsync>(CacheKeyConsts.ALL_THIRD_PARTY_IDP, default), Times.Once); - } - - [TestMethod] - public async Task TestGetLdapOptionsAsync() - { - var requestUri = $"api/thirdPartyIdp/ldapOptions"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).Verifiable(); - var multilevelCacheClient = new Mock(); - var thirdPartyIdpService = new ThirdPartyIdpService(caller.Object, multilevelCacheClient.Object); - var result = await thirdPartyIdpService.GetLdapOptionsAsync("ldap"); - caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/UserServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/UserServiceTest.cs deleted file mode 100644 index d86ca1d99..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/UserServiceTest.cs +++ /dev/null @@ -1,780 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -using Moq; - -namespace Masa.Contrib.StackSdks.Auth.Tests; - -[TestClass] -public class UserServiceTest -{ - [TestMethod] - public async Task TestAddAsync() - { - var addUser = new AddUserModel(); - var user = new UserModel(); - var requestUri = $"api/user/external"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, addUser, default)).ReturnsAsync(user).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.AddAsync(addUser); - caller.Verify(provider => provider.PostAsync(requestUri, addUser, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestUpsertThirdPartyAsync() - { - var addUser = new UpsertThirdPartyUserModel() - { - Id = Guid.Parse("125082D3-CC88-48D2-3C27-08DA3ED8F4B7"), - ThridPartyIdentity = "ThridPartyIdentity", - }; - var user = new UserModel(); - var requestUri = $"api/thirdPartyUser/upsertThirdPartyUserExternal"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, addUser, default)).ReturnsAsync(user).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.UpsertThirdPartyUserAsync(addUser); - caller.Verify(provider => provider.PostAsync(requestUri, addUser, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestRemoveThirdPartyUserByThridPartyIdentityAsync() - { - var parameter = new { ThridPartyIdentity = "ThridPartyIdentity" }; - var requestUri = $"api/thirdPartyUser/RemoveByThridPartyIdentity"; - var caller = new Mock(); - caller.Setup(provider => provider.DeleteAsync(requestUri, parameter, true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.RemoveThirdPartyUserByThridPartyIdentityAsync(parameter.ThridPartyIdentity); - caller.Verify(provider => provider.DeleteAsync(requestUri, parameter, false, default), Times.Never); - } - - [TestMethod] - public async Task TestRemoveThirdPartyUserAsync() - { - var parameter = new { id = Guid.Parse("125082D3-CC88-48D2-3C27-08DA3ED8F4B7") }; - var requestUri = $"api/thirdPartyUser/RemoveThirdPartyUser"; - var caller = new Mock(); - caller.Setup(provider => provider.DeleteAsync(requestUri, parameter, true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.RemoveThirdPartyUserAsync(parameter.id); - caller.Verify(provider => provider.DeleteAsync(requestUri, parameter, true, default), Times.Never); - } - - [TestMethod] - public async Task TestAddThirdPartyUserAsync() - { - var addUser = new AddThirdPartyUserModel(); - var user = new UserModel(); - var requestUri = $"api/thirdPartyUser/addThirdPartyUser?whenExistReturn={true}"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, addUser, default)).ReturnsAsync(user).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.AddThirdPartyUserAsync(addUser); - caller.Verify(provider => provider.PostAsync(requestUri, addUser, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestGetThirdPartyUserAsync() - { - var data = new UserModel(); - var model = new GetThirdPartyUserModel(); - var requestUri = $"api/thirdPartyUser"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, model, default)).ReturnsAsync(data).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.GetThirdPartyUserAsync(model); - caller.Verify(provider => provider.GetAsync(requestUri, model, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task UpsertAsync() - { - var upsertUser = new UpsertUserModel(); - var user = new UserModel(); - var requestUri = $"api/user/upsertExternal"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, upsertUser, default)).ReturnsAsync(user).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.UpsertAsync(upsertUser); - caller.Verify(provider => provider.PostAsync(requestUri, upsertUser, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestGetListByDepartmentAsync() - { - var data = new List() - { - new StaffModel() - }; - Guid departmentId = Guid.NewGuid(); - var requestUri = $"api/staff/getListByDepartment"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.GetListByDepartmentAsync(departmentId); - caller.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestGetListByTeamAsync() - { - var data = new List() - { - new StaffModel() - }; - Guid teamId = Guid.NewGuid(); - var requestUri = $"api/staff/getListByTeam"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.GetListByTeamAsync(teamId); - caller.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestGetListByRoleAsync() - { - var data = new List() - { - new UserModel() - }; - Guid roleId = Guid.NewGuid(); - var requestUri = $"api/user/getListByRole"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.GetListByRoleAsync(roleId); - caller.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestGetTotalByDepartmentAsync() - { - long data = 10; - Guid departmentId = Guid.NewGuid(); - var requestUri = $"api/staff/getTotalByDepartment"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.GetTotalByDepartmentAsync(departmentId); - caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result == data); - } - - [TestMethod] - public async Task TestGetTotalByByRoleAsync() - { - long data = 10; - Guid roleId = Guid.NewGuid(); - var requestUri = $"api/staff/getTotalByRole"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.GetTotalByRoleAsync(roleId); - caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result == data); - } - - [TestMethod] - public async Task TestGetTotalByTeamAsync() - { - long data = 10; - Guid teamId = Guid.NewGuid(); - var requestUri = $"api/staff/getTotalByTeam"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.GetTotalByTeamAsync(teamId); - caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result == data); - } - - [TestMethod] - [DataRow("account", "123456")] - public async Task TestValidateCredentialsByAccountAsync(string account, string password) - { - var data = new UserModel(); - Guid departmentId = Guid.NewGuid(); - var requestUri = $"api/user/validateByAccount"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, It.IsAny(), default)) - .ReturnsAsync(data).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.ValidateAccountAsync(new ValidateAccountModel - { - Account = account, - Password = password, - Environment = "Develop" - }); - caller.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), default), Times.Once); - } - - [TestMethod] - [DataRow("authount")] - public async Task TestFindByAccountAsync(string account) - { - var data = new UserModel(); - var requestUri = $"api/user/byAccount"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.GetByAccountAsync(account); - caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - [DataRow("15168440403")] - public async Task TestFindByPhoneNumberAsync(string phoneNumber) - { - var data = new UserModel() - { - PhoneNumber = phoneNumber - }; - var requestUri = $"api/user/byPhoneNumber"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.GetByPhoneNumberAsync(phoneNumber); - caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result is not null && result.PhoneNumber == data.PhoneNumber); - } - - [TestMethod] - [DataRow("824255786@qq.com")] - public async Task TestFindByEmailAsync(string email) - { - var data = new UserModel(); - var requestUri = $"api/user/byEmail"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.GetByEmailAsync(email); - caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result is not null && result.Email == data.Email); - } - - [TestMethod] - public async Task TestGetCurrentUserAsync() - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var data = new UserModel(); - var requestUri = $"api/user/byId/{userId}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = GetUserService(caller, userContext); - var result = await userService.GetCurrentUserAsync(); - caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestGetCurrentStaffAsync() - { - var userId = Guid.NewGuid(); - var data = new StaffDetailModel(); - var requestUri = $"api/staff/getDetailByUserId"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = GetUserService(caller, userContext); - var result = await userService.GetCurrentStaffAsync(); - caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - [DataRow("masa-auth-web-admin", "https://www.baidu.com/")] - public async Task TestVisitedAsync(string appId, string url) - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var requestUri = $"api/user/visit"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, new { UserId = userId, Url = url }, true, default)).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = GetUserService(caller, userContext); - await userService.VisitedAsync(appId, url); - caller.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), true, default), Times.Once); - } - - [TestMethod] - public async Task TestGetVisitedListAsync() - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var data = new List() { - new UserVisitedModel - { - Name="baidu", - Url = "https://www.baidu.com/" - } - }; - var requestUri = $"api/user/visitedList"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = GetUserService(caller, userContext); - var result = await userService.GetVisitedListAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestUpdatePasswordAsync() - { - var user = new UpdateUserPasswordModel - { - Id = Guid.NewGuid(), - NewPassword = "masa123", - OldPassword = "masa123" - }; - var requestUri = $"api/user/password"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, user, true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.UpdatePasswordAsync(user); - caller.Verify(provider => provider.PutAsync(requestUri, user, true, default), Times.Once); - } - - [TestMethod] - public async Task TestUpdateUserAvatarAsync() - { - var user = new UpdateUserAvatarModel(default, ""); - var requestUri = $"api/user/avatar"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, user, true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.UpdateUserAvatarAsync(user); - caller.Verify(provider => provider.PutAsync(requestUri, user, true, default), Times.Once); - } - - [TestMethod] - public async Task TestUpdateStaffAvatarAsync() - { - var staff = new UpdateStaffAvatarModel(default, ""); - var requestUri = $"api/staff/updateAvatar"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, staff, true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.UpdateStaffAvatarAsync(staff); - caller.Verify(provider => provider.PutAsync(requestUri, staff, true, default), Times.Once); - } - - [TestMethod] - public async Task SendMsgCodeAsync() - { - var code = new SendMsgCodeModel(); - var requestUri = $"api/message/sms"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, code, true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.SendMsgCodeAsync(code); - caller.Verify(provider => provider.PostAsync(requestUri, code, true, default), Times.Once); - } - - [TestMethod] - public async Task TestVerifyMsgCodeAsync() - { - var code = new VerifyMsgCodeModel(); - var requestUri = $"api/user/verifyMsgCode"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, code, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.VerifyMsgCodeAsync(code); - caller.Verify(provider => provider.PostAsync(requestUri, code, default), Times.Once); - } - - [TestMethod] - public async Task TestUpdateUserPhoneNumberAsync() - { - var user = new UpdateUserPhoneNumberModel(Guid.NewGuid(), "15168440403", "123453"); - var requestUri = $"api/user/phoneNumber"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, user, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.UpdatePhoneNumberAsync(user); - caller.Verify(provider => provider.PutAsync(requestUri, user, default), Times.Once); - } - - [TestMethod] - public async Task TestLoginByPhoneNumberAsync() - { - var login = new LoginByPhoneNumberModel(); - var user = new UserModel(); - var requestUri = $"api/user/loginByPhoneNumber"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, login, default)).ReturnsAsync(user).Verifiable(); - var userService = GetUserService(caller); - await userService.LoginByPhoneNumberAsync(login); - caller.Verify(provider => provider.PostAsync(requestUri, login, default), Times.Once); - } - - [TestMethod] - public async Task TestRemoveUserRolesAsync() - { - var user = new RemoveUserRolesModel(); - var requestUri = $"api/user/userRoles"; - var caller = new Mock(); - caller.Setup(provider => provider.DeleteAsync(requestUri, user, true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.RemoveUserRolesAsync(user); - caller.Verify(provider => provider.DeleteAsync(requestUri, user, true, default), Times.Once); - } - - - [TestMethod] - public async Task TestDisableUserAsync() - { - var user = new DisableUserModel("account"); - var requestUri = $"api/user/disable"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, user, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.DisableAsync(user); - caller.Verify(provider => provider.PutAsync(requestUri, user, default), Times.Once); - } - - [TestMethod] - public async Task TestUpdateBasicInfoAsync() - { - var user = new UpdateUserBasicInfoModel - { - Id = Guid.NewGuid(), - DisplayName = "test", - Gender = GenderTypes.Male, - }; - var requestUri = $"api/user/basicInfo"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, user, true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.UpdateBasicInfoAsync(user); - caller.Verify(provider => provider.PutAsync(requestUri, user, true, default), Times.Once); - } - - [TestMethod] - public async Task TestUpdateStaffBasicInfoAsync() - { - var staff = new UpdateStaffBasicInfoModel - { - UserId = Guid.NewGuid(), - DisplayName = "test", - Gender = GenderTypes.Male, - PhoneNumber = "15168440403" - }; - var requestUri = $"api/staff/updateBasicInfo"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, staff, true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.UpdateStaffBasicInfoAsync(staff); - caller.Verify(provider => provider.PutAsync(requestUri, staff, true, default), Times.Once); - } - - [TestMethod] - public async Task GetUserPortraitsAsync() - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var userPortraits = new List { - new UserModel - { - Id = Guid.NewGuid(), - DisplayName = "DisplayName", - Account = "Account", - Name = "Name", - Avatar = "Avatar" - } - }; - var requestUri = $"api/user/byIds"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync>(requestUri, new Guid[] { userId }, default)) - .ReturnsAsync(userPortraits).Verifiable(); - var userService = GetUserService(caller); - var data = await userService.GetListByIdsAsync(userId); - caller.Verify(provider => provider.PostAsync>(requestUri, new Guid[] { userId }, default), Times.Once); - Assert.IsTrue(data.Count == 1); - } - - [TestMethod] - [DataRow("masa-auth")] - public async Task TestIntGetUserSystemDataAsync(string systemId) - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var data = 1; - var requestUri = $"api/user/systemData/byIds"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync>(requestUri, It.IsAny(), default)) - .ReturnsAsync(new Dictionary() { { userId, data.ToString() } }).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = GetUserService(caller, userContext); - var result = await userService.GetSystemDataAsync(systemId); - Assert.IsTrue(result == 1); - } - - [TestMethod] - [DataRow("masa-auth")] - public async Task TestObjectGetUserSystemDataAsync(string systemId) - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var data = new SystemData - { - Name = "name", - Value = "value" - }; - var requestUri = $"api/user/systemData/byIds"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync>(requestUri, It.IsAny(), default)) - .ReturnsAsync(new Dictionary() { { userId, JsonSerializer.Serialize(data) } }).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = GetUserService(caller, userContext); - var result = await userService.GetSystemDataAsync(systemId); - Assert.IsTrue(result is not null); - } - - [TestMethod] - [DataRow("masa-auth")] - public async Task TestIntUpsertSystemDataAsync(string systemId) - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var requestUri = $"api/user/systemData"; - var value = 1; - var data = new { UserId = userId, SystemId = systemId, Data = JsonSerializer.Serialize(value) }; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, data, true, default)).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = GetUserService(caller, userContext); - await userService.UpsertSystemDataAsync(systemId, value); - caller.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), true, default), Times.Once); - } - - [TestMethod] - [DataRow("masa-auth")] - public async Task TestObjectSaveUserSystemDataAsync(string systemId) - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var requestUri = $"api/user/systemData"; - var value = new SystemData - { - Name = "name", - Value = "value" - }; - var data = new { UserId = userId, SystemId = systemId, Data = JsonSerializer.Serialize(value) }; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, data, true, default)).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = GetUserService(caller, userContext); - await userService.UpsertSystemDataAsync(systemId, value); - caller.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), true, default), Times.Once); - } - - [TestMethod] - public async Task TestGetListByAccountAsync() - { - var data = new List() - { - new UserSimpleModel(Guid.NewGuid(), "account", "displayName") - }; - var accounts = new List { "account" }; - var requestUri = $"api/user/listByAccount"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.GetListByAccountAsync(accounts); - caller.Verify(provider => provider.GetAsync>(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestSetCurrentTeamAsyncAsync() - { - var userId = Guid.Parse("A9C8E0DD-1E9C-474D-8FE7-8BA9672D53D1"); - var teamId = Guid.Parse("A659E0DD-1E9C-474D-8FE7-8BA6592D53D1"); - var requestUri = $"api/staff/UpdateCurrentTeam"; - var caller = new Mock(); - var data = new UpdateCurrentTeamModel - { - UserId = userId, - TeamId = teamId - }; - caller.Setup(provider => provider.PutAsync(requestUri, data, true, default)).Verifiable(); - var userContext = new Mock(); - userContext.Setup(user => user.GetUserId()).Returns(userId).Verifiable(); - var userService = GetUserService(caller, userContext); - await userService.SetCurrentTeamAsync(teamId); - caller.Verify(provider => provider.PutAsync(requestUri, It.IsAny(), true, default), Times.Once); - } - - [TestMethod] - public async Task TestSendEmailAsync() - { - var model = new SendEmailModel(); - var requestUri = $"api/message/email"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, model, true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.SendEmailAsync(model); - caller.Verify(provider => provider.PostAsync(requestUri, model, true, default), Times.Once); - } - - [TestMethod] - public async Task TestRegisterByEmailAsyncegisterAsync() - { - var model = new RegisterByEmailModel(); - var requestUri = $"api/user/register"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, model, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.RegisterByEmailAsync(model); - caller.Verify(provider => provider.PostAsync(requestUri, model, default), Times.Once); - } - - [TestMethod] - public async Task TestRegisterByPhoneAsync() - { - var model = new RegisterByPhoneModel(); - var requestUri = $"api/user/register"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, model, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.RegisterByPhoneAsync(model); - caller.Verify(provider => provider.PostAsync(requestUri, model, default), Times.Once); - } - - [TestMethod] - public async Task TestHasPasswordAsync() - { - var requestUri = $"api/user/hasPassword"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, It.IsAny(), default)).ReturnsAsync(true).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.HasPasswordAsync(); - caller.Verify(provider => provider.GetAsync(requestUri, It.IsAny(), default), Times.Once); - Assert.IsTrue(result is true); - } - - [TestMethod] - public async Task TestRegisterThirdPartyUserAsync() - { - var model = new RegisterThirdPartyUserModel(); - var user = new UserModel(); - var requestUri = $"api/thirdPartyUser/register"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, model, default)).ReturnsAsync(user).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.RegisterThirdPartyUserAsync(model); - caller.Verify(provider => provider.PostAsync(requestUri, model, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - [DataRow("develop", "13566668888")] - public async Task TestHasPhoneNumberInEnvAsync(string env, string phoneNumber) - { - var requestUri = $"api/user/HasPhoneNumberInEnv?env={env}&phoneNumber={phoneNumber}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)) - .ReturnsAsync(true).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.HasPhoneNumberInEnvAsync(env, phoneNumber); - Assert.IsTrue(result); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - } - - [TestMethod] - public async Task TestResetPasswordByEmailAsync() - { - var model = new ResetPasswordByEmailModel(); - var user = new UserModel(); - var requestUri = $"api/user/reset_password_by_email"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, model, default)).ReturnsAsync(true).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.ResetPasswordByEmailAsync(model); - caller.Verify(provider => provider.PostAsync(requestUri, model, default), Times.Once); - Assert.IsTrue(result); - } - - [TestMethod] - public async Task TestResetPasswordByPhoneAsync() - { - var model = new ResetPasswordByPhoneModel(); - var user = new UserModel(); - var requestUri = $"api/user/reset_password_by_phone"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, model, default)).ReturnsAsync(true).Verifiable(); - var userService = GetUserService(caller); - var result = await userService.ResetPasswordByPhoneAsync(model); - caller.Verify(provider => provider.PostAsync(requestUri, model, default), Times.Once); - Assert.IsTrue(result); - } - - [TestMethod] - public async Task TestRemoveAsync() - { - var model = new RemoveUserModel(default); - var caller = new Mock(); - caller.Setup(provider => provider.DeleteAsync("api/user", It.IsAny(), true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.RemoveAsync(default); - caller.Verify(provider => provider.DeleteAsync("api/user", It.IsAny(), true, default), Times.Once); - } - - [TestMethod] - public async Task TestBindRolesAsync() - { - var model = new BindUserRolesModel - { - Id = Guid.NewGuid(), - RoleCodes = new[] { "test_code" } - }; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync("api/user/bind_roles", model, true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.BindRolesAsync(model); - caller.Verify(provider => provider.PostAsync("api/user/bind_roles", model, true, default), Times.Once); - } - - [TestMethod] - public async Task TestUnbindRolesAsync() - { - var model = new UnbindUserRolesModel - { - Id = Guid.NewGuid(), - RoleCodes = new[] { "test_code" } - }; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync("api/user/unbind_roles", model, true, default)).Verifiable(); - var userService = GetUserService(caller); - await userService.UnbindRolesAsync(model); - caller.Verify(provider => provider.PostAsync("api/user/unbind_roles", model, true, default), Times.Once); - } - - static UserService GetUserService(Mock caller, Mock? userContext = null) - { - userContext ??= new Mock(); - var multilevelCacheClient = new Mock(); - return new UserService(caller.Object, userContext.Object, multilevelCacheClient.Object); - } -} - -class SystemData -{ - public string Name { get; set; } - public string Value { get; set; } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/_Imports.cs deleted file mode 100644 index c04e59f4f..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/_Imports.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Authentication.Identity; -global using Masa.BuildingBlocks.Caching; -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Auth; -global using Masa.BuildingBlocks.StackSdks.Auth.Contracts.Consts; -global using Masa.BuildingBlocks.StackSdks.Auth.Contracts.Enum; -global using Masa.BuildingBlocks.StackSdks.Auth.Contracts.Model; -global using Masa.BuildingBlocks.StackSdks.Isolation; -global using Masa.Contrib.StackSdks.Auth.Service; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.VisualStudio.TestTools.UnitTesting; -global using Moq; -global using Moq.Protected; -global using System.Net; -global using System.Text.Json; diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/Masa.Contrib.StackSdks.Config.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/Masa.Contrib.StackSdks.Config.Tests.csproj deleted file mode 100644 index a0008d9d7..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/Masa.Contrib.StackSdks.Config.Tests.csproj +++ /dev/null @@ -1,37 +0,0 @@ - - - - enable - enable - false - true - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - Always - - - - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/MasaStackConfigTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/MasaStackConfigTest.cs deleted file mode 100644 index 3cda76e79..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/MasaStackConfigTest.cs +++ /dev/null @@ -1,187 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -using Masa.BuildingBlocks.Configuration; -using Moq; - -namespace Masa.Contrib.StackSdks.Config.Tests; - -[TestClass] -public class MasaStackConfigTest -{ - private MasaStackConfig _stackConfig; - private Dictionary _config; - - [TestInitialize] - public void Initialize() - { - var builder = WebApplication.CreateBuilder(); - var configuration = builder.Configuration.AddJsonFile("appsettings.json", true, true).Build(); - _config = new Dictionary() - { - { MasaStackConfigConstant.VERSION, configuration.GetValue(MasaStackConfigConstant.VERSION) }, - { MasaStackConfigConstant.IS_DEMO, configuration.GetValue(MasaStackConfigConstant.IS_DEMO).ToString() }, - { MasaStackConfigConstant.DOMAIN_NAME, configuration.GetValue(MasaStackConfigConstant.DOMAIN_NAME) }, - { MasaStackConfigConstant.NAMESPACE, configuration.GetValue(MasaStackConfigConstant.NAMESPACE) }, - { MasaStackConfigConstant.CLUSTER, configuration.GetValue(MasaStackConfigConstant.CLUSTER) }, - { MasaStackConfigConstant.OTLP_URL, configuration.GetValue(MasaStackConfigConstant.OTLP_URL) }, - { MasaStackConfigConstant.REDIS, configuration.GetValue(MasaStackConfigConstant.REDIS) }, - { MasaStackConfigConstant.CONNECTIONSTRING, configuration.GetValue(MasaStackConfigConstant.CONNECTIONSTRING) }, - { MasaStackConfigConstant.MASA_STACK, configuration.GetValue(MasaStackConfigConstant.MASA_STACK) }, - { MasaStackConfigConstant.ELASTIC, configuration.GetValue(MasaStackConfigConstant.ELASTIC) }, - { MasaStackConfigConstant.ENVIRONMENT, configuration.GetValue(MasaStackConfigConstant.ENVIRONMENT) }, - { MasaStackConfigConstant.ADMIN_PWD, configuration.GetValue(MasaStackConfigConstant.ADMIN_PWD) }, - { MasaStackConfigConstant.DCC_SECRET, configuration.GetValue(MasaStackConfigConstant.DCC_SECRET) }, - { MasaStackConfigConstant.SUFFIX_IDENTITY, configuration.GetValue(MasaStackConfigConstant.SUFFIX_IDENTITY) } - }; - - Mock dccClient = new(); - - dccClient.Setup(client => client.GetAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), It.IsAny(), - It.IsAny>>()!)) - .ReturnsAsync(_config); - - _stackConfig = new MasaStackConfig(dccClient.Object, _config); - } - - [TestMethod] - public void TestGetAllServers() - { - var allServer = _stackConfig.GetAllService(); - - Assert.IsNotNull(allServer); - } - - [TestMethod] - public void TestGetDefaultDccOptions() - { - var dccOptions = MasaStackConfigUtils.GetDefaultDccOptions(_config, MasaStackProject.Auth, MasaStackApp.WEB); - - Assert.IsNotNull(dccOptions?.RedisOptions); - } - - [TestMethod] - public void TestGetAdminPwd() - { - Assert.IsNotNull(_stackConfig.AdminPwd); - } - - [TestMethod] - public void TestGetEnvironment() - { - var environment = _stackConfig.Environment; - - Assert.IsNotNull(environment); - } - - [TestMethod] - public void TestGetAllUINames() - { - var allUIs = _stackConfig.GetUIDomainPairs(); - - Assert.IsNotNull(allUIs); - } - - [TestMethod] - public void TestGetSsoDomain() - { - var ssoDomain = _stackConfig.GetSsoDomain(); - - Assert.IsNotNull(ssoDomain); - } - - [TestMethod] - public void TestGetPmDomain() - { - var pmDomain = _stackConfig.GetPmServiceDomain(); - - Assert.IsNotNull(pmDomain); - } - - [TestMethod] - public void TestGetAuthServiceDomain() - { - var authServiceDomain = _stackConfig.GetAuthServiceDomain(); - - Assert.IsNotNull(authServiceDomain); - } - - [TestMethod] - public void TestGetElasticModel() - { - var esModel = _stackConfig.ElasticModel; - - Assert.IsNotNull(esModel); - } - - [TestMethod] - public void TestGetVersion() - { - var version = _stackConfig.Version; - - Assert.IsNotNull(version); - } - - [TestMethod] - public void TestGetServiceId() - { - var pmServiceId = _stackConfig.GetServiceId(MasaStackProject.PM); - - Assert.AreEqual("pm-service", pmServiceId); - } - - [TestMethod] - public void TestGetWebId() - { - var pmWebId = _stackConfig.GetWebId(MasaStackProject.PM); - - Assert.AreEqual("pm-web", pmWebId); - } - - [TestMethod] - public void TestGetDefaultUserId() - { - var userId = _stackConfig.GetDefaultUserId(); - Assert.IsNotNull(userId); - - var userId2 = _stackConfig.GetDefaultUserId(); - Assert.AreEqual(userId, userId2); - } - - [TestMethod] - public void TestGetDefaultTeamId() - { - var teamId = _stackConfig.GetDefaultTeamId(); - Assert.IsNotNull(teamId); - - var teamId2 = _stackConfig.GetDefaultTeamId(); - Assert.AreEqual(teamId, teamId2); - } - - [TestMethod] - public void TestGetEsModel() - { - var es = _stackConfig.ElasticModel; - - Assert.IsTrue(es is not null && es.Nodes.Any()); - } - - [TestMethod] - public void TestGetAuthConnectionString() - { - var suffixIdentity = _stackConfig.SuffixIdentity; - - Assert.AreEqual("dev", suffixIdentity); - } - - [TestMethod] - public void TestHasAlert() - { - var result = _stackConfig.HasAlert(); - - Assert.AreEqual(true, result); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/_Imports.cs deleted file mode 100644 index a615fe77e..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/_Imports.cs +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.StackSdks.Config; -global using Microsoft.AspNetCore.Builder; -global using Microsoft.Extensions.Configuration; -global using Microsoft.VisualStudio.TestTools.UnitTesting; - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/appsettings.json b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/appsettings.json deleted file mode 100644 index f0a1bddb6..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Config.Tests/appsettings.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "MASA_CLUSTER": "Default", - "CONNECTIONSTRING": "{\"Server\": \"masastack-sqlserver.masastack\", \"port\": 1433,\"Database\":\"\",\"UserId\": \"sa\",\"Password\":\"p@ssw0rd\"}", - "DOMAIN_NAME": "masastack.com", - "ELASTIC": "{\"Nodes\": [\"masastack-es.masastack\"],\"Index\": \"user_dev\"}", - "IS_DEMO": "true", - "MASA_STACK": "[{\"id\":\"pm\",\"service\":{\"id\":\"pm-service\",\"domain\":\"pm-staging.masastack\"},\"web\":{\"id\":\"pm-web\",\"domain\":\"pm.masastack.com\"}},{\"id\":\"dcc\",\"service\":{\"id\":\"dcc-service\",\"domain\":\"dcc-staging.masastack\"},\"web\":{\"id\":\"dcc-web\",\"domain\":\"\"}},{\"id\":\"tsc\",\"service\":{\"id\":\"tsc-service\",\"domain\":\"\"},\"web\":{\"id\":\"tsc-web\",\"domain\":\"\"}},{\"id\":\"alert\",\"service\":{\"id\":\"alert-service\",\"domain\":\"\"},\"web\":{\"id\":\"alert-web\",\"domain\":\"\"}},{\"id\":\"scheduler\",\"service\":{\"id\":\"scheduler-service\",\"domain\":\"\"},\"worker\":{\"id\":\"scheduler-worker\",\"domain\":\"\"},\"web\":{\"id\":\"scheduler-web\",\"domain\":\"\"}},{\"id\":\"mc\",\"service\":{\"id\":\"mc-service\",\"domain\":\"\"},\"web\":{\"id\":\"mc-web\",\"domain\":\"\"}},{\"id\":\"auth\",\"service\":{\"id\":\"auth-service\",\"domain\":\"\"},\"web\":{\"id\":\"auth-web\",\"domain\":\"\"},\"sso\":{\"id\":\"auth-sso\",\"domain\":\"\"}}]", - "OTLP_URL": "otel-collector.masastack:9013", - "REDIS": "{\"RedisHost\": \"localhost\", \"RedisPort\": 6379, \"RedisDb\": 0,\"RedisPassword\": \"\"}", - "MASA_VERSION": "1.0-Preview1", - "MASA_ENVIRONMENT": "Development", - "MASA_NAMESPACE": "masastack", - "ADMIN_PWD": "admin_pwd", - "DCC_SECRET": "dcc_secret", - "SUFFIX_IDENTITY": "dev" -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/DccClientTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/DccClientTest.cs deleted file mode 100644 index 36751110f..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/DccClientTest.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Dcc.Tests; - -[TestClass] -public class DccClientTest -{ - [TestMethod] - public void TestAddDccClient() - { - var services = new ServiceCollection(); - - services.AddDccClient(); - - var dccClient = services.BuildServiceProvider().GetRequiredService(); - Assert.IsNotNull(dccClient); - } - - [TestMethod] - public void TestAddDccClient2() - { - var builder = WebApplication.CreateBuilder(); - builder.Services.AddDccClient(); - var serviceProvider = builder.Services.BuildServiceProvider(); - var options = serviceProvider.GetRequiredService>(); - var redisOptions = options.Get("masa.contrib.basicability.dcc"); - Assert.AreEqual(1, redisOptions.Servers.Count); - Assert.AreEqual("localhost", redisOptions.Servers[0].Host); - Assert.AreEqual(8888, redisOptions.Servers[0].Port); - Assert.AreEqual(0, redisOptions.DefaultDatabase); - - var dccClient = serviceProvider.GetRequiredService(); - Assert.IsNotNull(dccClient); - } - - [TestMethod] - public void TestAddDccClient3() - { - var services = new ServiceCollection(); - - services.AddDccClient(options => - { - options.Servers.Add(new RedisServerOptions("localhost", 8888)); - options.DefaultDatabase = 0; - options.Password = "xxxx"; - }); - - var dccClient = services.BuildServiceProvider().GetRequiredService(); - Assert.IsNotNull(dccClient); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/LabelServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/LabelServiceTest.cs deleted file mode 100644 index 6e44a8e60..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/LabelServiceTest.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Dcc.Tests; - -[TestClass] -public class LabelServiceTest -{ - [TestMethod] - [DataRow("status")] - public async Task TestGetListByTypeCodeAsync(string typeCode) - { - var data = new List - { - new LabelModel { Code = "normal" }, - new LabelModel { Code = "frozen" } - }; - - var distributedCacheClient = new Mock(); - distributedCacheClient.Setup(client => client.GetAsync>(typeCode, null)).ReturnsAsync(data).Verifiable(); - var dccClient = new DccClient(distributedCacheClient.Object); - - var result = await dccClient.LabelService.GetListByTypeCodeAsync(typeCode); - distributedCacheClient.Verify(client => client.GetAsync>(typeCode, null), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - [DataRow("status")] - public async Task TestGetListByTypeCodeAsync2(string typeCode) - { - List? data = null; - - var distributedCacheClient = new Mock(); - distributedCacheClient.Setup(client => client.GetAsync>(It.IsAny(), null)).ReturnsAsync(data).Verifiable(); - var dccClient = new DccClient(distributedCacheClient.Object); - - var result = await dccClient.LabelService.GetListByTypeCodeAsync(typeCode); - distributedCacheClient.Verify(client => client.GetAsync>(typeCode, null), Times.Once); - - Assert.IsFalse(result.Any()); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/Masa.Contrib.StackSdks.Dcc.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/Masa.Contrib.StackSdks.Dcc.Tests.csproj deleted file mode 100644 index b92b45c7d..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/Masa.Contrib.StackSdks.Dcc.Tests.csproj +++ /dev/null @@ -1,43 +0,0 @@ - - - - enable - enable - false - true - - - - - - - - - - - - - Always - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/_Imports.cs deleted file mode 100644 index 3cccd1ff3..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/_Imports.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Caching; -global using Masa.BuildingBlocks.StackSdks.Dcc; -global using Masa.BuildingBlocks.StackSdks.Dcc.Contracts.Model; -global using Masa.Contrib.Caching.Distributed.StackExchangeRedis; -global using Microsoft.AspNetCore.Builder; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.Extensions.Options; -global using Microsoft.VisualStudio.TestTools.UnitTesting; -global using Moq; diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/appsettings.json b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/appsettings.json deleted file mode 100644 index c0f6fc8f9..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Dcc.Tests/appsettings.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "DccOptions": { - "RedisOptions": { - "Servers": [ - { - "Host": "localhost", - "Port": 8888 - } - ], - "DefaultDatabase": 0, - "Password": "" - } - } -} \ No newline at end of file diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/ChannelServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/ChannelServiceTest.cs deleted file mode 100644 index 05473e392..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/ChannelServiceTest.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Tests; - -[TestClass] -public class ChannelServiceTest -{ - [TestMethod] - public async Task TestGetAsync() - { - var data = new ChannelModel(); - Guid channelId = Guid.NewGuid(); - var requestUri = $"api/channel/{channelId}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var channelService = new Mock(caller.Object); - var result = await channelService.Object.GetAsync(channelId); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestGetListAsync() - { - var options = new GetChannelModel(); - var data = new PaginatedListModel(); - var requestUri = $"api/channel"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); - var channelService = new Mock(caller.Object); - var result = await channelService.Object.GetListAsync(options); - caller.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestCreateAsync() - { - var options = new CreateChannelModel(); - var requestUri = $"api/channel"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); - var messageTaskService = new Mock(caller.Object); - await messageTaskService.Object.CreateAsync(options); - caller.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/Masa.Contrib.StackSdks.Mc.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/Masa.Contrib.StackSdks.Mc.Tests.csproj deleted file mode 100644 index ac7cedfa6..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/Masa.Contrib.StackSdks.Mc.Tests.csproj +++ /dev/null @@ -1,28 +0,0 @@ - - - - enable - false - true - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/McClientTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/McClientTest.cs deleted file mode 100644 index 40100b2d6..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/McClientTest.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Tests; - -[TestClass] -public class McClientTest -{ - [TestMethod] - public void TestAddMcClient() - { - var services = new ServiceCollection(); - services.AddMcClient("https://localhost:18102"); - var mcClient = services.BuildServiceProvider().GetRequiredService(); - - Assert.IsNotNull(mcClient); - } - - [TestMethod] - public void TestAddMcClientShouldThrowArgumentNullException() - { - var services = new ServiceCollection(); - Assert.ThrowsException(() => services.AddMcClient(mcServiceBaseAddress: null!)); - } - - [TestMethod] - public void TestAddMcClientShouldThrowArgumentNullException2() - { - var services = new ServiceCollection(); - Assert.ThrowsException(() => services.AddMcClient(callerBuilder: null!)); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/MessageTaskServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/MessageTaskServiceTest.cs deleted file mode 100644 index dde782cd7..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/MessageTaskServiceTest.cs +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Tests; - -[TestClass] -public class MessageTaskServiceTest -{ - [TestMethod] - public async Task TestGetAsync() - { - var data = new MessageTaskModel(); - Guid id = Guid.NewGuid(); - var requestUri = $"api/message-task/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var messageTaskService = new Mock(caller.Object); - var result = await messageTaskService.Object.GetAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestSendOrdinaryMessageByInternalAsync() - { - var options = new SendOrdinaryMessageByInternalModel(); - var requestUri = $"api/message-task/SendOrdinaryMessageByInternal"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); - var messageTaskService = new Mock(caller.Object); - await messageTaskService.Object.SendOrdinaryMessageByInternalAsync(options); - caller.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); - } - - [TestMethod] - public async Task TestSendTemplateMessageByInternalAsync() - { - var options = new SendTemplateMessageByInternalModel(); - var requestUri = $"api/message-task/SendTemplateMessageByInternal"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); - var messageTaskService = new Mock(caller.Object); - await messageTaskService.Object.SendTemplateMessageByInternalAsync(options); - caller.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); - } - - [TestMethod] - public async Task TestSendOrdinaryMessageByExternalAsync() - { - var options = new SendOrdinaryMessageByExternalModel(); - var requestUri = $"api/message-task/SendOrdinaryMessageByExternal"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); - var messageTaskService = new Mock(caller.Object); - await messageTaskService.Object.SendOrdinaryMessageByExternalAsync(options); - caller.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); - } - - [TestMethod] - public async Task TestSendTemplateMessageByExternalAsync() - { - var options = new SendTemplateMessageByExternalModel(); - var requestUri = $"api/message-task/SendTemplateMessageByExternal"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); - var messageTaskService = new Mock(caller.Object); - await messageTaskService.Object.SendTemplateMessageByExternalAsync(options); - caller.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); - } - - [TestMethod] - public async Task TestGetListAsync() - { - var options = new GetMessageTaskModel(1, 10); - var data = new PaginatedListModel(); - var requestUri = $"api/message-task"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); - var service = new Mock(caller.Object); - var result = await service.Object.GetListAsync(options); - caller.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestDeleteAsync() - { - Guid id = Guid.NewGuid(); - var requestUri = $"api/message-task/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.DeleteAsync(requestUri, null, true, default)).Verifiable(); - var service = new Mock(caller.Object); - await service.Object.DeleteAsync(id); - caller.Verify(provider => provider.DeleteAsync(requestUri, null, true, default), Times.Once); - } - - [TestMethod] - public async Task TestUpdateAsync() - { - Guid id = Guid.NewGuid(); - var options = new MessageTaskUpsertModel(); - var requestUri = $"api/message-task/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, options, true, default)).Verifiable(); - var service = new Mock(caller.Object); - await service.Object.UpdateAsync(id, options); - caller.Verify(provider => provider.PutAsync(requestUri, options, true, default), Times.Once); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/MessageTemplateServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/MessageTemplateServiceTest.cs deleted file mode 100644 index 7791bdb84..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/MessageTemplateServiceTest.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Tests; - -[TestClass] -public class MessageTemplateServiceTest -{ - [TestMethod] - public async Task TestGetAsync() - { - var data = new MessageTemplateModel(); - Guid id = Guid.NewGuid(); - var requestUri = $"api/message-template/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var messageTemplateService = new Mock(caller.Object); - var result = await messageTemplateService.Object.GetAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestGetListAsync() - { - var options = new GetMessageTemplateModel(); - var data = new PaginatedListModel(); - var requestUri = $"api/message-template"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); - var messageTemplateService = new Mock(caller.Object); - var result = await messageTemplateService.Object.GetListAsync(options); - caller.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); - Assert.IsTrue(result is not null); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/ReceiverGroupServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/ReceiverGroupServiceTest.cs deleted file mode 100644 index 6beb91d45..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/ReceiverGroupServiceTest.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Tests; - -[TestClass] -public class ReceiverGroupServiceTest -{ - [TestMethod] - public async Task TestGetAsync() - { - var data = new ReceiverGroupModel(); - Guid id = Guid.NewGuid(); - var requestUri = $"api/receiver-group/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var receiverGroupService = new Mock(caller.Object); - var result = await receiverGroupService.Object.GetAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestGetListAsync() - { - var options = new GetReceiverGroupModel(); - var data = new PaginatedListModel(); - var requestUri = $"api/receiver-group"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); - var receiverGroupService = new Mock(caller.Object); - var result = await receiverGroupService.Object.GetListAsync(options); - caller.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); - Assert.IsTrue(result is not null); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/WebsiteMessageServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/WebsiteMessageServiceTest.cs deleted file mode 100644 index 0548168d5..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/WebsiteMessageServiceTest.cs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Mc.Tests; - -[TestClass] -public class WebsiteMessageServiceTest -{ - [TestMethod] - public async Task TestGetAsync() - { - var data = new WebsiteMessageModel(); - Guid id = Guid.NewGuid(); - var requestUri = $"api/website-message/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var websiteMessageService = new Mock(caller.Object); - var result = await websiteMessageService.Object.GetAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestGetListAsync() - { - var options = new GetWebsiteMessageModel(1,10); - var data = new PaginatedListModel(); - var requestUri = $"api/website-message"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); - var websiteMessageService = new Mock(caller.Object); - var result = await websiteMessageService.Object.GetListAsync(options); - caller.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestCheckAsync() - { - var requestUri = $"api/website-message/Check"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, null, true, default)).Verifiable(); - var websiteMessageService = new Mock(caller.Object); - await websiteMessageService.Object.CheckAsync(); - caller.Verify(provider => provider.PostAsync(requestUri, null, true, default), Times.Once); - } - - [TestMethod] - public async Task TestDeleteAsync() - { - Guid id = Guid.NewGuid(); - var requestUri = $"api/website-message/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.DeleteAsync(requestUri, null, true, default)).Verifiable(); - var websiteMessageService = new Mock(caller.Object); - await websiteMessageService.Object.DeleteAsync(id); - caller.Verify(provider => provider.DeleteAsync(requestUri, null, true, default), Times.Once); - } - - [TestMethod] - public async Task TestGetChannelListAsync() - { - var data = new List(); - var requestUri = $"api/website-message/ChannelList"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var websiteMessageService = new Mock(caller.Object); - var result = await websiteMessageService.Object.GetChannelListAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestGetNoticeListAsync() - { - var options = new GetNoticeListModel(); - var data = new List(); - var requestUri = $"api/website-message/NoticeList"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, options, default)).ReturnsAsync(data).Verifiable(); - var websiteMessageService = new Mock(caller.Object); - var result = await websiteMessageService.Object.GetNoticeListAsync(options); - caller.Verify(provider => provider.GetAsync>(requestUri, options, default), Times.Once); - Assert.IsTrue(result is not null); - } - - [TestMethod] - public async Task TestReadAsync() - { - var options = new ReadWebsiteMessageModel(); - var requestUri = $"api/website-message/Read"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); - var websiteMessageService = new Mock(caller.Object); - await websiteMessageService.Object.ReadAsync(options); - caller.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); - } - - [TestMethod] - public async Task TestSetAllReadAsync() - { - var options = new ReadAllWebsiteMessageModel(1,10); - var requestUri = $"api/website-message/SetAllRead"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, options, true, default)).Verifiable(); - var websiteMessageService = new Mock(caller.Object); - await websiteMessageService.Object.SetAllReadAsync(options); - caller.Verify(provider => provider.PostAsync(requestUri, options, true, default), Times.Once); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/_Imports.cs deleted file mode 100644 index be7b94ead..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/_Imports.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Mc; -global using Masa.BuildingBlocks.StackSdks.Mc.Model; -global using Masa.Contrib.StackSdks.Mc.Service; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.VisualStudio.TestTools.UnitTesting; -global using Moq; -global using System; -global using System.Collections.Generic; -global using System.Threading.Tasks; diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/Handler.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/Handler.cs deleted file mode 100644 index ef979935f..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/Handler.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Middleware.Tests.Application; - -public class Handler -{ -#pragma warning disable CA1822 - [EventHandler] - public void TestCommand(TestCommand testCommand) - { - - } - - [EventHandler] - public void TestAllowCommand(TestAllowCommand testCommand) - { - testCommand.Count++; - } - - [EventHandler] - public void TestQuery(TestQuery testQuery) - { - testQuery.Result = true; - } -#pragma warning restore CA1822 -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/TestAllowCommand.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/TestAllowCommand.cs deleted file mode 100644 index 83f6f7691..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/TestAllowCommand.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Middleware.Tests.Application; - -[AllowedEvent] -public record TestAllowCommand : Command -{ - public int Count { get; set; } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/TestCommand.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/TestCommand.cs deleted file mode 100644 index c9987cabe..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/TestCommand.cs +++ /dev/null @@ -1,8 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Middleware.Tests.Application; - -public record TestCommand : Command -{ -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/TestQuery.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/TestQuery.cs deleted file mode 100644 index 55758d2d8..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Application/TestQuery.cs +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Middleware.Tests.Application; - -public record TestQuery : Query -{ - public override bool Result { get; set; } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/EventMiddlewareTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/EventMiddlewareTest.cs deleted file mode 100644 index 0b93973aa..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/EventMiddlewareTest.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Middleware.Tests; - -[TestClass] -public class EventMiddlewareTest -{ - private IServiceProvider _serviceProvider; - private readonly IEventBus _eventBus; - - public EventMiddlewareTest() - { - var builder = WebApplication.CreateBuilder(); - - builder.Services.AddMasaIdentity(options => - { - options.Mapping(nameof(MasaUser.Account), "ACCOUNT"); - }); - - Mock dccClient = new(); - var configuration = builder.Configuration; - var configs = new Dictionary() - { - { MasaStackConfigConstant.VERSION, configuration.GetValue(MasaStackConfigConstant.VERSION) }, - { MasaStackConfigConstant.IS_DEMO, configuration.GetValue(MasaStackConfigConstant.IS_DEMO).ToString() }, - { MasaStackConfigConstant.DOMAIN_NAME, configuration.GetValue(MasaStackConfigConstant.DOMAIN_NAME) }, - { MasaStackConfigConstant.NAMESPACE, configuration.GetValue(MasaStackConfigConstant.NAMESPACE) }, - { MasaStackConfigConstant.CLUSTER, configuration.GetValue(MasaStackConfigConstant.CLUSTER) }, - { MasaStackConfigConstant.OTLP_URL, configuration.GetValue(MasaStackConfigConstant.OTLP_URL) }, - { MasaStackConfigConstant.REDIS, configuration.GetValue(MasaStackConfigConstant.REDIS) }, - { MasaStackConfigConstant.CONNECTIONSTRING, configuration.GetValue(MasaStackConfigConstant.CONNECTIONSTRING) }, - { MasaStackConfigConstant.ELASTIC, configuration.GetValue(MasaStackConfigConstant.ELASTIC) }, - { MasaStackConfigConstant.ENVIRONMENT, configuration.GetValue(MasaStackConfigConstant.ENVIRONMENT) }, - { MasaStackConfigConstant.ADMIN_PWD, configuration.GetValue(MasaStackConfigConstant.ADMIN_PWD) }, - { MasaStackConfigConstant.DCC_SECRET, configuration.GetValue(MasaStackConfigConstant.DCC_SECRET) } - }; - dccClient.Setup(aa => aa.GetAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), It.IsAny(), - It.IsAny>>()!)) - .ReturnsAsync(configs); - - builder.Services.AddSingleton(serviceProvider => - { - return new MasaStackConfig(dccClient.Object, configs); - }); - builder.Services.AddEventBus(new Assembly[1] { Assembly.GetExecutingAssembly() }, ServiceLifetime.Scoped); - builder.Services.AddStackMiddleware(); - - _serviceProvider = builder.Services.BuildServiceProvider(); - var httpContextAccessor = _serviceProvider.GetRequiredService(); - httpContextAccessor.HttpContext = new DefaultHttpContext() - { - User = new ClaimsPrincipal(new List() - { - new(new List() - { - new(ClaimType.DEFAULT_USER_ID, "1"), - new("ACCOUNT", "guest") - }) - }) - }; - - _eventBus = _serviceProvider.GetRequiredService(); - } - - [TestMethod] - public void TestCommand() - { - var command = new TestCommand(); - Assert.ThrowsExceptionAsync(async () => await _eventBus.PublishAsync(command), "DISABLED_OPERATE"); - } - - [TestMethod] - public async Task TestAllowCommand() - { - var command = new TestAllowCommand(); - await _eventBus.PublishAsync(command); - Assert.AreEqual(1, command.Count); - } - - [TestMethod] - public async Task TestQuery() - { - var query = new TestQuery(); - await _eventBus.PublishAsync(query); - Assert.IsTrue(query.Result); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Masa.Contrib.StackSdks.Middleware.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Masa.Contrib.StackSdks.Middleware.Tests.csproj deleted file mode 100644 index 021f3742f..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/Masa.Contrib.StackSdks.Middleware.Tests.csproj +++ /dev/null @@ -1,42 +0,0 @@ - - - - enable - enable - false - true - - - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - Always - - - - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/RequestMiddlewareTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/RequestMiddlewareTest.cs deleted file mode 100644 index b9fb29184..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/RequestMiddlewareTest.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Middleware.Tests; - -[TestClass] -public class RequestMiddlewareTest -{ - private IServiceProvider _serviceProvider; - - public RequestMiddlewareTest() - { - var builder = WebApplication.CreateBuilder(); - - Mock dccClient = new(); - var configuration = builder.Configuration; - var configs = new Dictionary() - { - { MasaStackConfigConstant.VERSION, configuration.GetValue(MasaStackConfigConstant.VERSION) }, - { MasaStackConfigConstant.IS_DEMO, configuration.GetValue(MasaStackConfigConstant.IS_DEMO).ToString() }, - { MasaStackConfigConstant.DOMAIN_NAME, configuration.GetValue(MasaStackConfigConstant.DOMAIN_NAME) }, - { MasaStackConfigConstant.NAMESPACE, configuration.GetValue(MasaStackConfigConstant.NAMESPACE) }, - { MasaStackConfigConstant.CLUSTER, configuration.GetValue(MasaStackConfigConstant.CLUSTER) }, - { MasaStackConfigConstant.OTLP_URL, configuration.GetValue(MasaStackConfigConstant.OTLP_URL) }, - { MasaStackConfigConstant.REDIS, configuration.GetValue(MasaStackConfigConstant.REDIS) }, - { MasaStackConfigConstant.CONNECTIONSTRING, configuration.GetValue(MasaStackConfigConstant.CONNECTIONSTRING) }, - { MasaStackConfigConstant.ELASTIC, configuration.GetValue(MasaStackConfigConstant.ELASTIC) }, - { MasaStackConfigConstant.ENVIRONMENT, configuration.GetValue(MasaStackConfigConstant.ENVIRONMENT) }, - { MasaStackConfigConstant.ADMIN_PWD, configuration.GetValue(MasaStackConfigConstant.ADMIN_PWD) }, - { MasaStackConfigConstant.DCC_SECRET, configuration.GetValue(MasaStackConfigConstant.DCC_SECRET) } - }; - dccClient.Setup(aa => aa.GetAsync( - It.IsAny(), - It.IsAny(), - It.IsAny(), It.IsAny(), - It.IsAny>>()!)) - .ReturnsAsync(configs); - - builder.Services.AddSingleton(serviceProvider => - { - return new MasaStackConfig(dccClient.Object, configs); - }); - - builder.Services.AddStackMiddleware(); - - _serviceProvider = builder.Services.BuildServiceProvider(); - } - - [TestMethod] - public async Task TestRequestMiddleware() - { - DefaultHttpContext defaultContext = new DefaultHttpContext(); - defaultContext.Response.Body = new MemoryStream(); - defaultContext.Request.Path = "/"; - - var requestMiddleware = _serviceProvider.GetRequiredService(); - await requestMiddleware.InvokeAsync(defaultContext, (innerHttpContext) => - { - innerHttpContext.Response.WriteAsync("content"); - return Task.CompletedTask; - }); - - //Don't forget to rewind the stream - defaultContext.Response.Body.Seek(0, SeekOrigin.Begin); - var body = new StreamReader(defaultContext.Response.Body).ReadToEnd(); - - Assert.AreEqual("content", body); - } - - [TestMethod] - public void TestDisabledRequestMiddleware() - { - DefaultHttpContext defaultContext = new DefaultHttpContext(); - defaultContext.SetEndpoint(new Endpoint(c => Task.CompletedTask, new EndpointMetadataCollection(new DisabledRouteAttribute()), "myapp")); - - var requestMiddleware = _serviceProvider.GetRequiredService(); - - Assert.ThrowsExceptionAsync(async () => - await requestMiddleware.InvokeAsync(defaultContext, (innerHttpContext) => - { - return Task.CompletedTask; - })); - - //Assert - var endpoint = defaultContext.GetEndpoint(); - Assert.IsNotNull(endpoint); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/_Imports.cs deleted file mode 100644 index fb4fd023a..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/_Imports.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Configuration; -global using Masa.BuildingBlocks.Dispatcher.Events; -global using Masa.BuildingBlocks.ReadWriteSplitting.Cqrs.Commands; -global using Masa.BuildingBlocks.ReadWriteSplitting.Cqrs.Queries; -global using Masa.BuildingBlocks.StackSdks.Auth.Contracts; -global using Masa.BuildingBlocks.StackSdks.Config; -global using Masa.BuildingBlocks.StackSdks.Middleware; -global using Masa.Contrib.Authentication.Identity; -global using Masa.Contrib.Dispatcher.Events; -global using Masa.Contrib.StackSdks.Config; -global using Masa.Contrib.StackSdks.Middleware.Tests.Application; -global using Microsoft.AspNetCore.Builder; -global using Microsoft.AspNetCore.Http; -global using Microsoft.Extensions.Configuration; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.VisualStudio.TestTools.UnitTesting; -global using Moq; -global using System.Reflection; -global using System.Security.Claims; diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/appsettings.json b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/appsettings.json deleted file mode 100644 index 035b229f0..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Middleware.Tests/appsettings.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "CLUSTER": "Default", - "CONNECTIONSTRING": "{\"Server\": \"masastack-sqlserver.masastack\", \"port\": 1433,\"Database\":\"\",\"UserId\": \"sa\",\"Password\":\"p@ssw0rd\"}", - "DOMAIN_NAME": "masastack.com", - "ELASTIC": "{\"ElasticNodes\": [\"masastack-es.masastack\"],\"Index\": \"user_dev\"}", - "IS_DEMO": "true", - "MASA_STACK": "[{\"id\":\"pm\",\"name\":\"PM\",\"service\":{\"name\":\"PM.Service\",\"id\":\"pm-service\",\"domain\":\"pm-staging.masastack\"},\"web\":{\"name\":\"PM.Web\",\"id\":\"pm-web\",\"domain\":\"\"}},{\"id\":\"dcc\",\"name\":\"DCC\",\"service\":{\"name\":\"Dcc.Service\",\"id\":\"dcc-service\",\"domain\":\"dcc-staging.masastack\"},\"web\":{\"name\":\"DCC.Web\",\"id\":\"dcc-web\",\"domain\":\"\"}},{\"id\":\"tsc\",\"name\":\"TSC\",\"service\":{\"name\":\"TSC.Service\",\"id\":\"tsc-service\",\"domain\":\"\"},\"web\":{\"name\":\"TSC.Web\",\"id\":\"tsc-web\",\"domain\":\"\"}},{\"id\":\"alert\",\"name\":\"Alert\",\"service\":{\"name\":\"Alert.Service\",\"id\":\"alert-service\",\"domain\":\"\"},\"web\":{\"name\":\"Alert.Web\",\"id\":\"alert-web\",\"domain\":\"\"}},{\"id\":\"scheduler\",\"name\":\"Scheduler\",\"service\":{\"name\":\"Scheduler.Service\",\"id\":\"scheduler-service\",\"domain\":\"\"},\"worker\":{\"name\":\"Scheduler.Worker\",\"id\":\"scheduler-worker\",\"domain\":\"\"},\"web\":{\"name\":\"Scheduler.Web\",\"id\":\"scheduler-web\",\"domain\":\"\"}},{\"id\":\"mc\",\"name\":\"MC\",\"service\":{\"name\":\"MC.Service\",\"id\":\"mc-service\",\"domain\":\"\"},\"web\":{\"name\":\"MC.Web\",\"id\":\"mc-web\",\"domain\":\"\"}},{\"id\":\"auth\",\"name\":\"Auth\",\"service\":{\"name\":\"Auth.Service\",\"id\":\"auth-service\",\"domain\":\"\"},\"web\":{\"name\":\"Auth.Web\",\"id\":\"auth-web\",\"domain\":\"\"},\"sso\":{\"name\":\"Auth.SSO\",\"id\":\"auth-sso\",\"domain\":\"\"}}]", - "OTLP_URL": "otel-collector.masastack:9013", - "REDIS": "{\"RedisHost\": \"localhost\", \"RedisPort\": 6379, \"RedisDb\": 0,\"RedisPassword\": \"\"}", - "VERSION": "1.0-Preview1", - "ENVIRONMENT": "Development", - "NAMESPACE": "masastack", - "ADMIN_PWD": "admin_pwd", - "DCC_SECRET": "dcc_secret" -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/AppServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/AppServiceTest.cs deleted file mode 100644 index 6f989afed..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/AppServiceTest.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Pm.Tests; - -[TestClass] -public class AppServiceTest -{ - [TestMethod] - [DataRow(1)] - public async Task TestGetAsync(int id) - { - var data = new AppDetailModel(); - - var requestUri = $"api/v1/app/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.AppService.GetAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - [DataRow(1)] - public async Task TestGet1Async(int id) - { - AppDetailModel? data = null; - - var requestUri = $"api/v1/app/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.AppService.GetAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - [DataRow("identity")] - public async Task TestGetByIdentityAsync(string identity) - { - var data = new AppDetailModel(); - - var requestUri = $"open-api/app/{identity}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.AppService.GetByIdentityAsync(identity); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - [DataRow("identity")] - public async Task TestGetByIdentity1Async(string identity) - { - AppDetailModel? data = null; - - var requestUri = $"open-api/app/{identity}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.AppService.GetByIdentityAsync(identity); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - public async Task TestGetListAsync() - { - var data = new List - { - new AppDetailModel() - }; - - var requestUri = $"api/v1/app"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.AppService.GetListAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestGetList1Async() - { - List? data = null; - - var requestUri = $"api/v1/app"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.AppService.GetListAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 0); - } - - [TestMethod] - public async Task TestGetListByProjectIdsAsync() - { - var data = new List - { - new AppDetailModel() - }; - var projectIds = new List { 1 }; - - var requestUri = $"api/v1/projects/app"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync, List>(requestUri, projectIds, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.AppService.GetListByProjectIdsAsync(projectIds); - caller.Verify(provider => provider.PostAsync, List>(requestUri, projectIds, default), Times.Once); - - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestGetListByProjectIds1Async() - { - List? data = null; - var projectIds = new List { 1 }; - - var requestUri = $"api/v1/projects/app"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync, List>(It.IsAny(), projectIds, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.AppService.GetListByProjectIdsAsync(projectIds); - caller.Verify(provider => provider.PostAsync, List>(requestUri, projectIds, default), Times.Once); - - Assert.IsTrue(result.Count == 0); - } - - [TestMethod] - [DataRow(1)] - public async Task TestGetWithEnvironmentClusterAsync(int id) - { - var data = new AppDetailModel(); - - var requestUri = $"api/v1/appWhitEnvCluster/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.AppService.GetWithEnvironmentClusterAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - [DataRow(1)] - public async Task TestGetWithEnvironmentCluster1Async(int id) - { - AppDetailModel? data = null; - - var requestUri = $"api/v1/appWhitEnvCluster/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.AppService.GetWithEnvironmentClusterAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - [DataRow(AppTypes.UI)] - public async Task TestGetListByAppTypes(params AppTypes[] appTypes) - { - var data = new List - { - new AppDetailModel() - }; - - var requestUri = $"open-api/app/by-types"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync>(requestUri, appTypes, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.AppService.GetListByAppTypes(appTypes); - caller.Verify(provider => provider.PostAsync>(requestUri, appTypes, default), Times.Once); - - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - [DataRow(AppTypes.UI)] - public async Task TestGetListByAppTypes1(params AppTypes[] appTypes) - { - List? data = null; - - var requestUri = $"open-api/app/by-types"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync>(It.IsAny(), appTypes, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.AppService.GetListByAppTypes(appTypes); - caller.Verify(provider => provider.PostAsync>(requestUri, appTypes, default), Times.Once); - - Assert.IsTrue(result.Count == 0); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/ClusterServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/ClusterServiceTest.cs deleted file mode 100644 index e5fbce71a..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/ClusterServiceTest.cs +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Pm.Tests; - -[TestClass] -public class ClusterServiceTest -{ - [TestMethod] - [DataRow(1)] - public async Task TestGetAsync(int id) - { - var data = new ClusterDetailModel(); - - var requestUri = $"api/v1/cluster/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ClusterService.GetAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - [DataRow(1)] - public async Task TestGetAsync1(int id) - { - ClusterDetailModel? data = null; - - var requestUri = $"api/v1/cluster/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ClusterService.GetAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - public async Task TestGetEnvironmentClustersAsync() - { - var data = new List - { - new EnvironmentClusterModel { Id = 1 } - }; - - var requestUri = $"api/v1/envClusters"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ClusterService.GetEnvironmentClustersAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestGetEnvironmentClusters1Async() - { - List? data = null; - - var requestUri = $"api/v1/envClusters"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ClusterService.GetEnvironmentClustersAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 0); - } - - [TestMethod] - public async Task TestGetListAsync() - { - var data = new List - { - new ClusterModel { Id = 1 } - }; - - var requestUri = $"api/v1/cluster"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ClusterService.GetListAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestGetList1Async() - { - List? data = null; - - var requestUri = $"api/v1/cluster"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ClusterService.GetListAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 0); - } - - [TestMethod] - [DataRow(1)] - public async Task TestGetListByEnvIdAsync(int envId) - { - var data = new List - { - new ClusterModel { Id = 1 } - }; - - var requestUri = $"api/v1/{envId}/cluster"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ClusterService.GetListByEnvIdAsync(envId); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - [DataRow(1)] - public async Task TestGetListByEnvId1Async(int envId) - { - List? data = null; - - var requestUri = $"api/v1/{envId}/cluster"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ClusterService.GetListByEnvIdAsync(envId); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 0); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/EnvironmentServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/EnvironmentServiceTest.cs deleted file mode 100644 index 526a53255..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/EnvironmentServiceTest.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Pm.Tests; - -[TestClass] -public class EnvironmentServiceTest -{ - [TestMethod] - [DataRow(1)] - public async Task TestGetAsync(int id) - { - var data = new EnvironmentDetailModel(); - - var requestUri = $"api/v1/env/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default).Result).Returns(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.EnvironmentService.GetAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - [DataRow(1)] - public async Task TestGet1Async(int id) - { - EnvironmentDetailModel? data = null; - - var requestUri = $"api/v1/env/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.EnvironmentService.GetAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - public async Task TestGetListAsync() - { - var data = new List - { - new EnvironmentModel { Id=1, Color="", Name="" } - }; - - var requestUri = $"api/v1/env"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.EnvironmentService.GetListAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestGetList1Async() - { - List? data = null; - - var requestUri = $"api/v1/env"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.EnvironmentService.GetListAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 0); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/Masa.Contrib.StackSdks.Pm.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/Masa.Contrib.StackSdks.Pm.Tests.csproj deleted file mode 100644 index d597e8d0a..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/Masa.Contrib.StackSdks.Pm.Tests.csproj +++ /dev/null @@ -1,28 +0,0 @@ - - - - enable - false - true - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/PmClientTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/PmClientTest.cs deleted file mode 100644 index 5fde11d82..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/PmClientTest.cs +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Pm.Tests; - -[TestClass] -public class PmClientTest -{ - [TestMethod] - public void TestAddPmClient() - { - var services = new ServiceCollection(); - - services.AddPmClient(option => - { - option.UseHttpClient(builder => - { - builder.Configure = opt => opt.BaseAddress = new Uri("https://github.com"); - }); - }); - - var pmClient = services.BuildServiceProvider().GetRequiredService(); - Assert.IsNotNull(pmClient); - } - - [TestMethod] - public void TestAddPmClient1() - { - var services = new ServiceCollection(); - - services.AddPmClient("https://github.com"); - - var pmClient = services.BuildServiceProvider().GetRequiredService(); - Assert.IsNotNull(pmClient); - } - - [TestMethod] - public void TestAddPmClientShouldThrowArgumentNullException() - { - var services = new ServiceCollection(); - - Assert.ThrowsException(() => services.AddPmClient("")); - } - - [TestMethod] - public void TestAddMultiplePmClient() - { - var services = new ServiceCollection(); - - services.AddPmClient(option => - { - option.UseHttpClient(builder => - { - builder.Configure = opt => opt.BaseAddress = new Uri("https://github.com"); - }); - }); - - services.AddPmClient(option => - { - option.UseHttpClient(builder => - { - builder.Configure = opt => opt.BaseAddress = new Uri("https://github.com"); - }); - }); - - var pmClient = services.BuildServiceProvider().GetRequiredService(); - Assert.IsNotNull(pmClient); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/ProjectServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/ProjectServiceTest.cs deleted file mode 100644 index 24927a778..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/ProjectServiceTest.cs +++ /dev/null @@ -1,247 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Pm.Tests; - -[TestClass] -public class ProjectServiceTest -{ - [TestMethod] - public async Task TestGetProjectAppsAsync() - { - var data = new List() - { - new ProjectAppsModel(1, "", "", "", Guid.NewGuid()) - }; - string env = "development"; - var requestUri = $"open-api/projectwithapps/{env}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetProjectAppsAsync(env); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestGetProjectApps2Async() - { - List? data = null; - string env = "development"; - var requestUri = $"open-api/projectwithapps/{env}"; - var caller = new Mock(); - caller.Setup(provider => (provider.GetAsync>(It.IsAny(), default))).ReturnsAsync(data) - .Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetProjectAppsAsync(env); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 0); - } - - [TestMethod] - [DataRow(1)] - public async Task TestGetAsync(int Id) - { - var data = new ProjectDetailModel(); - - var requestUri = $"api/v1/project/{Id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetAsync(Id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - [DataRow(1)] - public async Task TestGet1Async(int id) - { - ProjectDetailModel? data = null; - - var requestUri = $"api/v1/project/{id}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetAsync(id); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - [DataRow("identity")] - public async Task TestGetByIdentityAsync(string identity) - { - var data = new ProjectDetailModel(); - - var requestUri = $"open-api/project/{identity}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetByIdentityAsync(identity); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - [DataRow("identity")] - public async Task TestGetByIdentity1Async(string identity) - { - ProjectDetailModel? data = null; - - var requestUri = $"open-api/project/{identity}"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetByIdentityAsync(identity); - caller.Verify(provider => provider.GetAsync(requestUri, default), Times.Once); - - Assert.IsNotNull(result); - } - - [TestMethod] - [DataRow(1)] - public async Task TestGetListByEnvironmentClusterIdAsync(int envClusterId) - { - var data = new List() - { - new ProjectModel { Id = 1 } - }; - var requestUri = $"api/v1/{envClusterId}/project"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetListByEnvironmentClusterIdAsync(envClusterId); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - [DataRow(1)] - public async Task TestGetListByEnvironmentClusterId1Async(int envClusterId) - { - List? data = null; - var requestUri = $"api/v1/{envClusterId}/project"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetListByEnvironmentClusterIdAsync(envClusterId); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 0); - } - - [TestMethod] - public async Task TestGetListByTeamIdsAsync() - { - var data = new List() - { - new ProjectModel { Id = 1 } - }; - var teamIds = new List { Guid.NewGuid() }; - var requestUri = $"open-api/project/teamProjects/Develop"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync>(requestUri, teamIds, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetListByTeamIdsAsync(teamIds, "Develop"); - caller.Verify(provider => provider.PostAsync>(requestUri, teamIds, default), Times.Once); - - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestGetListByTeamIds1Async() - { - List? data = null; - var teamIds = new List { Guid.NewGuid() }; - var requestUri = "open-api/project/teamProjects/Develop"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync>(It.IsAny(), It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetListByTeamIdsAsync(teamIds, "Develop"); - caller.Verify(provider => provider.PostAsync>(requestUri, teamIds, default), Times.Once); - - Assert.IsTrue(result.Count == 0); - } - - [TestMethod] - public async Task TestGetProjectTypesAsync() - { - var data = new List() - { - new ProjectTypeModel { Id = 1 } - }; - var requestUri = $"api/v1/project/projectType"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetProjectTypesAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestGetProjectTypes1Async() - { - List? data = null; - var requestUri = $"api/v1/project/projectType"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetProjectTypesAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 0); - } - - [TestMethod] - public async Task TestGetListAsync() - { - var data = new List() - { - new ProjectModel() - }; - var requestUri = $"api/v1/projects"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(requestUri, default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetListAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 1); - } - - [TestMethod] - public async Task TestGetList1Async() - { - List? data = null; - var requestUri = $"api/v1/projects"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync>(It.IsAny(), default)).ReturnsAsync(data).Verifiable(); - var pmCaching = new PmClient(caller.Object); - - var result = await pmCaching.ProjectService.GetListAsync(); - caller.Verify(provider => provider.GetAsync>(requestUri, default), Times.Once); - - Assert.IsTrue(result.Count == 0); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/_Imports.cs deleted file mode 100644 index c357e939a..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/_Imports.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Pm; -global using Masa.BuildingBlocks.StackSdks.Pm.Enum; -global using Masa.BuildingBlocks.StackSdks.Pm.Model; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.VisualStudio.TestTools.UnitTesting; -global using Moq; -global using System; -global using System.Collections.Generic; -global using System.Threading.Tasks; diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/Masa.Contrib.StackSdks.Scheduler.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/Masa.Contrib.StackSdks.Scheduler.Tests.csproj deleted file mode 100644 index 9f573b9ef..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/Masa.Contrib.StackSdks.Scheduler.Tests.csproj +++ /dev/null @@ -1,28 +0,0 @@ - - - - enable - false - true - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/SchedulerClientTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/SchedulerClientTest.cs deleted file mode 100644 index 3d84ad681..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/SchedulerClientTest.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Scheduler.Tests; - -[TestClass] -public class SchedulerClientTest -{ - [TestMethod] - public void TestAddSchedulerClientByOptions() - { - var services = new ServiceCollection(); - - services.AddSchedulerClient(option => - { - option.UseHttpClient(builder => - { - builder.Configure = opt => opt.BaseAddress = new Uri("https://github.com"); - }); - }); - - var schedulerClient = services.BuildServiceProvider().GetService(); - Assert.IsNotNull(schedulerClient); - } - - [TestMethod] - public void TestAddSchedulerClient() - { - var services = new ServiceCollection(); - services.AddSchedulerClient("https://github.com"); - var schedulerClient = services.BuildServiceProvider().GetService(); - Assert.IsNotNull(schedulerClient); - } - - [TestMethod] - public void TestAddSchedulerClientShouldThrowArgumentNullException() - { - var services = new ServiceCollection(); - - Assert.ThrowsException(() => services.AddSchedulerClient("")); - } - - [TestMethod] - public void TestAddSchedulerClientShouldThrowArgumentNullException2() - { - var services = new ServiceCollection(); - - Assert.ThrowsException(() => services.AddSchedulerClient(callerBuilder: null!)); - } - -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/SchedulerJobServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/SchedulerJobServiceTest.cs deleted file mode 100644 index 8774d85e3..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/SchedulerJobServiceTest.cs +++ /dev/null @@ -1,301 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -using Masa.BuildingBlocks.StackSdks.Scheduler.Enum; -using Masa.BuildingBlocks.StackSdks.Scheduler.Model; -using Masa.BuildingBlocks.StackSdks.Scheduler.Request; - -namespace Masa.Contrib.StackSdks.Scheduler.Tests; - -[TestClass] -public class SchedulerJobServiceTest -{ - const string API = "/api/scheduler-job"; - - [TestMethod] - public async Task TestAddSchedulerHttpJobAsync() - { - var requestData = new UpsertSchedulerJobRequest() - { - Name = "TestJob", - JobType = JobTypes.Http, - ProjectIdentity = "MASA_MC", - CronExpression = "", - HttpConfig = new SchedulerJobHttpConfig() - { - RequestUrl = "www.baidu.com", - HttpVerifyType = HttpVerifyTypes.CustomStatusCode, - HttpBody = "", - HttpHeaders = new List>() - { - new KeyValuePair("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36") - }, - HttpMethod = HttpMethods.GET, - VerifyContent = "200", - HttpParameters = new List>() - { - new KeyValuePair("ie", "utf-8"), - } - }, - OperatorId = Guid.NewGuid(), - Description = "Test", - FailedRetryCount = 0, - FailedRetryInterval = 0, - IsAlertException = false, - JobIdentity = "masa-mc-sync-job", - RunTimeoutSecond = 30, - RunTimeoutStrategy = RunTimeoutStrategyTypes.IgnoreTimeout, - ScheduleBlockStrategy = ScheduleBlockStrategyTypes.Parallel, - ScheduleExpiredStrategy = ScheduleExpiredStrategyTypes.Ignore - }; - - var requestUri = $"{API}/addSchedulerJobBySdk"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - var result = await schedulerClient.SchedulerJobService.AddAsync(requestData); - caller.Verify(provider => provider.PostAsync(requestUri, requestData, default), Times.Once); - - Assert.AreNotEqual(Guid.Empty, result); - } - - [TestMethod] - public async Task TestAddSchedulerJobApp() - { - var requestData = new UpsertSchedulerJobRequest() - { - Name = "TestJob", - JobType = JobTypes.JobApp, - ProjectIdentity = "MASA_MC", - CronExpression = "", - JobAppConfig = new SchedulerJobAppConfig() - { - JobAppIdentity = "MASA_MC_SERVICE", - JobEntryAssembly = "Masa.Test.Job", - JobEntryClassName = "TestRunJob", - JobParams = "1;2;3", - Version = "" - }, - OperatorId = Guid.NewGuid(), - Description = "Test", - FailedRetryCount = 0, - FailedRetryInterval = 0, - IsAlertException = false, - RunTimeoutSecond = 30, - JobIdentity = "masa-mc-sync-job", - RunTimeoutStrategy = RunTimeoutStrategyTypes.IgnoreTimeout, - ScheduleBlockStrategy = ScheduleBlockStrategyTypes.Parallel, - ScheduleExpiredStrategy = ScheduleExpiredStrategyTypes.Ignore - }; - - var requestUri = $"{API}/addSchedulerJobBySdk"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - var result = await schedulerClient.SchedulerJobService.AddAsync(requestData); - caller.Verify(provider => provider.PostAsync(requestUri, requestData, default), Times.Once); - - Assert.AreNotEqual(Guid.Empty, result); - } - - [TestMethod] - public async Task TestAddSchedulerDaprServiceInvocationJob() - { - var requestData = new UpsertSchedulerJobRequest() - { - Name = "TestJob", - JobType = JobTypes.DaprServiceInvocation, - ProjectIdentity = "MASA_MC", - CronExpression = "", - DaprServiceInvocationConfig = new SchedulerJobDaprServiceInvocationConfig() - { - DaprServiceIdentity = "MASA_MC_DAPR_SERVICE", - Data = "Test", - HttpMethod = HttpMethods.POST, - MethodName = "TestMethod" - }, - OperatorId = Guid.NewGuid(), - Description = "Test", - FailedRetryCount = 0, - FailedRetryInterval = 0, - IsAlertException = false, - RunTimeoutSecond = 30, - JobIdentity = "masa-mc-sync-job", - RunTimeoutStrategy = RunTimeoutStrategyTypes.IgnoreTimeout, - ScheduleBlockStrategy = ScheduleBlockStrategyTypes.Parallel, - ScheduleExpiredStrategy = ScheduleExpiredStrategyTypes.Ignore - }; - - var requestUri = $"{API}/addSchedulerJobBySdk"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - var result = await schedulerClient.SchedulerJobService.AddAsync(requestData); - caller.Verify(provider => provider.PostAsync(requestUri, requestData, default), Times.Once); - - Assert.AreNotEqual(Guid.Empty, result); - } - - [TestMethod] - public async Task TestAddSchedulerJobArgumentNullException() - { - var requestData = new UpsertSchedulerJobRequest() - { - Name = "TestJob", - JobType = JobTypes.Http, - CronExpression = "", - JobIdentity = "masa-mc-sync-job", - OperatorId = Guid.NewGuid() - }; - - var requestUri = $"{API}/addSchedulerJobBySdk"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - await Assert.ThrowsExceptionAsync(async () => await schedulerClient.SchedulerJobService.AddAsync(requestData)); - } - - [TestMethod] - public async Task TestAddSchedulerHttpJobArgumentNullException() - { - var requestData = new UpsertSchedulerJobRequest() - { - Name = "TestJob", - JobType = JobTypes.Http, - CronExpression = "", - OperatorId = Guid.NewGuid() - }; - - var requestUri = $"{API}/addSchedulerJobBySdk"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - await Assert.ThrowsExceptionAsync(async () => await schedulerClient.SchedulerJobService.AddAsync(requestData)); - } - - [TestMethod] - public async Task TestAddSchedulerJobAppArgumentNullException() - { - var requestData = new UpsertSchedulerJobRequest() - { - Name = "TestJob", - JobType = JobTypes.JobApp, - CronExpression = "", - OperatorId = Guid.NewGuid() - }; - - var requestUri = $"{API}/addSchedulerJobBySdk"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - await Assert.ThrowsExceptionAsync(async () => await schedulerClient.SchedulerJobService.AddAsync(requestData)); - } - - [TestMethod] - public async Task TestAddSchedulerDaprInvocationJobArgumentNullException() - { - var requestData = new UpsertSchedulerJobRequest() - { - Name = "TestJob", - JobType = JobTypes.DaprServiceInvocation, - CronExpression = "", - OperatorId = Guid.NewGuid() - }; - - var requestUri = $"{API}/addSchedulerJobBySdk"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, requestData, default)).ReturnsAsync(Guid.NewGuid()).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - await Assert.ThrowsExceptionAsync(async () => await schedulerClient.SchedulerJobService.AddAsync(requestData)); - } - - [TestMethod] - public async Task TestRemoveSchedulerJobAsync() - { - var requestData = new SchedulerJobRequestBase() - { - JobId = Guid.NewGuid(), - OperatorId = Guid.NewGuid() - }; - - var caller = new Mock(); - caller.Setup(provider => provider.DeleteAsync(API, requestData, true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - var result = await schedulerClient.SchedulerJobService.RemoveAsync(requestData); - caller.Verify(provider => provider.DeleteAsync(API, requestData, true, default), Times.Once); - - Assert.IsTrue(result); - } - - [TestMethod] - public async Task TestStartSchedulerJobAsync() - { - var requestData = new SchedulerJobRequestBase() - { - JobId = Guid.NewGuid(), - OperatorId = Guid.NewGuid() - }; - - var requestUri = $"{API}/startJob"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, requestData, true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - var result = await schedulerClient.SchedulerJobService.StartAsync(requestData); - caller.Verify(provider => provider.PutAsync(requestUri, requestData, true, default), Times.Once); - Assert.IsTrue(result); - } - - [TestMethod] - public async Task TestEnableSchedulerJob() - { - var requestData = new SchedulerJobRequestBase() - { - JobId = Guid.NewGuid(), - OperatorId = Guid.NewGuid() - }; - - var requestUri = $"{API}/changeEnableStatus"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, It.IsAny(), true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - var result = await schedulerClient.SchedulerJobService.EnableAsync(requestData); - caller.Verify(provider => provider.PutAsync(requestUri, It.IsAny(), true, default), Times.Once); - Assert.IsTrue(result); - } - - [TestMethod] - public async Task TestDisableSchedulerJob() - { - var requestData = new SchedulerJobRequestBase() - { - JobId = Guid.NewGuid(), - OperatorId = Guid.NewGuid() - }; - - var requestUri = $"{API}/changeEnableStatus"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, It.IsAny(), true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - var result = await schedulerClient.SchedulerJobService.DisableAsync(requestData); - caller.Verify(provider => provider.PutAsync(requestUri, It.IsAny(), true, default), Times.Once); - Assert.IsTrue(result); - } - - [TestMethod] - public async Task GetSchedulerJobQueryByIdentityAsync() - { - var requestData = new GetSchedulerJobByIdentityRequest() - { - JobIdentity = "masa-scheduler-test-job", - ProjectIdentity = "masa-scheduler" - }; - - var requestUri = $"{API}/getSchedulerJobQueryByIdentity"; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync(requestUri, requestData, default)).ReturnsAsync(new SchedulerJobModel()).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - var result = await schedulerClient.SchedulerJobService.GetSchedulerJobQueryByIdentityAsync(requestData); - caller.Verify(provider => provider.GetAsync(requestUri, requestData, default), Times.Once); - Assert.IsNotNull(result); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/SchedulerTaskServiceTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/SchedulerTaskServiceTest.cs deleted file mode 100644 index 16fa07848..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/SchedulerTaskServiceTest.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -using Masa.BuildingBlocks.StackSdks.Scheduler.Request; - -namespace Masa.Contrib.StackSdks.Scheduler.Tests; - -[TestClass] -public class SchedulerTaskServiceTest -{ - const string API = "/api/scheduler-task"; - - [TestMethod] - public async Task TestStopSchedulerTaskAsync() - { - var requestData = new SchedulerTaskRequestBase() - { - TaskId = Guid.NewGuid(), - OperatorId = Guid.NewGuid() - }; - - var requestUri = $"{API}/stop"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, requestData, true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - var result = await schedulerClient.SchedulerTaskService.StopAsync(requestData); - caller.Verify(provider => provider.PutAsync(requestUri, requestData, true, default), Times.Once); - Assert.IsTrue(result); - } - - [TestMethod] - public async Task TestStartSchedulerTaskAsync() - { - var request = new SchedulerTaskRequestBase() - { - TaskId = Guid.NewGuid(), - OperatorId = Guid.NewGuid() - }; - - var requestUri = $"{API}/start"; - var caller = new Mock(); - caller.Setup(provider => provider.PutAsync(requestUri, It.IsAny(), true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - var result = await schedulerClient.SchedulerTaskService.StartAsync(request); - caller.Verify(provider => provider.PutAsync(requestUri, It.IsAny(), true, default), Times.Once); - Assert.IsTrue(result); - } - - [TestMethod] - public async Task TestNotifyRunResultAsync() - { - var request = new NotifySchedulerTaskRunResultRequest() - { - TaskId = Guid.NewGuid(), - Status = BuildingBlocks.StackSdks.Scheduler.Enum.TaskRunResultStatus.Success, - OperatorId = Guid.NewGuid() - }; - - var requestUri = $"{API}/notifyRunResultBySdk"; - var caller = new Mock(); - caller.Setup(provider => provider.PostAsync(requestUri, It.IsAny(), true, default)).Verifiable(); - var schedulerClient = new SchedulerClient(caller.Object); - await schedulerClient.SchedulerTaskService.NotifyRunResultAsync(request); - caller.Verify(provider => provider.PostAsync(requestUri, It.IsAny(), true, default), Times.Once); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/_Imports.cs deleted file mode 100644 index 4644a4aa4..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Scheduler.Tests/_Imports.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Scheduler; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.VisualStudio.TestTools.UnitTesting; -global using Moq; -global using System; -global using System.Collections.Generic; -global using System.Threading.Tasks; diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/ClickhouseApmServiceTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/ClickhouseApmServiceTests.cs deleted file mode 100644 index 95cfbfa22..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/ClickhouseApmServiceTests.cs +++ /dev/null @@ -1,143 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests; - -[TestClass] -public class ClickhouseApmServiceTests -{ - private static IApmService _APMService; - private static DateTime _start = DateTime.Parse("2024-01-03T22:00:00.000Z"); - - [ClassInitialize] - public static void Initialized(TestContext testContext) - { - var connection = new ClickHouseConnection(TestUtils.ConnectionString); - Common.InitTable(false, connection); - Common.InitTable(true, connection); - var services = new ServiceCollection(); - services.AddLogging(builder => builder.AddConsole()); - services.AddMASAStackApmClickhouse(TestUtils.ConnectionString, "custom_log", "custom_trace"); - _APMService = services.BuildServiceProvider().GetRequiredService(); - Common.InitTableJsonData(false, AppDomain.CurrentDomain.BaseDirectory, connection); - Common.InitTableJsonData(false, AppDomain.CurrentDomain.BaseDirectory, connection); - _start -= MasaStackClickhouseConnection.TimeZone.BaseUtcOffset; - _start -= TimeZoneInfo.Local.BaseUtcOffset; - } - - [TestMethod] - public async Task ServicePageAsync() - { - var query = new ApmEndpointRequestDto - { - Start = _start, - End = _start.AddHours(1), - ComparisonType = ComparisonTypes.DayBefore, - StatusCodes = "401,402,503,500", - PageSize = 10, - Page = 1 - }; - var result = await _APMService.ServicePageAsync(query); - Assert.IsNotNull(result); - Assert.IsTrue(result.Total > 0); - Assert.IsNotNull(result.Result); - } - - [TestMethod] - public async Task EndpointPageAsync() - { - var query = new ApmEndpointRequestDto - { - Start = _start, - End = _start.AddHours(1), - ComparisonType = ComparisonTypes.DayBefore, - StatusCodes = "401,402,503,500", - PageSize = 10, - Page = 1, - Service = "tsc-service-iotdev" - }; - var result = await _APMService.EndpointPageAsync(query); - Assert.IsNotNull(result); - Assert.IsTrue(result.Total > 0); - Assert.IsNotNull(result.Result); - } - - [TestMethod] - public async Task ChartDataAsync() - { - var query = new ApmEndpointRequestDto - { - Start = _start, - End = _start.AddHours(1), - ComparisonType = ComparisonTypes.DayBefore, - StatusCodes = "401,402,503,500", - PageSize = 10, - Page = 1, - Service = "tsc-service-iotdev" - }; - var result = await _APMService.ChartDataAsync(query); - Assert.IsNotNull(result); - Assert.IsTrue(result.Any()); - } - - [TestMethod] - public async Task EndpointLatencyDistributionAsync() - { - var query = new ApmEndpointRequestDto - { - Start = _start, - End = _start.AddHours(1), - ComparisonType = ComparisonTypes.DayBefore, - StatusCodes = "401,402,503,500", - PageSize = 10, - Page = 1, - Service = "tsc-service-iotdev", - Endpoint = "/api/trace/list" - }; - var result = await _APMService.EndpointLatencyDistributionAsync(query); - Assert.IsNotNull(result); - Assert.IsNotNull(result.Latencies); - } - - [TestMethod] - public async Task ErrorMessagePageAsync() - { - var query = new ApmEndpointRequestDto - { - Start = _start, - End = _start.AddHours(1), - ComparisonType = ComparisonTypes.DayBefore, - StatusCodes = "401,402,503,500", - PageSize = 10, - Page = 1, - Service = "tsc-service-iotdev" - }; - var result = await _APMService.ErrorMessagePageAsync(query); - Assert.IsNotNull(result); - } - - [TestMethod] - public async Task TraceLatencyDetailAsync() - { - var query = new ApmTraceLatencyRequestDto - { - Start = _start, - End = _start.AddHours(1), - ComparisonType = ComparisonTypes.DayBefore, - StatusCodes = "401,402,503,500", - Page = 1, - Service = "tsc-service-iotdev", - Endpoint = "/api/trace/list" - }; - var result = await _APMService.TraceLatencyDetailAsync(query); - Assert.IsNotNull(result); - Assert.IsTrue(result.Total > 0); - Assert.IsNotNull(result.Result); - query.Env = "Development"; - query.LatMax = 10_000;//10s - result = await _APMService.TraceLatencyDetailAsync(query); - Assert.IsNotNull(result); - Assert.IsTrue(result.Total > 0); - Assert.IsNotNull(result.Result); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/Data/otel_trace_data.json b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/Data/otel_trace_data.json deleted file mode 100644 index 0057f7a1f..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/Data/otel_trace_data.json +++ /dev/null @@ -1,266 +0,0 @@ -[ - { - "Timestamp" : "2024-01-03T22:02:12.828Z", - "TraceId" : "ecc21857f5032d057571b1230e8eb014", - "SpanId" : "3fe92b307ca25331", - "ParentSpanId" : "c819bede56087c3d", - "TraceState" : "", - "SpanName" : "HTTP GET", - "SpanKind" : "SPAN_KIND_CLIENT", - "ServiceName" : "tsc-service-iotdev", - "ResourceAttributes" : "{'service.namespace':'Development','service.version':'1.0-Prev','service.instance.id':'2efa4321-1f36-441a-bb1c-8eb25bc894dc','telemetry.sdk.name':'opentelemetry','telemetry.sdk.language':'dotnet','telemetry.sdk.version':'1.5.1','service.layer':'masastack','service.name':'tsc-service-iotdev'}", - "ScopeName" : "OpenTelemetry.Instrumentation.Http.HttpClient", - "ScopeVersion" : "1.0.0.0", - "SpanAttributes" : "{'http.scheme':'http','net.peer.name':'127.0.0.1','net.peer.port':'30090','http.url':'http:\/\/127.0.0.1:9090\/api\/v1\/query_range?end=1704348132&query=round(sum+(increase(http_server_duration_count%7bservice_namespace%3d%22Development%22%2c%7d%5b1m%5d))%2c1)&start=1704304932&step=172s','http.status_code':'200','peer.service':'127.0.0.1:9090','http.method':'GET','http.flavor':'1.1','host.name':'Lonsid-52','user_agent.original':''}", - "Duration" : 128014800, - "StatusCode" : "STATUS_CODE_UNSET", - "StatusMessage" : "", - "Events.Timestamp" : "[]", - "Events.Name" : "[]", - "Events.Attributes" : "[]", - "Links.TraceId" : "[]", - "Links.SpanId" : "[]", - "Links.TraceState" : "[]", - "Links.Attributes" : "[]" - }, - { - "Timestamp" : "2024-01-03T22:02:12.684Z", - "TraceId" : "ecc21857f5032d057571b1230e8eb014", - "SpanId" : "7e2d0530e1bf8106", - "ParentSpanId" : "c819bede56087c3d", - "TraceState" : "", - "SpanName" : "HTTP GET", - "SpanKind" : "SPAN_KIND_CLIENT", - "ServiceName" : "tsc-service-iotdev", - "ResourceAttributes" : "{'telemetry.sdk.version':'1.5.1','service.layer':'masastack','service.name':'tsc-service-iotdev','service.namespace':'Development','service.version':'1.0-Prev','service.instance.id':'2efa4321-1f36-441a-bb1c-8eb25bc894dc','telemetry.sdk.name':'opentelemetry','telemetry.sdk.language':'dotnet'}", - "ScopeName" : "OpenTelemetry.Instrumentation.Http.HttpClient", - "ScopeVersion" : "1.0.0.0", - "SpanAttributes" : "{'http.scheme':'http','http.method':'GET','net.peer.port':'30090','http.flavor':'1.1','host.name':'Lonsid-52','user_agent.original':'','http.status_code':'200','peer.service':'127.0.0.1:9090','net.peer.name':'127.0.0.1','http.url':'http:\/\/127.0.0.1:9090\/api\/v1\/label\/__name__\/values?lable=__name__'}", - "Duration" : 105716900, - "StatusCode" : "STATUS_CODE_UNSET", - "StatusMessage" : "", - "Events.Timestamp" : "[]", - "Events.Name" : "[]", - "Events.Attributes" : "[]", - "Links.TraceId" : "[]", - "Links.SpanId" : "[]", - "Links.TraceState" : "[]", - "Links.Attributes" : "[]" - }, - { - "Timestamp" : "2024-01-03T22:02:12.656Z", - "TraceId" : "ecc21857f5032d057571b1230e8eb014", - "SpanId" : "c819bede56087c3d", - "ParentSpanId" : "1ad3ed80e6cd7563", - "TraceState" : "", - "SpanName" : "\/api\/metric\/multi-range", - "SpanKind" : "SPAN_KIND_SERVER", - "ServiceName" : "tsc-service-iotdev", - "ResourceAttributes" : "{'telemetry.sdk.name':'opentelemetry','telemetry.sdk.language':'dotnet','telemetry.sdk.version':'1.5.1','service.layer':'masastack','service.name':'tsc-service-iotdev','service.namespace':'Development','service.version':'1.0-Prev','service.instance.id':'2efa4321-1f36-441a-bb1c-8eb25bc894dc'}", - "ScopeName" : "OpenTelemetry.Instrumentation.AspNetCore", - "ScopeVersion" : "1.0.0.0", - "SpanAttributes" : "{'http.client_ip':'','http.target':'\/api\/metric\/multi-range','http.request_content_length':'328','http.status_code':'200','http.method':'GET','http.url':'http:\/\/localhost:18010\/api\/metric\/multi-range','http.flavor':'HTTP\/1.1','http.request_content_type':'application\/json; charset=utf-8','authorization':'Bearer token','host.name':'Lonsid-52','http.response_content_type':'application\/json; charset=utf-8','net.host.port':'18010','http.scheme':'http','user_agent.original':'','http.request_content_body':'{\"Layer\": null,\"Service\": null,\"Instance\": null,\"EndPoint\": null,\"Start\":\"2024-01-03T18:02:12.1674699Z\",\"End\":\"2024-01-04T06:02:12.1674699Z\",\"Step\":\"172s\",\"MetricNames\":[\"round(sum (increase(http_server_duration_count[1m])),1)\",\"round(sum (increase(http_server_duration_sum[1m]))\/sum (increase(http_server_duration_count[1m])),1)\"]}','net.host.name':'localhost'}", - "Duration" : 490802200, - "StatusCode" : "STATUS_CODE_UNSET", - "StatusMessage" : "", - "Events.Timestamp" : "[]", - "Events.Name" : "[]", - "Events.Attributes" : "[]", - "Links.TraceId" : "[]", - "Links.SpanId" : "[]", - "Links.TraceState" : "[]", - "Links.Attributes" : "[]" - }, - { - "Timestamp" : "2024-01-03T22:02:12.391Z", - "TraceId" : "bfad12923f64935cec97f5e3dd5b9a47", - "SpanId" : "f7d9f646dbfc500d", - "ParentSpanId" : "", - "TraceState" : "", - "SpanName" : "tsc_iotdev", - "SpanKind" : "SPAN_KIND_CLIENT", - "ServiceName" : "tsc-service-iotdev", - "ResourceAttributes" : "{'telemetry.sdk.language':'dotnet','telemetry.sdk.version':'1.5.1','service.layer':'masastack','service.name':'tsc-service-iotdev','service.namespace':'Development','service.version':'1.0-Prev','service.instance.id':'2efa4321-1f36-441a-bb1c-8eb25bc894dc','telemetry.sdk.name':'opentelemetry'}", - "ScopeName" : "OpenTelemetry.Instrumentation.EntityFrameworkCore", - "ScopeVersion" : "1.0.0.7", - "SpanAttributes" : "{'peer.service':'127.0.0.1,1433','db.statement_type':'Text','db.statement':'SELECT TOP(@ __p_0) [i].[Id], [i].[Content], [i].[CreationTime], [i].[EventId], [i].[EventTypeName], [i].[ExpandContent], [i].[ModificationTime], [i].[RowVersion], [i].[State], [i].[TimesSent], [i].[TransactionId]\\r\\nFROM [tsc].[IntegrationEventLog] AS [i]\\r\\nWHERE [i].[State] = 0\\r\\nORDER BY [i].[CreationTime]','db.system':'mssql','db.name':'tsc_iotdev'}", - "Duration" : 145378900, - "StatusCode" : "STATUS_CODE_UNSET", - "StatusMessage" : "", - "Events.Timestamp" : "[]", - "Events.Name" : "[]", - "Events.Attributes" : "[]", - "Links.TraceId" : "[]", - "Links.SpanId" : "[]", - "Links.TraceState" : "[]", - "Links.Attributes" : "[]" - }, - { - "Timestamp" : "2024-01-03T22:02:12.372Z", - "TraceId" : "bca3e932f72628858f040df98172fa09", - "SpanId" : "e7591443dde17f6e", - "ParentSpanId" : "2700571f3f7589d4", - "TraceState" : "", - "SpanName" : "\/api\/trace\/list", - "SpanKind" : "SPAN_KIND_SERVER", - "ServiceName" : "tsc-service-iotdev", - "ResourceAttributes" : "{'telemetry.sdk.language':'dotnet','telemetry.sdk.version':'1.5.1','service.layer':'masastack','service.name':'tsc-service-iotdev','service.namespace':'Development','service.version':'1.0-Prev','service.instance.id':'2efa4321-1f36-441a-bb1c-8eb25bc894dc','telemetry.sdk.name':'opentelemetry'}", - "ScopeName" : "OpenTelemetry.Instrumentation.AspNetCore", - "ScopeVersion" : "1.0.0.0", - "SpanAttributes" : "{'net.host.name':'localhost','authorization':'Bearer token','user_agent.original':'','http.status_code':'200','net.host.port':'18010','http.url':'http:\/\/localhost:18010\/api\/trace\/list?Start=2024\/1\/3%2018:02:12&End=2024\/1\/4%206:02:12&IsDesc=True&IsError=False&Page=1&PageSize=10','http.client_ip':'','host.name':'Lonsid-52','http.scheme':'http','http.target':'\/api\/trace\/list','http.method':'GET','http.flavor':'HTTP\/1.1','http.response_content_type':'application\/json; charset=utf-8'}", - "Duration" : 243969100, - "StatusCode" : "STATUS_CODE_UNSET", - "StatusMessage" : "", - "Events.Timestamp" : "[]", - "Events.Name" : "[]", - "Events.Attributes" : "[]", - "Links.TraceId" : "[]", - "Links.SpanId" : "[]", - "Links.TraceState" : "[]", - "Links.Attributes" : "[]" - }, - { - "Timestamp" : "2024-01-03T22:02:12.186Z", - "TraceId" : "15a58db826237e3c2f9ff872c10f1e27", - "SpanId" : "55fdbbb0b5755535", - "ParentSpanId" : "28acb93474b6ddf7", - "TraceState" : "", - "SpanName" : "\/api\/trace\/attr-values", - "SpanKind" : "SPAN_KIND_SERVER", - "ServiceName" : "tsc-service-iotdev", - "ResourceAttributes" : "{'service.instance.id':'2efa4321-1f36-441a-bb1c-8eb25bc894dc','telemetry.sdk.name':'opentelemetry','telemetry.sdk.language':'dotnet','telemetry.sdk.version':'1.5.1','service.layer':'masastack','service.name':'tsc-service-iotdev','service.namespace':'Development','service.version':'1.0-Prev'}", - "ScopeName" : "OpenTelemetry.Instrumentation.AspNetCore", - "ScopeVersion" : "1.0.0.0", - "SpanAttributes" : "{'http.request_content_body':'{\"Name\": null,\"Alias\": null,\"Type\":6,\"MaxCount\":1000,\"Interval\": null,\"AllValue\": false,\"TraceId\": null,\"Service\":\"\",\"Instance\": null,\"Endpoint\": null,\"Keyword\": null,\"Start\":\"2024-01-03T18:02:12.1674699Z\",\"End\":\"2024-01-04T06:02:12.1674699Z\",\"RawQuery\": null,\"Conditions\": null,\"Sort\": null,\"Page\":1,\"PageSize\":20}','net.host.name':'localhost','http.method':'GET','http.target':'\/api\/trace\/attr-values','http.flavor':'HTTP\/1.1','user_agent.original':'','http.url':'http:\/\/localhost:18010\/api\/trace\/attr-values','http.request_content_type':'application\/json; charset=utf-8','host.name':'Lonsid-52','net.host.port':'18010','http.scheme':'http','authorization':'Bearer token','http.client_ip':'','http.request_content_length':'304','http.status_code':'200','http.response_content_type':'application\/json; charset=utf-8'}", - "Duration" : 126784100, - "StatusCode" : "STATUS_CODE_UNSET", - "StatusMessage" : "", - "Events.Timestamp" : "[]", - "Events.Name" : "[]", - "Events.Attributes" : "[]", - "Links.TraceId" : "[]", - "Links.SpanId" : "[]", - "Links.TraceState" : "[]", - "Links.Attributes" : "[]" - }, - { - "Timestamp" : "2024-01-03T22:02:12.089Z", - "TraceId" : "135eada26529589440f22dd55b6a6975", - "SpanId" : "14864123964f693f", - "ParentSpanId" : "18ead6cf4f8b0d1d", - "TraceState" : "", - "SpanName" : "\/api\/trace\/errorStatus", - "SpanKind" : "SPAN_KIND_SERVER", - "ServiceName" : "tsc-service-iotdev", - "ResourceAttributes" : "{'telemetry.sdk.name':'opentelemetry','telemetry.sdk.language':'dotnet','telemetry.sdk.version':'1.5.1','service.layer':'masastack','service.name':'tsc-service-iotdev','service.namespace':'Development','service.version':'1.0-Prev','service.instance.id':'2efa4321-1f36-441a-bb1c-8eb25bc894dc'}", - "ScopeName" : "OpenTelemetry.Instrumentation.AspNetCore", - "ScopeVersion" : "1.0.0.0", - "SpanAttributes" : "{'net.host.name':'localhost','http.target':'\/api\/trace\/errorStatus','user_agent.original':'','authorization':'Bearer token','http.client_ip':'','host.name':'Lonsid-52','http.status_code':'200','http.method':'GET','http.scheme':'http','http.url':'http:\/\/localhost:18010\/api\/trace\/errorStatus','net.host.port':'18010','http.flavor':'HTTP\/1.1','http.response_content_type':'application\/json; charset=utf-8'}", - "Duration" : 2004400, - "StatusCode" : "STATUS_CODE_UNSET", - "StatusMessage" : "", - "Events.Timestamp" : "[]", - "Events.Name" : "[]", - "Events.Attributes" : "[]", - "Links.TraceId" : "[]", - "Links.SpanId" : "[]", - "Links.TraceState" : "[]", - "Links.Attributes" : "[]" - }, - { - "Timestamp" : "2024-01-03T22:02:11.273Z", - "TraceId" : "5f0982d9ca0972fe0c90e87376477ec8", - "SpanId" : "f7f20f341b595a6c", - "ParentSpanId" : "", - "TraceState" : "", - "SpanName" : "tsc_iotdev", - "SpanKind" : "SPAN_KIND_CLIENT", - "ServiceName" : "tsc-service-iotdev", - "ResourceAttributes" : "{'service.name':'tsc-service-iotdev','service.namespace':'Development','service.version':'1.0-Prev','service.instance.id':'2efa4321-1f36-441a-bb1c-8eb25bc894dc','telemetry.sdk.name':'opentelemetry','telemetry.sdk.language':'dotnet','telemetry.sdk.version':'1.5.1','service.layer':'masastack'}", - "ScopeName" : "OpenTelemetry.Instrumentation.EntityFrameworkCore", - "ScopeVersion" : "1.0.0.7", - "SpanAttributes" : "{'db.system':'mssql','db.name':'tsc_iotdev','peer.service':'127.0.0.1,1433','db.statement_type':'Text','db.statement':'SELECT TOP(@ __p_0) [i].[Id], [i].[Content], [i].[CreationTime], [i].[EventId], [i].[EventTypeName], [i].[ExpandContent], [i].[ModificationTime], [i].[RowVersion], [i].[State], [i].[TimesSent], [i].[TransactionId]\\r\\nFROM [tsc].[IntegrationEventLog] AS [i]\\r\\nWHERE [i].[State] = 0\\r\\nORDER BY [i].[CreationTime]'}", - "Duration" : 98267900, - "StatusCode" : "STATUS_CODE_UNSET", - "StatusMessage" : "", - "Events.Timestamp" : "[]", - "Events.Name" : "[]", - "Events.Attributes" : "[]", - "Links.TraceId" : "[]", - "Links.SpanId" : "[]", - "Links.TraceState" : "[]", - "Links.Attributes" : "[]" - }, - { - "Timestamp" : "2024-01-03T22:02:10.179Z", - "TraceId" : "6b0fde523c65d18862f50ed99aa6f85e", - "SpanId" : "6ad9e25caa8f4f28", - "ParentSpanId" : "", - "TraceState" : "", - "SpanName" : "tsc_iotdev", - "SpanKind" : "SPAN_KIND_CLIENT", - "ServiceName" : "tsc-service-iotdev", - "ResourceAttributes" : "{'service.namespace':'Development','service.version':'1.0-Prev','service.instance.id':'2efa4321-1f36-441a-bb1c-8eb25bc894dc','telemetry.sdk.name':'opentelemetry','telemetry.sdk.language':'dotnet','telemetry.sdk.version':'1.5.1','service.layer':'masastack','service.name':'tsc-service-iotdev'}", - "ScopeName" : "OpenTelemetry.Instrumentation.EntityFrameworkCore", - "ScopeVersion" : "1.0.0.7", - "SpanAttributes" : "{'db.name':'tsc_iotdev','peer.service':'127.0.0.1,1433','db.statement_type':'Text','db.statement':'SELECT TOP(@ __p_0) [i].[Id], [i].[Content], [i].[CreationTime], [i].[EventId], [i].[EventTypeName], [i].[ExpandContent], [i].[ModificationTime], [i].[RowVersion], [i].[State], [i].[TimesSent], [i].[TransactionId]\\r\\nFROM [tsc].[IntegrationEventLog] AS [i]\\r\\nWHERE [i].[State] = 0\\r\\nORDER BY [i].[CreationTime]','db.system':'mssql'}", - "Duration" : 91859100, - "StatusCode" : "STATUS_CODE_UNSET", - "StatusMessage" : "", - "Events.Timestamp" : "[]", - "Events.Name" : "[]", - "Events.Attributes" : "[]", - "Links.TraceId" : "[]", - "Links.SpanId" : "[]", - "Links.TraceState" : "[]", - "Links.Attributes" : "[]" - }, - { - "Timestamp" : "2024-01-03T22:02:09.654Z", - "TraceId" : "87a81d697be817ff9e48f7bc80f57301", - "SpanId" : "65f6fdf66547dfad", - "ParentSpanId" : "eb3a1ae54e324251", - "TraceState" : "", - "SpanName" : "\/api\/log\/list", - "SpanKind" : "SPAN_KIND_SERVER", - "ServiceName" : "tsc-service-iotdev", - "ResourceAttributes" : "{'service.namespace':'Development','service.version':'1.0-Prev','service.instance.id':'2efa4321-1f36-441a-bb1c-8eb25bc894dc','telemetry.sdk.name':'opentelemetry','telemetry.sdk.language':'dotnet','telemetry.sdk.version':'1.5.1','service.layer':'masastack','service.name':'tsc-service-iotdev'}", - "ScopeName" : "OpenTelemetry.Instrumentation.AspNetCore", - "ScopeVersion" : "1.0.0.0", - "SpanAttributes" : "{'user_agent.original':'','net.host.port':'18010','http.target':'\/api\/log\/list','http.url':'http:\/\/localhost:18010\/api\/log\/list?Query=a=\\'test\\'&Start=2024\/1\/3%2014:47:23&End=2024\/1\/4%202:47:23&IsDesc=True&Page=1&PageSize=10','authorization':'Bearer token','host.name':'Lonsid-52','http.scheme':'http','http.method':'GET','http.client_ip':'','http.status_code':'500','net.host.name':'localhost','http.response_content_type':'text\/plain; charset=utf-8','http.flavor':'HTTP\/1.1'}", - "Duration" : 283681400, - "StatusCode" : "STATUS_CODE_ERROR", - "StatusMessage" : "", - "Events.Timestamp" : "[]", - "Events.Name" : "[]", - "Events.Attributes" : "[]", - "Links.TraceId" : "[]", - "Links.SpanId" : "[]", - "Links.TraceState" : "[]", - "Links.Attributes" : "[]" - }, - { - "Timestamp" : "2024-01-03T22:02:09.630Z", - "TraceId" : "d6ad209686047701802cbe32b8f3345e", - "SpanId" : "b243c61dabdd4676", - "ParentSpanId" : "630bb5b95c34b166", - "TraceState" : "", - "SpanName" : "\/api\/log\/list", - "SpanKind" : "SPAN_KIND_SERVER", - "ServiceName" : "tsc-service-iotdev", - "ResourceAttributes" : "{'service.version':'1.0-Prev','service.instance.id':'2efa4321-1f36-441a-bb1c-8eb25bc894dc','telemetry.sdk.name':'opentelemetry','telemetry.sdk.language':'dotnet','telemetry.sdk.version':'1.5.1','service.layer':'masastack','service.name':'tsc-service-iotdev','service.namespace':'Development'}", - "ScopeName" : "OpenTelemetry.Instrumentation.AspNetCore", - "ScopeVersion" : "1.0.0.0", - "SpanAttributes" : "{'http.response_content_type':'text\/plain; charset=utf-8','net.host.name':'localhost','http.scheme':'http','http.target':'\/api\/log\/list','http.status_code':'500','authorization':'Bearer token','host.name':'Lonsid-52','net.host.port':'18010','http.method':'GET','http.flavor':'HTTP\/1.1','http.url':'http:\/\/localhost:18010\/api\/log\/list?Query=a=\\'test\\'&Start=2024\/1\/3%2014:47:23&End=2024\/1\/4%202:47:23&IsDesc=True&Page=1&PageSize=10','user_agent.original':'','http.client_ip':''}", - "Duration" : 309668700, - "StatusCode" : "STATUS_CODE_ERROR", - "StatusMessage" : "", - "Events.Timestamp" : "[]", - "Events.Name" : "[]", - "Events.Attributes" : "[]", - "Links.TraceId" : "[]", - "Links.SpanId" : "[]", - "Links.TraceState" : "[]", - "Links.Attributes" : "[]" - } -] \ No newline at end of file diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests.csproj deleted file mode 100644 index b84fe471b..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests.csproj +++ /dev/null @@ -1,28 +0,0 @@ - - - - enable - enable - false - true - - - - - - - - - - - - - - - - - Always - - - - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/TestUtils.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/TestUtils.cs deleted file mode 100644 index 636292590..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/TestUtils.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests; - -internal class TestUtils -{ - public const string ConnectionString = "Compress=True;CheckCompressedHash=False;Compressor=lz4;SocketTimeout=10000;Host=localhost;Port=9000;Database=default;User=default"; - //public const string ConnectionString = "Compress=True;CheckCompressedHash=False;Compressor=lz4;SocketTimeout=10000;Host=192.168.51.234;Port=19003;User=test;Password=123456;Database=default"; -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/_Imports.cs deleted file mode 100644 index f2df84947..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Tests/_Imports.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using ClickHouse.Ado; -global using Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models; -global using Masa.Contrib.StackSdks.Tsc.Apm.Clickhouse.Models.Request; -global using Masa.Contrib.StackSdks.Tsc.Clickhouse; -global using Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.Extensions.Logging; -global using Microsoft.VisualStudio.TestTools.UnitTesting; diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Common.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Common.cs deleted file mode 100644 index 41197fa56..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Common.cs +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests; - -public class Common -{ - public static void InitTable(bool isLog, IDbConnection connection) - { - var name = isLog ? "log" : "trace"; - if (connection.State == ConnectionState.Closed) - connection.Open(); - using var cmd = connection.CreateCommand(); - var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Data/otel_{name}.txt"); - using var reader = new StreamReader(path); - - var sql = reader.ReadToEnd(); - cmd.CommandText = sql; - try - { - cmd.ExecuteNonQuery(); - } - catch - { - //table is exists - } - - } - - public static void InitTableData(bool isLog, string rootPath, IDbConnection connection) - { - var name = isLog ? "log" : "trace"; - if (connection.State == ConnectionState.Closed) - connection.Open(); - using var cmd = connection.CreateCommand(); - var path = Path.Combine(rootPath, $"Data/otel_{name}_data.txt"); - using var dataReader = new StreamReader(path); - var sql = dataReader.ReadToEnd(); - cmd.CommandText = sql; - cmd.ExecuteNonQuery(); - } - - public static void InitTableJsonData(bool isLog, string rootPath, IDbConnection connection) - { - var name = isLog ? "log" : "trace"; - if (connection.State == ConnectionState.Closed) - connection.Open(); - using var cmd = connection.CreateCommand(); - cmd.CommandText = $"select count() from otel_{name}s"; - var count = Convert.ToInt32(cmd.ExecuteScalar()); - if (count > 0) - return; - var path = Path.Combine(rootPath, $"Data/otel_{name}_data.json"); - using var dataReader = new StreamReader(path); - var data = dataReader.ReadToEnd(); - var sql = GetInsertSql(data, $"otel_{name}s"); - cmd.CommandText = sql; - cmd.ExecuteNonQuery(); - } - - private static string? GetInsertSql(string jsonData, string table = "ttttttt") - { - var data = JsonSerializer.Deserialize(jsonData); - if (data == null || data.Length == 0) - return default; - - var header = new StringBuilder($"insert into {table}"); - header.Append('(').AppendLine(); - bool isFirst = true; - var sql = new StringBuilder(); - foreach (var jsonNode in data) - { - sql.Append('('); - foreach (var item in jsonNode.EnumerateObject()) - { - if (isFirst) - { - header.Append($"{item.Name},"); - } - if (item.Value.ValueKind == JsonValueKind.Number) - sql.Append($"{item.Value},"); - else if (item.Value.TryGetDateTime(out var time)) - sql.Append($"'{time.ToString("yyyy-MM-dd HH:mm:ss.ffff")}',"); - else - sql.Append($"'{item.Value.ToString().Replace("\\'", "''").Replace("'", "''").Replace("@", "")}',"); - } - sql.Remove(sql.Length - 1, 1).AppendLine("),"); - isFirst = false; - } - header.Remove(header.Length - 1, 1).Append(')').AppendLine().Append("values").AppendLine().Append(sql.Remove(sql.Length - 1, 1)); - return header.ToString(); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Consts.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Consts.cs deleted file mode 100644 index 738be3cc6..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Consts.cs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests; - -internal class Consts -{ - public const string ConnectionString = "Compress=True;CheckCompressedHash=False;Compressor=lz4;SocketTimeout=5000;Host=localhost;Port=9000;Database=default;User=default"; - //public const string ConnectionString = "Compress=True;CheckCompressedHash=False;Compressor=lz4;SocketTimeout=5000;Host=192.168.51.234;Port=19003;Database=default;User=default"; -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_log.txt b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_log.txt deleted file mode 100644 index ce5111e75..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_log.txt +++ /dev/null @@ -1,57 +0,0 @@ -CREATE TABLE otel_logs -( - `Timestamp` DateTime64(9) CODEC(Delta(8), ZSTD(1)), - - `TraceId` String CODEC(ZSTD(1)), - - `SpanId` String CODEC(ZSTD(1)), - - `TraceFlags` UInt32 CODEC(ZSTD(1)), - - `SeverityText` LowCardinality(String) CODEC(ZSTD(1)), - - `SeverityNumber` Int32 CODEC(ZSTD(1)), - - `ServiceName` LowCardinality(String) CODEC(ZSTD(1)), - - `Body` String CODEC(ZSTD(1)), - - `ResourceSchemaUrl` String CODEC(ZSTD(1)), - - `ResourceAttributes` Map(LowCardinality(String), String) CODEC(ZSTD(1)), - - `ScopeSchemaUrl` String CODEC(ZSTD(1)), - - `ScopeName` String CODEC(ZSTD(1)), - - `ScopeVersion` String CODEC(ZSTD(1)), - - `ScopeAttributes` Map(LowCardinality(String), String) CODEC(ZSTD(1)), - - `LogAttributes` Map(LowCardinality(String), String) CODEC(ZSTD(1)), - - INDEX idx_trace_id TraceId TYPE bloom_filter(0.001) GRANULARITY 1, - - INDEX idx_res_attr_key mapKeys(ResourceAttributes) TYPE bloom_filter(0.01) GRANULARITY 1, - - INDEX idx_res_attr_value mapValues(ResourceAttributes) TYPE bloom_filter(0.01) GRANULARITY 1, - - INDEX idx_scope_attr_key mapKeys(ScopeAttributes) TYPE bloom_filter(0.01) GRANULARITY 1, - - INDEX idx_scope_attr_value mapValues(ScopeAttributes) TYPE bloom_filter(0.01) GRANULARITY 1, - - INDEX idx_log_attr_key mapKeys(LogAttributes) TYPE bloom_filter(0.01) GRANULARITY 1, - - INDEX idx_log_attr_value mapValues(LogAttributes) TYPE bloom_filter(0.01) GRANULARITY 1, - - INDEX idx_body Body TYPE tokenbf_v1(32768, 3, 0) GRANULARITY 1 -) -ENGINE = MergeTree -PARTITION BY toDate(Timestamp) -ORDER BY (ServiceName, - SeverityText, - toUnixTimestamp(Timestamp), - TraceId) -TTL toDateTime(Timestamp) + toIntervalDay(30) -SETTINGS index_granularity = 8192, - ttl_only_drop_parts = 1; \ No newline at end of file diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_log_data.txt b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_log_data.txt deleted file mode 100644 index a8ead19ac..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_log_data.txt +++ /dev/null @@ -1,5 +0,0 @@ -INSERT INTO otel_logs (`Timestamp`, TraceId, SpanId, TraceFlags, SeverityText, SeverityNumber, ServiceName, Body, ResourceSchemaUrl, ResourceAttributes, ScopeSchemaUrl, ScopeName, ScopeVersion, ScopeAttributes, LogAttributes) -VALUES -('2023-11-02 09:59:21.282', '3a749e0df4bde3713ea47ed0b8efe83f', '97ef48656ca34d09', 1, 'Information', 9, 'service', 'DrinkingCubeProMqOperation received:2120872750', '', '{''service.namespace'':''Staging'',''service.version'':''1.0.0'',''service.instance.id'':''f14beab6-1632-4262-8434-f545e5892ae4'',''telemetry.sdk.name'':''opentelemetry'',''telemetry.sdk.language'':''dotnet'',''telemetry.sdk.version'':''1.5.1'',''service.layer'':''service'',''service.name'':''service''}', '', '', '', '{}', '{''dotnet.ilogger.category'':''Service.DrinkingCubePro.IoTDrinkingCubeProSubService'',''{OriginalFormat}'':''DrinkingCubeProMqOperation received:2120872750'',''SpanId'':''97ef48656ca34d09'',''TraceId'':''3a749e0df4bde3713ea47ed0b8efe83f'',''ParentId'':''0000000000000000''}'), -('2023-11-02 09:59:20.434', 'c119aa7717eea47be25332c82ceeff2e', '2158ac1037130e81', 1, 'Information', 9, 'service', 'DrinkingCubeProMqOperation received:2102801854', '', '{''service.name'':''service'',''service.namespace'':''Test'',''service.version'':''1.0.0'',''service.instance.id'':''c6bcf682-8028-44bd-92d2-188b99658ce3'',''telemetry.sdk.name'':''opentelemetry'',''telemetry.sdk.language'':''dotnet'',''telemetry.sdk.version'':''1.5.1'',''service.layer'':''service''}', '', '', '', '{}', '{''TraceId'':''c119aa7717eea47be25332c82ceeff2e'',''ParentId'':''0000000000000000'',''dotnet.ilogger.category'':''Device.Service.DrinkingCubePro.IoTDrinkingCubeProSubService'',''{OriginalFormat}'':''DrinkingCubeProMqOperation received:2102801854'',''SpanId'':''2158ac1037130e81''}'), -('2023-11-02 09:59:20.375', '9f6eb756b0368219564bbfad593477f7', '6717dd37c6bbe77a', 1, 'Information', 9, 'service', 'KafKa写入{"type":2,"dataType":1,"content":"{\"appProperty\":{\"dataTimestamp\":1698919160336,\"datastream\":\"dp_upload\",\"deviceId\":\"10001\"},\"body\":{\"common\":{\"iot_uid\":\"100008\",\"mode\":\"0\",\"rssi\":\"10,99\",\"serial\":100001},\"data\":\"hVRDJl/wyQHEkxJ5/xNQp/N7aJTowIpyxtxzUvDABVwMPki1u7b85soGhmGBDoi0W+ySz4J8XU1jRzIbrprEcG0dGA9xoobdFL4N0rL+GiI0xxHxSqr/r1xjnscD8P1VR64aJYq9dBXsN37n/R3F+BYkWXagAczqmLUQvDe56ZPQEmnAHM1pL4BanNw9vAu5aShEHg2TR2z1WpG2NOrAug==\"},\"sysProperty\":{\"messageType\":\"deviceDatapoint\",\"productId\":\"300888\"},\"PubTime\":1698919160408}","deviceInfoId":"8F5D73CD-87A4-4128-BD7C-E0ACB9CCAA00","serial":"1684450839","result":"","decodeContent":"{\"curState\":\"2\",\"totalWater\":\"2272\",\"WaterFlow\":\"261\",\"life1\":\"100000\",\"life2\":\"72126\",\"life4\"\"life5\"\"max_life1\":\"100000\",\"max_life2\":\"100000\",\"max_life3\"\"max_life4\"\"max_life5\"\"active1\":\"1267478839\",\"active2\":\"68360197\",\"active3\"\"active4\"\"active5\"\"inWater\":\"105\",\"pureWater\":\"3\",\"alarm\":\"1\",\"Lock\":\"2\",\"inWaterOffset\":\"0\",\"pureWaterOffset\":\"0\",\"Wash\":\"0\",\"totalWater_filter_1\":\"2272\",\"totalWater_filter_2\":\"2272\",\"totalWater_filter_3\"\"totalWater_filter_4\"\"totalWater_filter_5\"\"water_temp\":\"26\",\"work_mode\":\"0\"}","mode":"0","communicationMethod":"","isDeleted""deleterUserId":"00000000-0000-0000-0000-000000000000","deletionTime":"0001-01-01T00:00:00","creationTime":"2023-11-02T09:59:20.354","creatorUserId":"00000000-0000-0000-0000-000000000000","lastModificationTime":"2023-11-02T09:59:20.3692973Z","lastModifierUserId":"00000000-0000-0000-0000-000000000000","id":"38239f21-2629-4a9b-a27e-8e97c6b775f4"}', '', '{''service.layer'':''service'',''service.name'':''service'',''service.namespace'':''Test'',''service.version'':''1.0.0'',''service.instance.id'':''c6bcf682-8028-44bd-92d2-188b99658ce3'',''telemetry.sdk.name'':''opentelemetry'',''telemetry.sdk.language'':''dotnet'',''telemetry.sdk.version'':''1.5.1''}', '', '', '', '{}', '{''RequestId'':''0HMUQMQ237O8Q:00000BF7'',''RequestPath'':''/api/iotsub/MQOperation'',''dotnet.ilogger.category'':''Services.Device.Infrastructure.Repositories.MessageRepository'',''{OriginalFormat}'':''KafKa写入{"type":2,"dataType":1,"content":"{\\"appProperty\\":{\\"dataTimestamp\\":1698919160336,\\"datastream\\":\\"dp_upload\\",\\"deviceId\\":\\"787320964\\"},\\"body\\":{\\"common\\":{\\"iot_uid\\":\\"10000008\\",\\"mode\\":\\"0\\",\\"rssi\\":\\"10,99\\",\\"serial\\":1684450839},\\"data\\":\\"hVRDJl/wyQHEkxJ5/xNQp/N7aJTowIpyxtxzUvDABVwMPki1u7b85soGhmGBDoi0W+ySz4J8XU1jRzIbrprEcG0dGA9xoobdFL4N0rL+GiI0xxHxSqr/r1xjnscD8P1VR64aJYq9dBXsN37n/R3F+BYkWXagAczqmLUQvDe56ZPQEmnAHM1pL4BanNw9vAu5aShEHg2TR2z1WpG2NOrAug==\\"},\\"sysProperty\\":{\\"messageType\\":\\"deviceDatapoint\\",\\"productId\\":\\"300888\\"},\\"PubTime\\":1698919160408}","deviceInfoId":"dcd65148-ab5c-44ec-940a-038aad7114cc","serial":"1684450839","result":"","decodeContent":"{\\"curState\\":\\"2\\",\\"totalWater\\":\\"2272\\",\\"WaterFlow\\":\\"261\\",\\"life1\\":\\"100000\\",\\"life2\\":\\"72126\\",\\"life3\\"\\"life4\\"\\"life5\\"\\"max_life1\\":\\"100000\\",\\"max_life2\\":\\"100000\\",\\"max_life3\\"\\"max_life4\\"\\"max_life5\\"\\"active1\\":\\"1267478839\\",\\"active2\\":\\"68360197\\",\\"active3\\"\\"active4\\"\\"active5\\"\\"inWater\\":\\"105\\",\\"pureWater\\":\\"3\\",\\"alarm\\":\\"1\\",\\"Lock\\":\\"2\\",\\"inWaterOffset\\":\\"0\\",\\"pureWaterOffset\\":\\"0\\",\\"Wash\\":\\"0\\",\\"totalWater_filter_1\\":\\"2272\\",\\"totalWater_filter_2\\":\\"2272\\",\\"totalWater_filter_3\\"\\"totalWater_filter_4\\"\\"totalWater_filter_5\\"\\"water_temp\\":\\"26\\",\\"work_mode\\":\\"0\\"}","mode":"0","communicationMethod":"","isDeleted""deleterUserId":"00000000-0000-0000-0000-000000000000","deletionTime":"0001-01-01T00:00:00","creationTime":"2023-11-02T09:59:20.354","creatorUserId":"00000000-0000-0000-0000-000000000000","lastModificationTime":"2023-11-02T09:59:20.3692973Z","lastModifierUserId":"00000000-0000-0000-0000-000000000000","id":"38239f21-2629-4a9b-a27e-8e97c6b775f4"}'',''SpanId'':''6717dd37c6bbe77a'',''TraceId'':''9f6eb756b0368219564bbfad593477f7'',''ParentId'':''0000000000000000'',''ConnectionId'':''0HMUQMQ237O8Q''}'); diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_trace.txt b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_trace.txt deleted file mode 100644 index 0bc804ed9..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_trace.txt +++ /dev/null @@ -1,69 +0,0 @@ -CREATE TABLE otel_traces -( - - `Timestamp` DateTime64(9) CODEC(Delta(8), ZSTD(1)), - - `TraceId` String CODEC(ZSTD(1)), - - `SpanId` String CODEC(ZSTD(1)), - - `ParentSpanId` String CODEC(ZSTD(1)), - - `TraceState` String CODEC(ZSTD(1)), - - `SpanName` LowCardinality(String) CODEC(ZSTD(1)), - - `SpanKind` LowCardinality(String) CODEC(ZSTD(1)), - - `ServiceName` LowCardinality(String) CODEC(ZSTD(1)), - - `ResourceAttributes` Map(LowCardinality(String), String) CODEC(ZSTD(1)), - - `ScopeName` String CODEC(ZSTD(1)), - - `ScopeVersion` String CODEC(ZSTD(1)), - - `SpanAttributes` Map(LowCardinality(String), String) CODEC(ZSTD(1)), - - `Duration` Int64 CODEC(ZSTD(1)), - - `StatusCode` LowCardinality(String) CODEC(ZSTD(1)), - - `StatusMessage` String CODEC(ZSTD(1)), - - `Events.Timestamp` Array(DateTime64(9)) CODEC(ZSTD(1)), - - `Events.Name` Array(LowCardinality(String)) CODEC(ZSTD(1)), - - `Events.Attributes` Array(Map(LowCardinality(String), String)) CODEC(ZSTD(1)), - - `Links.TraceId` Array(String) CODEC(ZSTD(1)), - - `Links.SpanId` Array(String) CODEC(ZSTD(1)), - - `Links.TraceState` Array(String) CODEC(ZSTD(1)), - - `Links.Attributes` Array(Map(LowCardinality(String), String)) CODEC(ZSTD(1)), - - INDEX idx_trace_id TraceId TYPE bloom_filter(0.001) GRANULARITY 1, - - INDEX idx_res_attr_key mapKeys(ResourceAttributes) TYPE bloom_filter(0.01) GRANULARITY 1, - - INDEX idx_res_attr_value mapValues(ResourceAttributes) TYPE bloom_filter(0.01) GRANULARITY 1, - - INDEX idx_span_attr_key mapKeys(SpanAttributes) TYPE bloom_filter(0.01) GRANULARITY 1, - - INDEX idx_span_attr_value mapValues(SpanAttributes) TYPE bloom_filter(0.01) GRANULARITY 1, - - INDEX idx_duration Duration TYPE minmax GRANULARITY 1 -) -ENGINE = MergeTree -PARTITION BY toDate(Timestamp) -ORDER BY (ServiceName, - SpanName, - toUnixTimestamp(Timestamp), - TraceId) -TTL toDateTime(Timestamp) + toIntervalDay(30) -SETTINGS index_granularity = 8192, - ttl_only_drop_parts = 1; - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_trace_data.txt b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_trace_data.txt deleted file mode 100644 index 5b16494df..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Data/otel_trace_data.txt +++ /dev/null @@ -1,5 +0,0 @@ - INSERT INTO otel_traces (`Timestamp`, TraceId, SpanId, ParentSpanId, TraceState, SpanName, SpanKind, ServiceName, ResourceAttributes, ScopeName, ScopeVersion, SpanAttributes, Duration, StatusCode, StatusMessage, `Events.Timestamp`, `Events.Name`, `Events.Attributes`, `Links.TraceId`, `Links.SpanId`, `Links.TraceState`, `Links.Attributes`) -VALUES -('2023-11-02 09:39:30.865', '2821e37c871ee22bcc10b43ddd7ca657', '402f0ed4040433e6', '1c9a707a29a9e449', '', 'HTTP POST', 'SPAN_KIND_CLIENT', 'service', '{''service.instance.id'':''c56534c5-2f62-48e8-82a5-6d8ecdbdd7de'',''telemetry.sdk.name'':''opentelemetry'',''telemetry.sdk.language'':''dotnet'',''telemetry.sdk.version'':''1.5.1'',''service.layer'':''service'',''service.name'':''service'',''service.namespace'':''Test'',''service.version'':''1.0.0''}', 'OpenTelemetry.Instrumentation.Http.HttpClient', '1.0.0.0', '{''http.flavor'':''1.1'',''host.name'':''service-device-676656994-xbnnq'',''http.request_content_body'':''{"deviceInfoId":"5EF36830-438D-4B7F-BA15-AF3A138412BA","activeTime":"2022-03-26T03:15:56.878289","active1":"","active2":"","active3":"","active4":"","active5":"","life1":"","life2":"","life3":"","life4":"","life5":"","maxLife1":"","maxLife2":"","maxLife3":"","maxLife4":"","maxLife5":"","lock":""}'',''peer.service'':''127.0.0.1:3500'',''http.scheme'':''http'',''http.method'':''POST'',''net.peer.name'':''127.0.0.1'',''net.peer.port'':''3500'',''http.url'':''http://127.0.0.1:3500/v1.0/invoke/service/method/api/filter/ActivateDeviceFilter'',''http.status_code'':''200''}', 4828300, 'STATUS_CODE_UNSET', '', [], [], [], [], [], [], []), -('2023-11-02 09:39:30.865', '2821e37c871ee22bcc10b43ddd7ca657', '402f0ed4040433e6', '1c9a707a29a9e449', '', 'HTTP POST', 'SPAN_KIND_CLIENT', 'service', '{''service.instance.id'':''c56534c5-2f62-48e8-82a5-6d8ecdbdd7de'',''telemetry.sdk.name'':''opentelemetry'',''telemetry.sdk.language'':''dotnet'',''telemetry.sdk.version'':''1.5.1'',''service.layer'':''service'',''service.name'':''service'',''service.namespace'':''Test'',''service.version'':''1.0.0''}', 'OpenTelemetry.Instrumentation.Http.HttpClient', '1.0.0.0', '{''http.flavor'':''1.1'',''host.name'':''service-device-676656994-xbnnq'',''http.request_content_body'':''{"deviceInfoId":"C829B9EE-E911-44F8-8E74-1EF991DA6803","activeTime":"2022-03-26T03:15:56.878289","active1":"","active2":"","active3":"","active4":"","active5":"","life1":"","life2":"","life3":"","life4":"","life5":"","maxLife1":"","maxLife2":"","maxLife3":"","maxLife4":"","maxLife5":"","lock":""}'',''peer.service'':''127.0.0.1:3500'',''http.scheme'':''http'',''http.method'':''POST'',''net.peer.name'':''127.0.0.1'',''net.peer.port'':''3500'',''http.url'':''http://127.0.0.1:3500/v1.0/invoke/service/method/api/filter/ActivateDeviceFilter'',''http.status_code'':''200''}', 4828300, 'STATUS_CODE_UNSET', '', [], [], [], [], [], [], []), -('2023-11-02 09:39:30.865', '2821e37c871ee22bcc10b43ddd7ca657', '402f0ed4040433e6', '1c9a707a29a9e449', '', 'HTTP POST', 'SPAN_KIND_CLIENT', 'service', '{''service.instance.id'':''c56534c5-2f62-48e8-82a5-6d8ecdbdd7de'',''telemetry.sdk.name'':''opentelemetry'',''telemetry.sdk.language'':''dotnet'',''telemetry.sdk.version'':''1.5.1'',''service.layer'':''service'',''service.name'':''service'',''service.namespace'':''Test'',''service.version'':''1.0.0''}', 'OpenTelemetry.Instrumentation.Http.HttpClient', '1.0.0.0', '{''http.flavor'':''1.1'',''host.name'':''service-device-676656994-xbnnq'',''http.request_content_body'':''{"deviceInfoId":"8995f797-0385-4b27-9452-181eb0bb4079","activeTime":"2022-03-26T03:15:56.878289","active1":"","active2":"","active3":"","active4":"","active5":"","life1":"","life2":"","life3":"","life4":"","life5":"","maxLife1":"","maxLife2":"","maxLife3":"","maxLife4":"","maxLife5":"","lock":""}'',''peer.service'':''127.0.0.1:3500'',''http.scheme'':''http'',''http.method'':''POST'',''net.peer.name'':''127.0.0.1'',''net.peer.port'':''3500'',''http.url'':''http://127.0.0.1:3500/v1.0/invoke/service/method/api/filter/ActivateDeviceFilter'',''http.status_code'':''200''}', 4828300, 'STATUS_CODE_UNSET', '', [], [], [], [], [], [], []) \ No newline at end of file diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/LogServiceTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/LogServiceTests.cs deleted file mode 100644 index 463678ed2..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/LogServiceTests.cs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests; - -[TestClass] -public class LogServiceTests -{ - private static ILogService logService; - private static DateTime startTime = DateTime.Parse("2023-11-02 09:00:00"); - - [ClassInitialize] - public static void Initialized(TestContext testContext) - { - var connection = new ClickHouseConnection(Consts.ConnectionString); - Common.InitTable(true, connection); - Common.InitTable(false, connection); - var services = new ServiceCollection(); - services.AddLogging(builder => builder.AddConsole()); - services.AddMASAStackClickhouse(Consts.ConnectionString, "custom_log", "custom_trace"); - Common.InitTableData(true, AppDomain.CurrentDomain.BaseDirectory, connection); - logService = services.BuildServiceProvider().GetRequiredService(); - startTime -= MasaStackClickhouseConnection.TimeZone.BaseUtcOffset; - } - - [TestMethod] - public async Task QueryListTest() - { - var query = new BaseRequestDto - { - Page = 1, - PageSize = 10, - Start = startTime, - End = startTime.AddHours(1), - Keyword = "Kafka", - Conditions = new List { - new FieldConditionDto{ - Name="Resource.service.name", - Type= ConditionTypes.Equal, - Value="service" - }, - new FieldConditionDto{ - Name="Resource.service.namespace", - Type=ConditionTypes.NotEqual, - Value="Test" - }, - new FieldConditionDto{ - Name="Resource.service.name", - Type=ConditionTypes.In, - Value=new List{ "service" } - }, - new FieldConditionDto{ - Name="Resource.service.name", - Type= ConditionTypes.NotIn, - Value=new List{"a","b" } - } - }, - }; - var result = await logService.ListAsync(query); - Assert.IsNotNull(result); - } - - [TestMethod] - public async Task MappingTest() - { - var mapping = await logService.GetMappingAsync(); - Assert.IsNotNull(mapping); - } - - [TestMethod] - public async Task AggTest() - { - var request = new SimpleAggregateRequestDto - { - Name = "Resource.service.name", - Type = AggregateTypes.Count, - Start = startTime, - End = startTime.AddHours(1), - }; - var result = await logService.AggregateAsync(request); - Assert.IsNotNull(result); - var num1 = Convert.ToInt64(result); - - request.Name = "Timestamp"; - request.Type = AggregateTypes.DateHistogram; - request.Interval = "5m"; - result = await logService.AggregateAsync(request); - Assert.IsNotNull(result); - Assert.IsTrue(result is IEnumerable); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests.csproj deleted file mode 100644 index cad15cbfd..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests.csproj +++ /dev/null @@ -1,55 +0,0 @@ - - - - enable - enable - false - true - - - - - - - - - - - - Always - - - Always - - - Always - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - Always - - - - \ No newline at end of file diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/TraceServiceTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/TraceServiceTests.cs deleted file mode 100644 index 9d63a7596..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/TraceServiceTests.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests; - -[TestClass] -public class TraceServiceTests -{ - private static ITraceService traceService; - private static DateTime startTime = DateTime.Parse("2023-11-02 09:00:00"); - - [ClassInitialize] - public static void Initialized(TestContext testContext) - { - var services = new ServiceCollection(); - var connection = new ClickHouseConnection(Consts.ConnectionString); - services.AddLogging(builder => builder.AddConsole()); - services.AddMASAStackClickhouse(Consts.ConnectionString, "custom_log", "custom_trace"); - Common.InitTableData(false, AppDomain.CurrentDomain.BaseDirectory, connection); - traceService = services.BuildServiceProvider().GetRequiredService(); - startTime -= MasaStackClickhouseConnection.TimeZone.BaseUtcOffset; - } - - [TestMethod] - public async Task QueryListTest() - { - var query = new BaseRequestDto - { - Page = 1, - PageSize = 10, - Start = startTime, - End = startTime.AddHours(1) - }; - var result = await traceService.ListAsync(query); - Assert.IsNotNull(result); - } - - [TestMethod] - public async Task TraceIdTest() - { - var result = await traceService.GetAsync("3a749e0df4bde3713ea47ed0b8efe83f"); - Assert.IsNotNull(result); - } - - [TestMethod] - public async Task AggTest() - { - var request = new SimpleAggregateRequestDto - { - Name = "Resource.service.name", - Type = AggregateTypes.Count, - Start = startTime, - End = startTime.AddHours(1), - }; - var result = await traceService.AggregateAsync(request); - Assert.IsNotNull(result); - var num1 = Convert.ToInt64(result); - - request.Type = AggregateTypes.DistinctCount; - result = await traceService.AggregateAsync(request); - var num2 = Convert.ToInt64(result); - Assert.IsTrue(num1 - num2 >= 0); - - request.Type = AggregateTypes.GroupBy; - result = await traceService.AggregateAsync(request); - Assert.IsTrue(result is IEnumerable); - - request.Name = "Duration"; - request.Type = AggregateTypes.Avg; - result = await traceService.AggregateAsync(request); - - request.Type = AggregateTypes.Sum; - result = await traceService.AggregateAsync(request); - - request.Name = "Timestamp"; - request.Type = AggregateTypes.DateHistogram; - request.Interval = "5m"; - result = await traceService.AggregateAsync(request); - Assert.IsNotNull(result); - Assert.IsTrue(result is IEnumerable); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/_Imports.cs deleted file mode 100644 index 310c87f0a..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Clickhouse.Tests/_Imports.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using ClickHouse.Ado; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Model; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Model.Aggregate; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Service; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.Extensions.Logging; -global using Microsoft.VisualStudio.TestTools.UnitTesting; -global using System.Data; -global using System.Text; -global using System.Text.Json; diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Converts/LogConverterTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Converts/LogConverterTests.cs deleted file mode 100644 index 6625730ce..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Converts/LogConverterTests.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests.Converts; - -[TestClass] -public class LogConverterTests -{ - [TestMethod] - public void DeserializeTest() - { - var str = StaticConfig.GetJson("Convert:logJson"); - JsonSerializerOptions options = new(); - options.Converters.Add(new LogResponseDtoConverter()); - - var log = JsonSerializer.Deserialize(str, options); - Assert.IsNotNull(log); - Assert.IsNotNull(log.Resource); - Assert.IsNotNull(log.Attributes); - Assert.AreEqual(1, log.TraceFlags); - Assert.AreEqual(9, log.SeverityNumber); - Assert.AreEqual("Information", log.SeverityText); - Assert.AreEqual("277df6d0204f09fa63ff4ab896673455", log.TraceId); - Assert.AreEqual("1c495129b86de343", log.SpanId); - Assert.IsNotNull(log.Body); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Converts/TraceConverterTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Converts/TraceConverterTests.cs deleted file mode 100644 index 237c55d3d..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Converts/TraceConverterTests.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests.Converts; - -[TestClass] -public class TraceConverterTests -{ - [TestMethod] - public void DeserializeTest() - { - var str = StaticConfig.GetJson("Convert:traceJson"); - JsonSerializerOptions options = new(); - options.Converters.Add(new TraceResponseDtoConverter()); - - var trace = JsonSerializer.Deserialize(str, options); - Assert.IsNotNull(trace); - Assert.IsNotNull(trace.Resource); - Assert.IsNotNull(trace.Attributes); - Assert.AreEqual(0, trace.TraceStatus); - Assert.AreEqual("277df6d0204f09fa63ff4ab896673455", trace.TraceId); - Assert.AreEqual("1c495129b86de343", trace.SpanId); - Assert.IsNotNull(trace.Kind); - - var isHttp = trace.TryParseHttp(out var httpResult); - Assert.IsTrue(isHttp); - Assert.IsNotNull(httpResult); - Assert.IsNotNull(httpResult.Method); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Extensions/DictionaryExtenistionsTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Extensions/DictionaryExtenistionsTests.cs deleted file mode 100644 index 35cec63cc..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Extensions/DictionaryExtenistionsTests.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests.Extensions; - -[TestClass] -public class DictionaryExtenistionsTests -{ - readonly JsonSerializerOptions options = new() - { - PropertyNamingPolicy = JsonNamingPolicy.CamelCase - }; - - [TestMethod] - public void ConvertDicTest() - { - var str = "{\"a.name\":\"David\",\"a.age\":20,\"sex\":\"Male\"}"; - var dic = JsonSerializer.Deserialize>(str, options); - Assert.IsNotNull(dic); - var convert = dic.GroupByKeyPrefix("a."); - Assert.IsNotNull(convert); - Assert.IsTrue(convert.ContainsKey("name")); - Assert.IsTrue(convert.ContainsKey("age")); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Extensions/JsonElementExtensionsTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Extensions/JsonElementExtensionsTests.cs deleted file mode 100644 index 948b403f3..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Extensions/JsonElementExtensionsTests.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests.Extensions; - -[TestClass] -public class JsonElementExtensionsTests -{ - [TestMethod] - public void ArrayTest() - { - var str = "[]"; - var json = JsonSerializer.Deserialize(str); - var result = json.ConvertToKeyValuePairs(); - Assert.IsNull(result); - } - - [TestMethod] - public void ObjectTest() - { - var str = "{\"name\":\"David\"}"; - var json = JsonSerializer.Deserialize(str); - var result = json.ConvertToKeyValuePairs(); - Assert.IsNotNull(result); - Assert.IsTrue(result.Any()); - } - - [TestMethod] - public void MixObjectTest() - { - var str = "{\"name\":\"David\",\"age\":20,\"level\":[1,2,5,6],\"parent\":{\"name\":\"David Parent\",\"age\":52,\"level\":[999]}}"; - var json = JsonSerializer.Deserialize(str); - var result = json.ConvertToKeyValuePairs(); - Assert.IsNotNull(result); - var find = result.FirstOrDefault(m => m.Key == "age"); - Assert.IsNotNull(find); - Assert.AreEqual(20,find.Value); - - find = result.FirstOrDefault(m => m.Key == "level"); - Assert.IsNotNull(find); - IEnumerable nums =((IEnumerable)find.Value).Select(n=>(int)n); - Assert.IsTrue(nums.Any()); - - var parent = result.FirstOrDefault(m => m.Key == "parent"); - Assert.IsNotNull(parent); - IEnumerable> parentNode = (IEnumerable>)parent.Value; - Assert.IsNotNull(parentNode); - Assert.IsTrue(parentNode.Any()); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Extensions/ServiceExtenistionTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Extensions/ServiceExtenistionTests.cs deleted file mode 100644 index 6edfe78f8..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Extensions/ServiceExtenistionTests.cs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests.Extensions; - -#pragma warning disable CS0618 -[TestClass] -public class ServiceExtenistionTests -{ - [TestMethod] - public void AddLogNodesTest() - { - ServiceCollection services = new(); - services.AddElasticClientLog(new string[] { StaticConfig.HOST }, StaticConfig.LOG_INDEX_NAME); - Assert.IsNotNull(ElasticConstant.Log); - Assert.AreEqual(ElasticConstant.Log.IndexName, StaticConfig.LOG_INDEX_NAME); - - var factory = services.BuildServiceProvider().GetRequiredService(); - Assert.IsNotNull(factory); - - Assert.IsNotNull(factory.CreateElasticClient(ElasticConstant.LOG_CALLER_CLIENT_NAME)); - Assert.ThrowsException(() => factory.CreateElasticClient(ElasticConstant.TRACE_CALLER_CLIENT_NAME)); - Assert.ThrowsException(() => factory.CreateElasticClient(ElasticConstant.DEFAULT_CALLER_CLIENT_NAME)); - services.Clear(); - } - - [TestMethod] - public void AddLogOptionsTest() - { - ServiceCollection services = new(); - services.AddElasticClientLog(options => - { - options.UseNodes(new string[] { StaticConfig.HOST }) - .UseConnectionSettings(setting => setting.EnableApiVersioningHeader(false)); - }, caller => - { - caller.BaseAddress = StaticConfig.HOST; - }, StaticConfig.LOG_INDEX_NAME); - - Assert.IsNotNull(ElasticConstant.Log); - Assert.AreEqual(ElasticConstant.Log.IndexName, StaticConfig.LOG_INDEX_NAME); - - var factory = services.BuildServiceProvider().GetRequiredService(); - Assert.IsNotNull(factory); - Assert.IsNotNull(factory.CreateElasticClient(ElasticConstant.LOG_CALLER_CLIENT_NAME)); - Assert.ThrowsException(() => factory.CreateElasticClient(ElasticConstant.TRACE_CALLER_CLIENT_NAME)); - Assert.ThrowsException(() => factory.CreateElasticClient(ElasticConstant.DEFAULT_CALLER_CLIENT_NAME)); - services.Clear(); - } - - [TestMethod] - public void AddTraceNodesTest() - { - ServiceCollection services = new(); - services.AddElasticClientTrace(new string[] { StaticConfig.HOST }, StaticConfig.TRACE_INDEX_NAME); - Assert.IsNotNull(ElasticConstant.Trace); - Assert.AreEqual(ElasticConstant.Trace.IndexName, StaticConfig.TRACE_INDEX_NAME); - - var factory = services.BuildServiceProvider().GetRequiredService(); - Assert.IsNotNull(factory); - Assert.ThrowsException(() => factory.CreateElasticClient(ElasticConstant.LOG_CALLER_CLIENT_NAME)); - Assert.IsNotNull(factory.CreateElasticClient(ElasticConstant.TRACE_CALLER_CLIENT_NAME)); - Assert.ThrowsException(() => factory.CreateElasticClient(ElasticConstant.DEFAULT_CALLER_CLIENT_NAME)); - services.Clear(); - } - - [TestMethod] - public void AddTraceOptionsTest() - { - ServiceCollection services = new(); - services.AddElasticClientTrace(options => - { - options.UseNodes(new string[] { StaticConfig.HOST }). - UseConnectionSettings(setting => setting.EnableApiVersioningHeader(false)); - }, caller => - { - caller.BaseAddress = StaticConfig.HOST; - }, StaticConfig.TRACE_INDEX_NAME); - - Assert.IsNotNull(ElasticConstant.Trace); - Assert.AreEqual(ElasticConstant.Trace.IndexName, StaticConfig.TRACE_INDEX_NAME); - - var factory = services.BuildServiceProvider().GetRequiredService(); - Assert.IsNotNull(factory); - Assert.ThrowsException(() => factory.CreateElasticClient(ElasticConstant.LOG_CALLER_CLIENT_NAME)); - Assert.IsNotNull(factory.CreateElasticClient(ElasticConstant.TRACE_CALLER_CLIENT_NAME)); - Assert.ThrowsException(() => factory.CreateElasticClient(ElasticConstant.DEFAULT_CALLER_CLIENT_NAME)); - services.Clear(); - } - - [TestMethod] - public void AddLogTraceNodesTest() - { - ServiceCollection services = new(); - services.AddElasticClientLogAndTrace(new string[] { StaticConfig.HOST }, StaticConfig.LOG_INDEX_NAME, StaticConfig.TRACE_INDEX_NAME); - Assert.IsNotNull(ElasticConstant.Trace); - Assert.AreEqual(ElasticConstant.Trace.IndexName, StaticConfig.TRACE_INDEX_NAME); - Assert.IsNotNull(ElasticConstant.Log); - Assert.AreEqual(ElasticConstant.Log.IndexName, StaticConfig.LOG_INDEX_NAME); - - var factory = services.BuildServiceProvider().GetRequiredService(); - Assert.IsNotNull(factory); - Assert.ThrowsException(() => factory.CreateElasticClient(ElasticConstant.LOG_CALLER_CLIENT_NAME)); - Assert.ThrowsException(() => factory.CreateElasticClient(ElasticConstant.TRACE_CALLER_CLIENT_NAME)); - Assert.IsNotNull(factory.CreateElasticClient(ElasticConstant.DEFAULT_CALLER_CLIENT_NAME)); - services.Clear(); - } - - [TestMethod] - public void AddLogTraceOptionsTest() - { - ServiceCollection services = new(); - services.AddElasticClientLogAndTrace(options => - { - options.UseNodes(new string[] { StaticConfig.HOST }). - UseConnectionSettings(setting => setting.EnableApiVersioningHeader(false)); - }, caller => - { - caller.BaseAddress = StaticConfig.HOST; - }, - StaticConfig.LOG_INDEX_NAME, - StaticConfig.TRACE_INDEX_NAME); - - Assert.IsNotNull(ElasticConstant.Trace); - Assert.AreEqual(ElasticConstant.Trace.IndexName, StaticConfig.TRACE_INDEX_NAME); - Assert.IsNotNull(ElasticConstant.Log); - Assert.AreEqual(ElasticConstant.Log.IndexName, StaticConfig.LOG_INDEX_NAME); - - var factory = services.BuildServiceProvider().GetRequiredService(); - Assert.IsNotNull(factory); - Assert.ThrowsException(() => factory.CreateElasticClient(ElasticConstant.LOG_CALLER_CLIENT_NAME)); - Assert.ThrowsException(() => factory.CreateElasticClient(ElasticConstant.TRACE_CALLER_CLIENT_NAME)); - Assert.IsNotNull(factory.CreateElasticClient(ElasticConstant.DEFAULT_CALLER_CLIENT_NAME)); - services.Clear(); - } -} -#pragma warning restore CS0618 diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests.csproj deleted file mode 100644 index ebd1068a4..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests.csproj +++ /dev/null @@ -1,36 +0,0 @@ - - - - enable - enable - false - true - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - Always - - - - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Service/LogServiceTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Service/LogServiceTests.cs deleted file mode 100644 index 9f90aa5e5..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Service/LogServiceTests.cs +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests; - -[TestClass] -public class LogServiceTests -{ - private ILogService _logService; - - [ClassInitialize] - public static void InitializeLog(TestContext testContext) - { - var mapping = StaticConfig.GetJson("Mapping:log"); - var dataJson = StaticConfig.GetJson("Init:log"); - var httpClient = new HttpClient() { BaseAddress = new Uri(StaticConfig.HOST) }; - httpClient.Send(StaticConfig.CreateMessage(StaticConfig.LOG_INDEX_NAME, HttpMethod.Delete)); - httpClient.Send(StaticConfig.CreateMessage(StaticConfig.LOG_INDEX_NAME, HttpMethod.Put, mapping)); - httpClient.Send(StaticConfig.CreateMessage($"{StaticConfig.LOG_INDEX_NAME}/_doc", HttpMethod.Post, dataJson)); - - httpClient.Send(StaticConfig.CreateMessage(StaticConfig.LOG_INDEX_RENAME, HttpMethod.Delete)); - httpClient.Send(StaticConfig.CreateMessage(StaticConfig.LOG_INDEX_RENAME, HttpMethod.Put, mapping)); - httpClient.Send(StaticConfig.CreateMessage($"{StaticConfig.LOG_INDEX_RENAME}/_doc", HttpMethod.Post, dataJson)); - Task.Delay(1000).Wait(); - } - - [TestInitialize] - public void Initialize() - { - ServiceCollection services = new(); - services.AddElasticClientLog(new string[] { StaticConfig.HOST }, StaticConfig.LOG_INDEX_NAME); - services.AddElasticClientLog(new string[] { StaticConfig.HOST }, StaticConfig.LOG_INDEX_RENAME); - var serviceProvider = services.BuildServiceProvider(); - _logService = serviceProvider.GetRequiredService(); - } - - [TestMethod] - public async Task MappingTest() - { - var mappings = await _logService.GetMappingAsync(); - Assert.IsNotNull(mappings); - Assert.IsTrue(mappings.Any()); - Assert.IsTrue(mappings.Any(m => m.Name == "@timestamp")); - } - - [TestMethod] - public async Task QueryEqualTest() - { - Assert.IsNotNull(ElasticConstant.Log.Mappings.Value); - var query = new BaseRequestDto - { - Page = 1, - PageSize = 10, - Conditions = new FieldConditionDto[] { - new FieldConditionDto{ Name="Attributes.Name", Type= ConditionTypes.Equal, Value="UserAuthorizationFailed" } - } - }; - - var result = await _logService.ListAsync(query); - Assert.IsNotNull(result); - Assert.IsTrue(result.Result.Any()); - } - - [TestMethod] - public async Task QueryNotEqualTest() - { - var query = new BaseRequestDto - { - Page = 1, - PageSize = 10, - Conditions = new FieldConditionDto[] { - new FieldConditionDto{ Name="Attributes.Name", Type= ConditionTypes.NotEqual, Value="UserAuthorizationFailed" } - } - }; - - var result = await _logService.ListAsync(query); - Assert.IsNotNull(result); - Assert.IsFalse(result.Result.Any()); - } - - [TestMethod] - public async Task QueryKeywordTest() - { - var query = new BaseRequestDto - { - Page = 1, - PageSize = 10, - Keyword = "requirements" - }; - - var result = await _logService.ListAsync(query); - Assert.IsNotNull(result); - Assert.IsTrue(result.Result.Any()); - } - - [TestMethod] - public async Task QueryGreaterTest() - { - var query = new BaseRequestDto - { - Page = 1, - PageSize = 10, - Conditions = new FieldConditionDto[] { - new FieldConditionDto{ Name="SeverityNumber",Type= ConditionTypes.GreatEqual,Value=8 }, - new FieldConditionDto{ Name="SeverityNumber",Type= ConditionTypes.Less,Value=10 }, - } - }; - - var result = await _logService.ListAsync(query); - Assert.IsNotNull(result); - Assert.IsTrue(result.Result.Any()); - } - - [TestMethod] - public async Task QueryInTest() - { - var query = new BaseRequestDto - { - Page = 1, - PageSize = 10, - Conditions = new FieldConditionDto[] { - new FieldConditionDto{ Name=ElasticConstant.SpanId, Type= ConditionTypes.In, Value=new string[]{ "1c495129b86de343", "aaaaaaa" } } - } - }; - - var result = await _logService.ListAsync(query); - Assert.IsNotNull(result); - Assert.IsTrue(result.Result.Any()); - - query.Conditions.First().Type = ConditionTypes.NotIn; - result = await _logService.ListAsync(query); - Assert.IsNotNull(result); - Assert.IsFalse(result.Result.Any()); - } - - [TestMethod] - public async Task QueryRegexTest() - { - var query = new BaseRequestDto - { - Page = 1, - PageSize = 10, - Conditions = new FieldConditionDto[] { - new FieldConditionDto{ Name=ElasticConstant.ServiceName, Type= ConditionTypes.Regex, Value="masa*"} - } - }; - - var result = await _logService.ListAsync(query); - Assert.IsNotNull(result); - Assert.IsTrue(result.Result.Any()); - - query.Conditions.First().Type = ConditionTypes.NotRegex; - result = await _logService.ListAsync(query); - Assert.IsNotNull(result); - Assert.IsFalse(result.Result.Any()); - } - - [TestMethod] - public async Task QueryExistsTest() - { - var query = new BaseRequestDto - { - Page = 1, - PageSize = 10, - Conditions = new FieldConditionDto[] { - new FieldConditionDto{ Name=ElasticConstant.ParentId, Type= ConditionTypes.Exists} - } - }; - - var result = await _logService.ListAsync(query); - Assert.IsNotNull(result); - Assert.IsFalse(result.Result.Any()); - - query.Conditions.First().Type = ConditionTypes.NotExists; - result = await _logService.ListAsync(query); - Assert.IsNotNull(result); - Assert.IsTrue(result.Result.Any()); - } - - [TestMethod] - public async Task AggCount() - { - var query = new SimpleAggregateRequestDto - { - Service = "masa-tsc-web-admin", - Name = ElasticConstant.ServiceName, - Type = AggregateTypes.Count - }; - var result = await _logService.AggregateAsync(query); - Assert.IsNotNull(result); - var num = Convert.ToInt32(result); - Assert.AreEqual(1, num); - } - - [TestMethod] - [DataRow(AggregateTypes.Avg)] - [DataRow(AggregateTypes.Sum)] - public async Task AggNumber(AggregateTypes type) - { - var query = new SimpleAggregateRequestDto - { - Service = "masa-tsc-web-admin", - Name = "Attributes.Id", - Type = type - }; - var result = await _logService.AggregateAsync(query); - Assert.IsNotNull(result); - var num = Convert.ToInt32(result); - Assert.AreEqual(2, num); - - query.Name = "Attributes.Name"; - var notNumException = false; - try - { - result = await _logService.AggregateAsync(query); - } - catch - { - notNumException = true; - } - Assert.IsTrue(notNumException); - } - - [TestMethod] - public async Task AggGroupByTest() - { - var query = new SimpleAggregateRequestDto - { - MaxCount = 10, - Service = "masa-tsc-web-admin", - Name = ElasticConstant.ServiceInstance, - Type = AggregateTypes.GroupBy - }; - - var result = await _logService.AggregateAsync(query); - Assert.IsNotNull(result); - var data = (IEnumerable)result; - Assert.IsTrue(data.Any()); - } - - [TestMethod] - public async Task AggDateHistogramTest() - { - var query = new SimpleAggregateRequestDto - { - MaxCount = 10, - Service = "masa-tsc-web-admin", - Name = ElasticConstant.Log.Timestamp, - Interval = "5m" - }; - - var result = await _logService.AggregateAsync(query); - Assert.IsNull(result); - - query.Type = AggregateTypes.DateHistogram; - result = await _logService.AggregateAsync(query); - Assert.IsNotNull(result); - var data = (IEnumerable>)result; - Assert.IsTrue(data.Any()); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Service/TraceServiceTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Service/TraceServiceTests.cs deleted file mode 100644 index 85895016e..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/Service/TraceServiceTests.cs +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests; - -[TestClass] -public class TraceServiceTests -{ - private ITraceService _traceService; - - [ClassInitialize] - public static void InitializeTrace(TestContext testContext) - { - var mapping = StaticConfig.GetJson("Mapping:trace"); - var httpJson = StaticConfig.GetJson("Init:traceHttp"); - var databaseJson = StaticConfig.GetJson("Init:traceDatabase"); - var exceptionJson = StaticConfig.GetJson("Init:traceException"); - - var httpClient = new HttpClient() { BaseAddress = new Uri(StaticConfig.HOST) }; - httpClient.Send(StaticConfig.CreateMessage(StaticConfig.TRACE_INDEX_NAME, HttpMethod.Delete)); - httpClient.Send(StaticConfig.CreateMessage(StaticConfig.TRACE_INDEX_NAME, HttpMethod.Put, mapping)); - httpClient.Send(StaticConfig.CreateMessage($"{StaticConfig.TRACE_INDEX_NAME}/_doc", HttpMethod.Post, httpJson)); - httpClient.Send(StaticConfig.CreateMessage($"{StaticConfig.TRACE_INDEX_NAME}/_doc", HttpMethod.Post, databaseJson)); - httpClient.Send(StaticConfig.CreateMessage($"{StaticConfig.TRACE_INDEX_NAME}/_doc", HttpMethod.Post, exceptionJson)); - Task.Delay(1000).Wait(); - } - - [TestInitialize] - public void Initialize() - { - ServiceCollection services = new(); - services.AddElasticClientTrace(options => - { - options.UseNodes(new string[] { StaticConfig.HOST }). - UseConnectionSettings(setting => setting.EnableApiVersioningHeader(false)); - }, - callerBuilder => - { - callerBuilder.BaseAddress = StaticConfig.HOST; - }, - StaticConfig.TRACE_INDEX_NAME); - var serviceProvider = services.BuildServiceProvider(); - _traceService = serviceProvider.GetRequiredService(); - } - - [TestMethod] - public async Task QueryTest() - { - Assert.IsNotNull(ElasticConstant.Trace.Mappings.Value); - - var query = new BaseRequestDto - { - Page = 1, - PageSize = 10, - Sort = - new FieldOrderDto - { - Name = ElasticConstant.ServiceName - } - }; - - var result = await _traceService.ListAsync(query); - Assert.IsNotNull(result); - Assert.IsTrue(result.Result.Any()); - } - - [TestMethod] - public async Task GetTest() - { - var result = await _traceService.GetAsync("277df6d0204f09fa63ff4ab896673455"); - Assert.IsNotNull(result); - Assert.IsTrue(result.Any()); - bool isHttp = result.First().TryParseHttp(out var httpDto); - Assert.IsTrue(isHttp); - Assert.IsNotNull(httpDto); - Assert.IsNotNull(httpDto.Method); - - result = await _traceService.GetAsync("notexits"); - Assert.IsNotNull(result); - Assert.IsFalse(result.Any()); - - //exception - result = await _traceService.GetAsync("1feb13f2c4b882a97db0ef7d43231d6d"); - Assert.IsNotNull(result); - Assert.IsTrue(result.Any()); - bool isException = result.First().TryParseException(out var exceptionDto); - Assert.IsTrue(isException); - Assert.IsNotNull(exceptionDto); - Assert.IsNotNull(exceptionDto.Message); - - result = await _traceService.GetAsync("894c8d019af8f422e660581da8d1f165"); - Assert.IsNotNull(result); - Assert.IsTrue(result.Any()); - bool isDatabase = result.First().TryParseDatabase(out var databaseDto); - Assert.IsTrue(isDatabase); - Assert.IsNotNull(databaseDto); - Assert.AreEqual("mssql", databaseDto.System); - } - - [TestMethod] - public async Task AggTest() - { - var query = new SimpleAggregateRequestDto - { - Service = "masa-tsc-web-admin", - Name = ElasticConstant.ServiceName, - Type = AggregateTypes.GroupBy, - MaxCount = 10 - }; - var result = await _traceService.AggregateAsync(query); - Assert.IsNotNull(result); - - var values = (IEnumerable)result; - Assert.IsNotNull(values); - Assert.IsTrue(values.All(s => !string.IsNullOrEmpty(s))); - } - - [TestMethod] - public async Task GetScrollAsyncTest() - { - var query = new ElasticsearchScrollRequestDto - { - Scroll = "1m", - PageSize = 1 - }; - var firstResult = await _traceService.ScrollAsync(query); - - Assert.IsNotNull(firstResult); - Assert.IsNotNull(firstResult.Result); - - var elasticsearchScrollResult = (ElasticsearchScrollResponseDto)firstResult; - Assert.IsNotNull(elasticsearchScrollResult.ScrollId); - query.ScrollId = elasticsearchScrollResult.ScrollId; - - var secondResult = await _traceService.ScrollAsync(query); - - Assert.IsNotNull(secondResult); - Assert.IsTrue(secondResult.Result.Any()); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/StaticConfig.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/StaticConfig.cs deleted file mode 100644 index 18b3d1adf..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/StaticConfig.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests; - -public static class StaticConfig -{ - internal const string LOG_INDEX_NAME = "test_logs"; - internal const string LOG_INDEX_RENAME = "test_logs_new"; - internal const string HOST = "http://localhost:9200"; - internal const string TRACE_INDEX_NAME = "test_traces"; - private static IConfiguration Configuration; - - public static IConfiguration InitConfiguration() - { - var config = new ConfigurationBuilder() - .AddJsonFile("testData.json") - .Build(); - return config; - } - - public static string GetJson(string name) - { - if (Configuration == null) - Configuration = InitConfiguration(); - return Configuration.GetSection(name).Get(); - } - - public static HttpRequestMessage CreateMessage(string indexName, HttpMethod method, string? message=null) - { - var result = new HttpRequestMessage() - { - Method = method, - RequestUri = new Uri($"/{indexName}", UriKind.Relative) - }; - if (!string.IsNullOrEmpty(message)) - result.Content = new StringContent(message, Encoding.UTF8, "application/json"); - return result; - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/_Imports.cs deleted file mode 100644 index 7eca7bc7a..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/_Imports.cs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Log; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Model; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Model.Aggregate; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Service; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Trace; -global using Masa.Contrib.StackSdks.Tsc.Elasticsearch.Constants; -global using Masa.Contrib.StackSdks.Tsc.Elasticsearch.Converters; -global using Masa.Contrib.StackSdks.Tsc.Elasticsearch.Model; -global using Masa.Utils.Data.Elasticsearch; -global using Microsoft.Extensions.Configuration; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.VisualStudio.TestTools.UnitTesting; -global using System.Text; -global using System.Text.Json; diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/testData.json b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/testData.json deleted file mode 100644 index 9b311bc66..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Elasticsearch.Tests/testData.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Convert": { - "logJson": "{\"@timestamp\":\"2022-11-15T12:12:11.028116800Z\",\"Attributes.Id\":2,\"Attributes.Name\":\"UserAuthorizationFailed\",\"Attributes.Reason\":\"These requirements were not met:\\r\\nDenyAnonymousAuthorizationRequirement: Requires an authenticated user.\",\"Attributes.[Scope.0]:ParentId\":\"0000000000000000\",\"Attributes.[Scope.0]:SpanId\":\"1c495129b86de343\",\"Attributes.[Scope.0]:TraceId\":\"277df6d0204f09fa63ff4ab896673455\",\"Attributes.[Scope.1]:ConnectionId\":\"0HMM705VTO6BQ\",\"Attributes.[Scope.2]:RequestId\":\"0HMM705VTO6BQ:00000001\",\"Attributes.[Scope.2]:RequestPath\":\"/\",\"Attributes.dotnet.ilogger.category\":\"Microsoft.AspNetCore.Authorization.DefaultAuthorizationService\",\"Attributes.{OriginalFormat}\":\"Authorization failed. {Reason}\",\"Body\":\"Authorization failed. These requirements were not met:\\r\\nDenyAnonymousAuthorizationRequirement: Requires an authenticated user.\",\"Resource.service.instance.id\":\"9eaf1452-8b12-4368-928c-48f871c250fe\",\"Resource.service.name\":\"masa-tsc-web-admin\",\"Resource.service.namespace\":\"Development\",\"Resource.service.version\":\"0.1.0\",\"Resource.telemetry.sdk.language\":\"dotnet\",\"Resource.telemetry.sdk.name\":\"opentelemetry\",\"Resource.telemetry.sdk.version\":\"1.3.0.519\",\"SeverityNumber\":9,\"SeverityText\":\"Information\",\"SpanId\":\"1c495129b86de343\",\"TraceFlags\":1,\"TraceId\":\"277df6d0204f09fa63ff4ab896673455\"}", - "traceJson": "{\"@timestamp\":\"2022-11-15T12:12:10.938123800Z\",\"Attributes.host.name\":\"SSKJ016\",\"Attributes.http.client_ip\":\"::1\",\"Attributes.http.flavor\":\"HTTP/2\",\"Attributes.http.host\":\"localhost:18012\",\"Attributes.http.method\":\"GET\",\"Attributes.http.response_content_length\":0,\"Attributes.http.scheme\":\"https\",\"Attributes.http.status_code\":302,\"Attributes.http.target\":\"/\",\"Attributes.http.url\":\"https://localhost:18012/\",\"Attributes.http.user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36\",\"EndTimestamp\":\"2022-11-15T12:12:11.323348000Z\",\"Kind\":\"SPAN_KIND_SERVER\",\"Link\":\"[]\",\"Name\":\"/\",\"Resource.service.instance.id\":\"9eaf1452-8b12-4368-928c-48f871c250fe\",\"Resource.service.name\":\"masa-tsc-web-admin\",\"Resource.service.namespace\":\"Development\",\"Resource.service.version\":\"0.1.0\",\"Resource.telemetry.sdk.language\":\"dotnet\",\"Resource.telemetry.sdk.name\":\"opentelemetry\",\"Resource.telemetry.sdk.version\":\"1.3.0.519\",\"SpanId\":\"1c495129b86de343\",\"TraceId\":\"277df6d0204f09fa63ff4ab896673455\",\"TraceStatus\":0}" - }, - "Mapping": { - "log": "{\"mappings\":{\"properties\":{\"@timestamp\":{\"type\":\"date\"},\"Attributes\":{\"properties\":{\"AuthenticationScheme\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"CommandType\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"ContentLength\":{\"type\":\"long\"},\"ContentType\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"ElapsedMilliseconds\":{\"type\":\"float\"},\"EndpointName\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"FullName\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"Host\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"Id\":{\"type\":\"long\"},\"Method\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"Name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"Path\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"PathBase\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"Protocol\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"QueryString\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"Reason\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"Scheme\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"StatusCode\":{\"type\":\"long\"},\"[Scope\":{\"properties\":{\"0]:ParentId\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"0]:SpanId\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"0]:TraceId\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"1]:ConnectionId\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"2]:RequestId\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"2]:RequestPath\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}},\"address\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"contentRoot\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"dotnet\":{\"properties\":{\"ilogger\":{\"properties\":{\"category\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}}}},\"envName\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"exception\":{\"properties\":{\"message\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"stacktrace\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"type\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}},\"{OriginalFormat}\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}},\"Body\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"Resource\":{\"properties\":{\"service\":{\"properties\":{\"instance\":{\"properties\":{\"id\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}},\"name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"namespace\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"version\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}},\"telemetry\":{\"properties\":{\"sdk\":{\"properties\":{\"language\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"version\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}}}}}},\"SeverityNumber\":{\"type\":\"long\"},\"SeverityText\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"SpanId\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"TraceFlags\":{\"type\":\"long\"},\"TraceId\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}}}", - "trace": "{\"mappings\":{\"properties\":{\"@timestamp\":{\"type\":\"date\"},\"Attributes\":{\"properties\":{\"db\":{\"properties\":{\"method\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"statement\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"statement_type\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"system\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"url\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}},\"enduser\":{\"properties\":{\"id\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"nick_name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}},\"exception\":{\"properties\":{\"message\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"stacktrace\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}},\"host\":{\"properties\":{\"name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}},\"http\":{\"properties\":{\"client_ip\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"flavor\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"host\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"method\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"request_content_body\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"request_content_length\":{\"type\":\"long\"},\"request_content_type\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"response_content_length\":{\"type\":\"long\"},\"response_content_type\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"scheme\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"status_code\":{\"type\":\"long\"},\"target\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"url\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"user_agent\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}},\"net\":{\"properties\":{\"peer\":{\"properties\":{\"ip\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"port\":{\"type\":\"long\"}}}}},\"peer\":{\"properties\":{\"service\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}}}},\"EndTimestamp\":{\"type\":\"date\"},\"Kind\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"Link\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"Name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"ParentSpanId\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"Resource\":{\"properties\":{\"service\":{\"properties\":{\"instance\":{\"properties\":{\"id\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}},\"name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"namespace\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"version\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}},\"telemetry\":{\"properties\":{\"sdk\":{\"properties\":{\"language\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"name\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"version\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}}}}}},\"SpanId\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"TraceId\":{\"type\":\"text\",\"fields\":{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"TraceStatus\":{\"type\":\"long\"}}}}" - }, - "Init": { - "log": "{\"@timestamp\":\"2022-11-15T12:12:11.028116800Z\",\"Attributes.Id\":2,\"Attributes.Name\":\"UserAuthorizationFailed\",\"Attributes.Reason\":\"These requirements were not met:\\r\\nDenyAnonymousAuthorizationRequirement: Requires an authenticated user.\",\"Attributes.[Scope.0]:ParentId\":\"0000000000000000\",\"Attributes.[Scope.0]:SpanId\":\"1c495129b86de343\",\"Attributes.[Scope.0]:TraceId\":\"277df6d0204f09fa63ff4ab896673455\",\"Attributes.[Scope.1]:ConnectionId\":\"0HMM705VTO6BQ\",\"Attributes.[Scope.2]:RequestId\":\"0HMM705VTO6BQ:00000001\",\"Attributes.[Scope.2]:RequestPath\":\"/\",\"Attributes.dotnet.ilogger.category\":\"Microsoft.AspNetCore.Authorization.DefaultAuthorizationService\",\"Attributes.{OriginalFormat}\":\"Authorization failed. {Reason}\",\"Body\":\"Authorization failed. These requirements were not met:\\r\\nDenyAnonymousAuthorizationRequirement: Requires an authenticated user.\",\"Resource.service.instance.id\":\"9eaf1452-8b12-4368-928c-48f871c250fe\",\"Resource.service.name\":\"masa-tsc-web-admin\",\"Resource.service.namespace\":\"Development\",\"Resource.service.version\":\"0.1.0\",\"Resource.telemetry.sdk.language\":\"dotnet\",\"Resource.telemetry.sdk.name\":\"opentelemetry\",\"Resource.telemetry.sdk.version\":\"1.3.0.519\",\"SeverityNumber\":9,\"SeverityText\":\"Information\",\"SpanId\":\"1c495129b86de343\",\"TraceFlags\":1,\"TraceId\":\"277df6d0204f09fa63ff4ab896673455\"}", - "traceHttp": "{\"@timestamp\":\"2022-11-15T12:12:10.938123800Z\",\"Attributes.host.name\":\"SSKJ016\",\"Attributes.http.client_ip\":\"::1\",\"Attributes.http.flavor\":\"HTTP/2\",\"Attributes.http.host\":\"localhost:18012\",\"Attributes.http.method\":\"GET\",\"Attributes.http.response_content_length\":0,\"Attributes.http.scheme\":\"https\",\"Attributes.http.status_code\":302,\"Attributes.http.target\":\"/\",\"Attributes.http.url\":\"https://localhost:18012/\",\"Attributes.http.user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36\",\"EndTimestamp\":\"2022-11-15T12:12:11.323348000Z\",\"Kind\":\"SPAN_KIND_SERVER\",\"Link\":\"[]\",\"Name\":\"/\",\"Resource.service.instance.id\":\"9eaf1452-8b12-4368-928c-48f871c250fe\",\"Resource.service.name\":\"masa-tsc-web-admin\",\"Resource.service.namespace\":\"Development\",\"Resource.service.version\":\"0.1.0\",\"Resource.telemetry.sdk.language\":\"dotnet\",\"Resource.telemetry.sdk.name\":\"opentelemetry\",\"Resource.telemetry.sdk.version\":\"1.3.0.519\",\"SpanId\":\"1c495129b86de343\",\"TraceId\":\"277df6d0204f09fa63ff4ab896673455\",\"TraceStatus\":0}", - "traceDatabase": "{\"@timestamp\":\"2022-11-15T12:14:19.353985100Z\",\"Attributes.db.name\":\"tsc_dev\",\"Attributes.db.statement\":\"SELECT TOP(@__p_2) [i].[Id], [i].[Content], [i].[CreationTime], [i].[EventId], [i].[EventTypeName], [i].[ModificationTime], [i].[RowVersion], [i].[State], [i].[TimesSent], [i].[TransactionId]\\r\\nFROM [tsc].[IntegrationEventLog] AS [i]\\r\\nWHERE ([i].[State] IN (3, 1) AND ([i].[TimesSent] <= @__maxRetryTimes_0)) AND ([i].[ModificationTime] < @__time_1)\\r\\nORDER BY [i].[CreationTime]\",\"Attributes.db.statement_type\":\"Text\",\"Attributes.db.system\":\"mssql\",\"Attributes.peer.service\":\"10.175.171.201,32679\",\"EndTimestamp\":\"2022-11-15T12:14:21.210334300Z\",\"Kind\":\"SPAN_KIND_CLIENT\",\"Link\":\"[]\",\"Name\":\"tsc_dev\",\"Resource.service.instance.id\":\"b17469f1-7243-4d4c-a921-76b84f358d3e\",\"Resource.service.name\":\"masa-tsc-service-admin\",\"Resource.service.namespace\":\"Development\",\"Resource.service.version\":\"0.1.0\",\"Resource.telemetry.sdk.language\":\"dotnet\",\"Resource.telemetry.sdk.name\":\"opentelemetry\",\"Resource.telemetry.sdk.version\":\"1.3.0.519\",\"SpanId\":\"680ec468b36c6d80\",\"TraceId\":\"894c8d019af8f422e660581da8d1f165\",\"TraceStatus\":0}", - "traceException": "{\"@timestamp\":\"2022-11-15T12:11:57.477146800Z\",\"Attributes.exception.message\":\"SearchAsync execute error elastic query error: status:404,message:ServerError: 404Type: index_not_found_exception Reason: \\\"no such index [masa-stack-trace-0.61]\\\"\",\"Attributes.exception.stacktrace\":\"System.UserFriendlyException: SearchAsync execute error elastic query error: status:404,message:ServerError: 404Type: index_not_found_exception Reason: \\\"no such index [masa-stack-trace-0.61]\\\"\\r\\n at Nest.IElasticClientExtenstion.SearchAsync[TResult,TQuery](IElasticClient client, String indexName, TQuery query, Func`3 condition, Action`2 result, Func`3 aggregate, Func`1 page, Func`3 sort, Func`1 includeFields, Func`1 excludeFields) in D:\\\\workplaces\\\\MASA.Framework\\\\src\\\\Contrib\\\\StackSdks\\\\Masa.Contrib.StackSdks.Tsc.Elasticsearch\\\\Extenistions\\\\IElasticClientExtenstion.cs:line 65\\r\\n at Nest.IElasticClientExtenstion.AggregateTraceAsync(IElasticClient client, SimpleAggregateRequestDto query) in D:\\\\workplaces\\\\MASA.Framework\\\\src\\\\Contrib\\\\StackSdks\\\\Masa.Contrib.StackSdks.Tsc.Elasticsearch\\\\Extenistions\\\\IElasticClientExtenstion.cs:line 227\\r\\n at Masa.Contrib.StackSdks.Tsc.Log.Elasticseach.TraceService.AggregateAsync(SimpleAggregateRequestDto query) in D:\\\\workplaces\\\\MASA.Framework\\\\src\\\\Contrib\\\\StackSdks\\\\Masa.Contrib.StackSdks.Tsc.Elasticsearch\\\\TraceService.cs:line 17\\r\\n at Masa.Tsc.Service.Admin.Application.Traces.QueryHandler.GetAttrValuesAsync(TraceAttrValuesQuery query) in D:\\\\workplaces\\\\MASA.TSC\\\\src\\\\Services\\\\Masa.Tsc.Service.Admin\\\\Application\\\\Traces\\\\QueryHandler.cs:line 60\\r\\n at Masa.Contrib.Dispatcher.Events.EventHandlerAttribute.ExecuteAction[TEvent](IServiceProvider serviceProvider, TEvent event)\\r\\n at Masa.Contrib.Dispatcher.Events.Internal.Dispatch.DispatcherBase.<>c__DisplayClass7_0`1.<b__0>d.MoveNext()\\r\\n--- End of stack trace from previous location ---\\r\\n at Masa.Contrib.Dispatcher.Events.Strategies.ExecutionStrategy.ExecuteAsync[TEvent](StrategyOptions strategyOptions, TEvent event, Func`2 func, Func`4 cancel)\\r\\n at Masa.Contrib.Dispatcher.Events.Internal.DispatcherExtensions.ThrowException(Exception exception)\\r\\n at Masa.Contrib.Dispatcher.Events.Internal.Dispatch.DispatcherBase.<>c__DisplayClass7_1`1.<b__1>d.MoveNext()\\r\\n--- End of stack trace from previous location ---\\r\\n at Masa.Contrib.Dispatcher.Events.Strategies.ExecutionStrategy.ExecuteAsync[TEvent](StrategyOptions strategyOptions, TEvent event, Func`2 func, Func`4 cancel)\\r\\n at Masa.Contrib.Dispatcher.Events.Internal.Dispatch.DispatcherBase.ExecuteEventHandlerAsync[TEvent](IServiceProvider serviceProvider, List`1 dispatchRelations, TEvent event)\\r\\n at Masa.Contrib.Dispatcher.Events.Internal.Dispatch.DispatcherBase.PublishEventAsync[TEvent](IServiceProvider serviceProvider, TEvent event)\\r\\n at Masa.Contrib.Dispatcher.Events.EventBus.<>c__DisplayClass7_0`1.<b__1>d.MoveNext()\\r\\n--- End of stack trace from previous location ---\\r\\n at Masa.Contrib.Dispatcher.Events.Internal.Middleware.TransactionMiddleware`1.HandleAsync(TEvent event, EventHandlerDelegate next)\\r\\n at Masa.Contrib.Dispatcher.Events.Internal.Middleware.TransactionMiddleware`1.HandleAsync(TEvent event, EventHandlerDelegate next)\\r\\n at Masa.Tsc.Service.Infrastructure.Middleware.LogMiddleware`1.HandleAsync(TEvent action, EventHandlerDelegate next) in D:\\\\workplaces\\\\MASA.TSC\\\\src\\\\Services\\\\Masa.Tsc.Service.Admin\\\\Infrastructure\\\\Middleware\\\\LogMiddleware.cs:line 24\\r\\n at Masa.Contrib.Dispatcher.Events.EventBus.PublishAsync[TEvent](TEvent event)\\r\\n at Masa.Tsc.Service.Admin.Services.TraceService.GetAttrValuesAsync(IEventBus eventBus, TraceAggregateRequestDto model) in D:\\\\workplaces\\\\MASA.TSC\\\\src\\\\Services\\\\Masa.Tsc.Service.Admin\\\\Services\\\\TraceService.cs:line 33\\r\\n at Microsoft.AspNetCore.Http.RequestDelegateFactory.g__ExecuteAwaited|58_0[T](Task`1 task, HttpContext httpContext)\\r\\n at Microsoft.AspNetCore.Http.RequestDelegateFactory.<>c__DisplayClass46_3.<b__2>d.MoveNext()\\r\\n--- End of stack trace from previous location ---\\r\\n at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\\r\\n at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)\\r\\n at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\\r\\n at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)\\r\\n at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)\\r\\n at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)\",\"Attributes.host.name\":\"SSKJ016\",\"Attributes.http.client_ip\":\"::1\",\"Attributes.http.flavor\":\"HTTP/1.1\",\"Attributes.http.host\":\"localhost:18010\",\"Attributes.http.method\":\"GET\",\"Attributes.http.request_content_body\":\"{\\r\\n \\\"page\\\": 0,\\r\\n \\\"size\\\": 0,\\r\\n \\\"keyword\\\": \\\"\\\",\\r\\n \\\"start\\\": \\\"2022-11-15T01:46:06.375Z\\\",\\r\\n \\\"end\\\": \\\"2022-11-15T11:46:06.375Z\\\",\\r\\n \\\"rawQuery\\\": \\\"\\\",\\r\\n \\r\\n \\\"type\\\": 6,\\r\\n \\\"maxCount\\\": 10,\\r\\n \\\"interval\\\": \\\"\\\",\\r\\n \\\"traceId\\\": \\\"\\\",\\r\\n \\\"service\\\": \\\"masa-tsc-service-admin\\\",\\r\\n \\\"instance\\\": \\\"df7f15cc-0e17-48b0-93d1-f0bc7e886be3\\\",\\r\\n \\\"endpoint\\\": \\\"\\\"\\r\\n}\",\"Attributes.http.request_content_length\":336,\"Attributes.http.request_content_type\":\"application/json\",\"Attributes.http.response_content_type\":\"text/plain; charset=utf-8\",\"Attributes.http.scheme\":\"https\",\"Attributes.http.status_code\":500,\"Attributes.http.target\":\"/api/trace/attr-values\",\"Attributes.http.url\":\"https://localhost:18010/api/trace/attr-values\",\"Attributes.http.user_agent\":\"PostmanRuntime/7.29.2\",\"EndTimestamp\":\"2022-11-15T12:12:02.989775300Z\",\"Kind\":\"SPAN_KIND_SERVER\",\"Link\":\"[]\",\"Name\":\"/api/trace/attr-values\",\"Resource.service.instance.id\":\"b17469f1-7243-4d4c-a921-76b84f358d3e\",\"Resource.service.name\":\"masa-tsc-service-admin\",\"Resource.service.namespace\":\"Development\",\"Resource.service.version\":\"0.1.0\",\"Resource.telemetry.sdk.language\":\"dotnet\",\"Resource.telemetry.sdk.name\":\"opentelemetry\",\"Resource.telemetry.sdk.version\":\"1.3.0.519\",\"SpanId\":\"7fe4e67c31d2a1ce\",\"TraceId\":\"1feb13f2c4b882a97db0ef7d43231d6d\",\"TraceStatus\":2}" - } -} \ No newline at end of file diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Extensions/ServiceExtensionsTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Extensions/ServiceExtensionsTests.cs deleted file mode 100644 index bc28d914c..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Extensions/ServiceExtensionsTests.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests.Extensions; - -[TestClass] -public class ServiceExtensionsTests -{ - [TestMethod] - public void ConfigrationTest() - { - IConfigurationRoot configuration = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile("appsettings.json") - .Build(); - using var loggerFactory = LoggerFactory.Create(builder => - { - builder.Services.AddObservable(builder, configuration); - }); - Assert.IsNotNull(configuration.GetSection("Masa:Observable").Get()); - } - - [TestMethod] - public void FuncTest() - { - using var loggerFactory = LoggerFactory.Create(builder => - { - builder.Services.AddObservable(builder, () => new MasaObservableOptions - { - ServiceName = "test-app" - }, () => ObservableHelper.OTLPURL, true); - }); - Assert.IsTrue(true); - } - - [TestMethod] - public void OptionsTest() - { - using var loggerFactory = LoggerFactory.Create(builder => - { - builder.Services.AddObservable(builder, new MasaObservableOptions - { - ServiceName = "test-app" - }, ObservableHelper.OTLPURL, true); - }); - Assert.IsTrue(true); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Extensions/SteamTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Extensions/SteamTests.cs deleted file mode 100644 index a5e16eead..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Extensions/SteamTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests.Extensions; - -[TestClass] -public class SteamTests -{ - [TestInitialize] - public void Initialize() - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - } - - [TestMethod] - [DataRow("曾经沧海难为水,除却巫山不是云")] - [DataRow("柳州柳刺史,种柳柳江边。", "gbk")] - [DataRow("")] - public async Task EncodingTest(string text, string? charCode = default) - { - Encoding? coding = null; - byte[] bytes; - if (!string.IsNullOrEmpty(charCode)) - { - coding = Encoding.GetEncoding(charCode); - bytes = coding.GetBytes(text); - } - else - { - bytes = Encoding.UTF8.GetBytes(text); - } - - using var ms = new MemoryStream(bytes); - - (long _, string? str) = await ms.ReadAsStringAsync(encoding: coding, bufferSize: 16); - - Debug.WriteLine(str); - - if (string.IsNullOrEmpty(text)) - Assert.IsNull(str); - else - Assert.AreEqual(str, text); - } - - [TestMethod] - public async Task NullStreamReadTest() - { - (long _, string? text) = await default(Stream)!.ReadAsStringAsync(); - Assert.IsNull(text); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Logging/LoggingTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Logging/LoggingTests.cs deleted file mode 100644 index c228e829f..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Logging/LoggingTests.cs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests.Logging; - -[TestClass] -public class LoggingTests -{ - [TestMethod] - public void AddMasaOpenTelemetryTest() - { - var logRecords = new List(); - bool isConfigureCalled = false; - using var loggerFactory = LoggerFactory.Create(builder => - { - var resources = ObservableHelper.CreateResourceBuilder(); - var uri = new Uri(ObservableHelper.OTLPURL); - builder.AddMasaOpenTelemetry(builder => - { - builder.SetResourceBuilder(resources); - builder.AddOtlpExporter(options => - { - if (uri != null) - options.Endpoint = uri; - }); - builder.AddInMemoryExporter(logRecords); - isConfigureCalled = true; - }); - }); - - Assert.IsTrue(isConfigureCalled); - var logger = loggerFactory.CreateLogger("OtlpLogExporterTests"); - logger.LogInformation("Hello from {name} {price}.", "tomato", 2.99); - Assert.IsTrue(logRecords.Count == 1); - var logRecord = logRecords[0]; - Assert.IsNotNull(logRecord.Attributes); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests.csproj deleted file mode 100644 index bf115ccc7..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests.csproj +++ /dev/null @@ -1,47 +0,0 @@ - - - - enable - enable - false - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Metric/MetricTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Metric/MetricTests.cs deleted file mode 100644 index b353f4a05..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Metric/MetricTests.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests.Metric; - -[TestClass] -public class MetricTests -{ - [TestMethod] - public void AddMasaOpenTelemetryTest() - { - bool isConfigureCalled = false; - IServiceCollection services = new ServiceCollection(); - services.AddMasaMetrics(builder => - { - var resources = ObservableHelper.CreateResourceBuilder(); - builder.SetResourceBuilder(resources); - builder.AddOtlpExporter(options => - { - options.Endpoint = new Uri(ObservableHelper.OTLPURL); - }); - isConfigureCalled = true; - }); - Assert.IsTrue(isConfigureCalled); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/ObservableHelper.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/ObservableHelper.cs deleted file mode 100644 index 9dcf552de..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/ObservableHelper.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests; - -internal static class ObservableHelper -{ - public static ResourceBuilder CreateResourceBuilder() - { - var options = new MasaObservableOptions - { - ServiceName = "test-app", - ServiceVersion = "0.1", - ServiceNameSpace = "develop" - }; - return ResourceBuilder.CreateDefault().AddMasaService(options); - } - - public const string OTLPURL = "http://localhost:4717"; -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Trace/ActivityTest.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Trace/ActivityTest.cs deleted file mode 100644 index 32f5aba71..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Trace/ActivityTest.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests.Trace; - -[TestClass] -public class ActivityTest -{ - [TestInitialize] - public void Initialize() - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - } - - [TestMethod] - public void HttpRequestMessageAddTagsTest() - { - HttpRequestMessage request = new() - { - Method = HttpMethod.Post - }; - var body = "{\"name\":\"张三\"}"; - request.Content = new StringContent(body, Encoding.GetEncoding("gbk"), "application/json"); - request.RequestUri = new Uri("http://localhost"); - - var activity = new Activity("tets"); - activity.AddMasaSupplement(request); - Assert.AreEqual(body, activity.GetTagItem(OpenTelemetryAttributeName.Http.REQUEST_CONTENT_BODY) as string); - } - - [TestMethod] - public void HttpResponseMessageAddTagsTest() - { - HttpResponseMessage response = new() - { - StatusCode = HttpStatusCode.OK, - Content = new StringContent("OK") - }; - - var activity = new Activity("tets"); - activity.AddMasaSupplement(response); - Assert.IsNotNull(activity); - } - - [TestMethod] - public void HttpRequestAddTagsTest() - { - Mock mock = new(); - mock.Setup(request => request.Method).Returns("post"); - mock.Setup(request => request.ContentType).Returns(" application/json; charset=gbk"); - mock.Setup(request => request.Host).Returns(new HostString("http://localhost")); - mock.Setup(request => request.Protocol).Returns("http1.1"); - mock.Setup(request => request.Scheme).Returns("http"); - var httpContext = new Mock(); - mock.Setup(request => request.HttpContext).Returns(httpContext.Object); - - var body = "{\"name\":\"张三\"}"; - var bytes = Encoding.GetEncoding("GBK").GetBytes(body); - using var ms = new MemoryStream(bytes); - mock.Setup(request => request.Body).Returns(ms); - mock.Setup(request => request.ContentLength).Returns(ms.Length); - - var activity = new Activity("tets"); - activity.AddMasaSupplement(mock.Object); - Assert.IsNotNull(activity); - Assert.AreEqual("http", activity.GetTagItem(OpenTelemetryAttributeName.Http.SCHEME) as string); - Assert.AreEqual("http1.1", activity.GetTagItem(OpenTelemetryAttributeName.Http.FLAVOR) as string); - Assert.AreEqual(body, activity.GetTagItem(OpenTelemetryAttributeName.Http.REQUEST_CONTENT_BODY) as string); - } - - [TestMethod] - public void HttpResponseAddTagsTest() - { - Mock mock = new(); - mock.Setup(request => request.StatusCode).Returns(200); - mock.Setup(request => request.ContentType).Returns(" application/json; charset=gbk"); - - var httpContext = new Mock(); - httpContext.Setup(context => context.User).Returns(new ClaimsPrincipal(new List { - new ClaimsIdentity( new Claim[]{ new Claim("sub","123456") },"userId"), - new ClaimsIdentity( new Claim[]{ new Claim("https://masastack.com/security/authentication/MasaNickName", "admin") },"userName") - })); - mock.Setup(request => request.HttpContext).Returns(httpContext.Object); - var body = "{\"name\":\"张三\"}"; - var bytes = Encoding.GetEncoding("GBK").GetBytes(body); - using var ms = new MemoryStream(bytes); - mock.Setup(request => request.Body).Returns(ms); - mock.Setup(request => request.ContentLength).Returns(ms.Length); - - var activity = new Activity("tets"); - activity.AddMasaSupplement(mock.Object); - Assert.IsNotNull(activity.GetTagItem(OpenTelemetryAttributeName.Http.RESPONSE_CONTENT_TYPE) as string); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Trace/TraceTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Trace/TraceTests.cs deleted file mode 100644 index a24cac7f8..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/Trace/TraceTests.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests.Trace; - -[TestClass] -public class TraceTests -{ - [TestMethod] - public void MasaTraceTest() - { - var logRecords = new List(); - bool isConfigureCalled = false; - using var loggerFactory = LoggerFactory.Create(builder => - { - var resources = ObservableHelper.CreateResourceBuilder(); - var uri = new Uri(ObservableHelper.OTLPURL); - - builder.AddMasaOpenTelemetry(builder => - { - builder.SetResourceBuilder(resources); - builder.AddOtlpExporter(options => - { - if (uri != null) - options.Endpoint = uri; - }); - builder.AddInMemoryExporter(logRecords); - isConfigureCalled = true; - }); - }); - - Assert.IsTrue(isConfigureCalled); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/_Imports.cs deleted file mode 100644 index 84d1c519d..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/_Imports.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Microsoft.AspNetCore.Http; -global using Microsoft.Extensions.Configuration; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.Extensions.Logging; -global using Microsoft.VisualStudio.TestTools.UnitTesting; -global using Moq; -global using OpenTelemetry.Logs; -global using OpenTelemetry.Metrics; -global using OpenTelemetry.Resources; -global using System; -global using System.Collections.Generic; -global using System.Diagnostics; -global using System.IO; -global using System.Net; -global using System.Net.Http; -global using System.Security.Claims; -global using System.Text; -global using System.Threading.Tasks; diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/appsettings.json b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/appsettings.json deleted file mode 100644 index 528c6f4e7..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.OpenTelemetry.Tests/appsettings.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "Masa": { - "Observable": { - "ServiceName": "test-app", - "ServiceNameSpace": "Development", - "ServiceVersion": "0.1.0", - "OtlpUrl": "http://localhost:4717" - } - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Extensions/CallerProviderExtensionsTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Extensions/CallerProviderExtensionsTests.cs deleted file mode 100644 index 19e994d10..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Extensions/CallerProviderExtensionsTests.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Tests.Extensions; - -[TestClass] -public class CallerProviderExtensionsTests -{ - [TestMethod] - public async Task SendGetRequestWithBodyParameterAsyncTest() - { - var caller = new Mock(); - string url = "http://locahost:80/test"; - var param = new { name = "name" }; - var result = "ok"; - caller.Setup(provider => provider.SendAsync(It.IsAny(), default)).ReturnsAsync(result); - var str = await caller.Object.GetByBodyAsync(url, param); - Assert.IsNotNull(str); - Assert.AreEqual(result, str); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Masa.Contrib.StackSdks.Tsc.Tests.csproj b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Masa.Contrib.StackSdks.Tsc.Tests.csproj deleted file mode 100644 index a012644ed..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Masa.Contrib.StackSdks.Tsc.Tests.csproj +++ /dev/null @@ -1,28 +0,0 @@ - - - - enable - false - true - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Service/LogServiceTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Service/LogServiceTests.cs deleted file mode 100644 index af9b17fe6..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Service/LogServiceTests.cs +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Tests.Service; - -[TestClass] -public class LogServiceTests -{ - private readonly Mock _mockHandler = new(); - private readonly Mock _httpClientFactory = new(); - private const string HOST = "http://localhost"; - private ITscClient _client; - private const string HTTP_CLIENT_NAME = "masa.contrib.stacksdks.tsc"; - - [TestInitialize] - public void Initialized() - { - IServiceCollection services = new ServiceCollection(); - services.AddSingleton(_httpClientFactory.Object); - var httpClient = new HttpClient(_mockHandler.Object) - { - BaseAddress = new Uri(HOST) - }; - _httpClientFactory.Setup(factory => factory.CreateClient(HTTP_CLIENT_NAME)).Returns(httpClient); - services.AddCaller(HTTP_CLIENT_NAME, builder => - { - builder.UseHttpClient(options => options.BaseAddress = HOST); - }); - var factory = services.BuildServiceProvider().GetRequiredService(); - _client = new TscClient(factory.Create(HTTP_CLIENT_NAME)); - } - - [TestMethod] - public async Task GetMappingFieldsAsyncTest() - { - var str = "[{\"name\":\"field1\",\"type\":\"text\"},{\"name\":\"field2\",\"type\":\"int\"}]"; - SetTestData(str); - var result = await _client.LogService.GetMappingAsync(); - Assert.IsNotNull(result); - } - - [TestMethod] - public async Task GetAggregationAsyncTest() - { - var time = DateTime.Now; - var query = new SimpleAggregateRequestDto - { - Start = time.AddMinutes(-15), - Keyword = "keyword", - End = time, - Name = "name", - Type = AggregateTypes.Count - }; - var str = "10"; - SetTestData(str); - var result = await _client.LogService.GetAggregationAsync(query); - Assert.IsNotNull(result); - } - - [TestMethod] - public async Task GetLatestAsyncTest() - { - var time = DateTime.Now; - var query = new LogLatestRequest - { - Start = time.AddMinutes(-15), - End = time, - IsDesc = true, - Query = "\"term\": {\"Resource.service.name\": \"masa.tsc.api\"}" - }; - - Assert.IsNotNull(query.Query); - Assert.IsTrue(query.Start > DateTime.MinValue); - Assert.IsTrue(query.End > DateTime.MinValue); - Assert.IsTrue(query.IsDesc); - - var str = - "{\"timestamp\":\"2022-11-15T07:01:28.2196126Z\",\"traceFlags\":0,\"severityText\":\"Information\",\"severityNumber\":9,\"body\":\"Request finished HTTP/2 GET https://localhost:18012/_blazor?id=_GmR6JVGGEuWA8wo5_vEgg&_=1668495688201 text/plain;charset=UTF-8 - - 200 1203 application/octet-stream 11.1170ms\",\"resource\":{\"service.instance.id\":\"57f5a1db-e0de-434d-aceb-45eb53a2efc8\",\"service.name\":\"masa-tsc-web-admin\",\"service.namespace\":\"Development\",\"service.version\":\"0.1.0\",\"telemetry.sdk.language\":\"dotnet\",\"telemetry.sdk.name\":\"opentelemetry\",\"telemetry.sdk.version\":\"1.3.0.519\"},\"attributes\":{\"dotnet.ilogger.category\":\"Microsoft.AspNetCore.Hosting.Diagnostics\"}}"; - SetTestData(str); - var result = await _client.LogService.GetLatestAsync(query); - Assert.IsNotNull(result); - } - - private void SetTestData(string result, HttpStatusCode httpStatusCode = HttpStatusCode.OK) - { - _mockHandler.Protected() - .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) - .ReturnsAsync(new HttpResponseMessage() - { - StatusCode = httpStatusCode, - Content = new StringContent(result) - }); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Service/MetricServiceTests.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Service/MetricServiceTests.cs deleted file mode 100644 index 299a2869d..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/Service/MetricServiceTests.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -namespace Masa.Contrib.StackSdks.Tsc.Tests.Service; - -[TestClass] -public class MetricServiceTests -{ - [TestMethod] - [DataRow(null)] - [DataRow(new string[] { "up", "prometheus_http_requests_total", "prometheus_http_request_duration_seconds_count" })] - [DataRow(new string[] { "not_exists_test" })] - public async Task GetNamesAsyncTest(IEnumerable match) - { - var data = new string[] { "up", "prometheus_http_requests_total", "prometheus_http_request_duration_seconds_count" }; - var caller = new Mock(); - caller.Setup(provider => provider.GetAsync?>(MetricService.NAMES_URI, It.Is>(dic => dic == null || dic.ContainsKey("match")), default)) - .ReturnsAsync((string? url, Dictionary param, CancellationToken token) => - { - if (param == null || !param.ContainsKey("match") || param["match"] is null || !param["match"].Contains("not_exists_test")) - return data; - return default; - }).Verifiable(); - var client = new TscClient(caller.Object); - var result = await client.MetricService.GetNamesAsync(match); - - if (match != null && match.Any(s => s == "not_exists_test")) - { - Assert.IsNull(result); - } - else - { - Assert.IsNotNull(result); - Assert.IsTrue(result.Any()); - } - } - - [TestMethod] - [DataRow("up", "2022-07-01T09:00:00.000Z", "2022-07-05T22:00:00.000Z")] - public async Task GetLabelValuesAsyncTest(string match, string start, string end) - { - var caller = new Mock(); - - - caller.Setup(provider => provider.SendAsync>>>(It.IsNotNull(), default)) - .ReturnsAsync(new Dictionary>> { - {"up",new Dictionary>{ - {"name",new List{"name1","name2"} } - } } - }); - var client = new TscClient(caller.Object); - - DateTime startDateTime = DateTime.Parse(start); - DateTime endDateTime = DateTime.Parse(end); - var query = new LableValuesRequest - { - Match = match, - Start = startDateTime, - End = endDateTime - }; - var result = await client.MetricService.GetLabelValuesAsync(query); - Assert.AreEqual(match, query.Matches.First()); - Assert.IsNotNull(result); - Assert.IsTrue(result.Any()); - } - - [TestMethod] - [DataRow("up", null, "2022-07-01T09:00:00.000Z", "2022-07-05T22:00:00.000Z")] - public async Task GetValuesAsyncTest(string match, IEnumerable labels, string start, string end) - { - var caller = new Mock(); - caller.Setup(provider => provider.SendAsync(It.IsNotNull(), default)).ReturnsAsync("1.0"); - var client = new TscClient(caller.Object); - - DateTime startDateTime = DateTime.Parse(start); - DateTime endDateTime = DateTime.Parse(end); - var result = await client.MetricService.GetValuesAsync(new ValuesRequest - { - Match = match, - Lables = labels, - End = endDateTime, - Start = startDateTime - }); - Assert.IsNotNull(result); - } -} diff --git a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/_Imports.cs b/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/_Imports.cs deleted file mode 100644 index 14a124515..000000000 --- a/src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Tsc.Test/_Imports.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) MASA Stack All rights reserved. -// Licensed under the MIT License. See LICENSE.txt in the project root for license information. - -global using Masa.BuildingBlocks.Service.Caller; -global using Masa.BuildingBlocks.StackSdks.Tsc; -global using Masa.BuildingBlocks.StackSdks.Tsc.Contracts.Model.Aggregate; -global using Masa.BuildingBlocks.StackSdks.Tsc.Model; -global using Masa.Contrib.StackSdks.Tsc.Service; -global using Microsoft.Extensions.DependencyInjection; -global using Microsoft.VisualStudio.TestTools.UnitTesting; -global using Moq; -global using Moq.Protected; -global using System; -global using System.Collections.Generic; -global using System.Linq; -global using System.Net; -global using System.Net.Http; -global using System.Threading; -global using System.Threading.Tasks;