diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json deleted file mode 100644 index 22ec7d7b..00000000 --- a/.config/dotnet-tools.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "version": 1, - "isRoot": true, - "tools": { - "paket": { - "version": "5.258.1", - "commands": [ - "paket" - ] - } - } -} \ No newline at end of file diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..3729ff0c --- /dev/null +++ b/.dockerignore @@ -0,0 +1,25 @@ +**/.classpath +**/.dockerignore +**/.env +**/.git +**/.gitignore +**/.project +**/.settings +**/.toolstarget +**/.vs +**/.vscode +**/*.*proj.user +**/*.dbmdl +**/*.jfm +**/azds.yaml +**/bin +**/charts +**/docker-compose* +**/Dockerfile* +**/node_modules +**/npm-debug.log +**/obj +**/secrets.dev.yaml +**/values.dev.yaml +LICENSE +README.md \ No newline at end of file diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..5f22e83b --- /dev/null +++ b/.editorconfig @@ -0,0 +1,23 @@ +[*.cs] +# CS0618: Type or member is obsolete +dotnet_diagnostic.CS0618.severity = none +# VSTHRD200: Use "Async" suffix for async methods +dotnet_diagnostic.VSTHRD200.severity = none +# SYSLIB0011: Type or member is obsolete +dotnet_diagnostic.SYSLIB0011.severity = none +# CS0168: Variable is declared but never used +dotnet_diagnostic.CS0168.severity = none +# CA1416: Validate platform compatibility +dotnet_diagnostic.CA1416.severity = error + + +# CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. +dotnet_diagnostic.CS4014.severity = none +# CS0169: The field is never used +dotnet_diagnostic.CS0169.severity = none +# CS0414: The field is assigned but its value is never used +dotnet_diagnostic.CS0414.severity = none +# CS0219: The variable is assigned but its value is never used +dotnet_diagnostic.CS0219.severity = none +# CS0649: Field is never assigned to, and will always have its default value +dotnet_diagnostic.CS0649.severity = none diff --git a/.gitignore b/.gitignore index 27f972f5..ce306bb4 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,7 @@ bld/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* +testlogs/ # NUNIT *.VisualState.xml @@ -258,4 +259,7 @@ OrleansAdoNetContent/ /.paket/ -launchSettings.json +/testlogs/ +/CustomEvent +/output* +/whitesource diff --git a/Directory.Build.props b/Directory.Build.props index b4fcf061..ee8f1ca6 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,11 +1,40 @@ - - Gigya Inc. - © 2020 Gigya Inc. - Microdot Framework - Microdot Framework - - 3.3.23 - $(SolutionDir)\test.runsettings - + + Gigya Inc. + © 2021 Gigya Inc. + Microdot Framework + Microdot Framework + https://github.com/gigya/microdot + https://github.com/gigya/microdot/blob/master/LICENSE.md + gigya microdot microservice microservices + 4.1.9 + true + + + + netstandard2.0;netstandard2.1;net5.0;net6.0 + win10-x64;linux-x64 + latest + true + Library + false + bin\$(Configuration) + $(SolutionDir)test.runsettings + $(SolutionDir)main.ruleset + + + + + + + + + + true + true + true + true + diff --git a/Directory.Build.targets b/Directory.Build.targets new file mode 100644 index 00000000..1ee72736 --- /dev/null +++ b/Directory.Build.targets @@ -0,0 +1,63 @@ + + + 3.5.1 + + + 3.6.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.Common.Tests/DummyCertificateLocator.cs b/Gigya.Microdot.Common.Tests/DummyCertificateLocator.cs index e89b5c45..443d0d1d 100644 --- a/Gigya.Microdot.Common.Tests/DummyCertificateLocator.cs +++ b/Gigya.Microdot.Common.Tests/DummyCertificateLocator.cs @@ -1,7 +1,7 @@ -using System; +using Gigya.Microdot.SharedLogic.HttpService; +using System; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; -using Gigya.Microdot.SharedLogic.HttpService; namespace Gigya.Microdot.Common.Tests { @@ -10,8 +10,21 @@ public class DummyCertificateLocator : ICertificateLocator public X509Certificate2 GetCertificate(string certName) { var ecdsa = ECDsa.Create(); // generate asymmetric key pair - var req = new CertificateRequest("cn=foobar", ecdsa, HashAlgorithmName.SHA256); - return req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5)); + + //var req = new CertificateRequest("cn=foobar", ecdsa, HashAlgorithmName.SHA256); + //return req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5)); + + return CreateSelfSignedRequest("cn=foobar", ecdsa, HashAlgorithmName.SHA256); + } + + private X509Certificate2 CreateSelfSignedRequest(string subjectName, ECDsa key, HashAlgorithmName hashAlgorithm) + { + Type certificateRequestType = Type.GetType("System.Security.Cryptography.X509Certificates.CertificateRequest"); + + object request = certificateRequestType?.GetConstructor(new[] { subjectName.GetType(), key.GetType(), hashAlgorithm.GetType() }) + ?.Invoke(new object[] { subjectName, key, hashAlgorithm }); + + return (X509Certificate2)certificateRequestType?.GetMethod("CreateSelfSigned")?.Invoke(request, new object[] { DateTimeOffset.Now, DateTimeOffset.Now.AddYears(5) }); } } } diff --git a/Gigya.Microdot.Common.Tests/FakesLoggersModules.cs b/Gigya.Microdot.Common.Tests/FakesLoggersModules.cs index f05d3799..73396277 100644 --- a/Gigya.Microdot.Common.Tests/FakesLoggersModules.cs +++ b/Gigya.Microdot.Common.Tests/FakesLoggersModules.cs @@ -1,10 +1,10 @@ -using System; using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Ninject; using Ninject; using Ninject.Syntax; +using System; namespace Gigya.Microdot.Common.Tests { diff --git a/Gigya.Microdot.Common.Tests/Gigya.Microdot.Common.Tests.csproj b/Gigya.Microdot.Common.Tests/Gigya.Microdot.Common.Tests.csproj index 9c886a36..38f3036a 100644 --- a/Gigya.Microdot.Common.Tests/Gigya.Microdot.Common.Tests.csproj +++ b/Gigya.Microdot.Common.Tests/Gigya.Microdot.Common.Tests.csproj @@ -1,16 +1,15 @@  - - net472 - Gigya.Microdot.Common.Tests - $(SolutionDir)main.ruleset - - - - - - - - - + + Gigya.Microdot.Common.Tests + + + + + + + + + + diff --git a/Gigya.Microdot.Common.Tests/KernelTestingExtensions.cs b/Gigya.Microdot.Common.Tests/KernelTestingExtensions.cs index 31fec285..2d7b5042 100644 --- a/Gigya.Microdot.Common.Tests/KernelTestingExtensions.cs +++ b/Gigya.Microdot.Common.Tests/KernelTestingExtensions.cs @@ -1,11 +1,11 @@ -using System; -using System.Diagnostics; -using Gigya.Microdot.Common.Tests; +using Gigya.Microdot.Common.Tests; using Gigya.Microdot.Hosting; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.SharedLogic.HttpService; using Ninject; +using System; +using System.Diagnostics; namespace Gigya.Microdot.Fakes.KernelUtils diff --git a/Gigya.Microdot.Common.Tests/Properties/AssemblyInfo.cs b/Gigya.Microdot.Common.Tests/Properties/AssemblyInfo.cs index c29581eb..d767500b 100644 --- a/Gigya.Microdot.Common.Tests/Properties/AssemblyInfo.cs +++ b/Gigya.Microdot.Common.Tests/Properties/AssemblyInfo.cs @@ -1,6 +1,4 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from diff --git a/Gigya.Microdot.Common.Tests/SpyEventPublisher.cs b/Gigya.Microdot.Common.Tests/SpyEventPublisher.cs index 62996d94..c0ecf52d 100644 --- a/Gigya.Microdot.Common.Tests/SpyEventPublisher.cs +++ b/Gigya.Microdot.Common.Tests/SpyEventPublisher.cs @@ -1,7 +1,7 @@ -using System.Collections.Concurrent; -using System.Threading.Tasks; using Gigya.Microdot.Interfaces.Events; using NSubstitute; +using System.Collections.Concurrent; +using System.Threading.Tasks; namespace Gigya.Microdot.Common.Tests { diff --git a/Gigya.Microdot.Common.Tests/paket.references b/Gigya.Microdot.Common.Tests/paket.references deleted file mode 100644 index 6e564ef8..00000000 --- a/Gigya.Microdot.Common.Tests/paket.references +++ /dev/null @@ -1,6 +0,0 @@ -NSubstitute -Ninject -System.Threading.Tasks.Dataflow -System.Data.DataSetExtensions -Microsoft.CSharp -System.Net.Http \ No newline at end of file diff --git a/Gigya.Microdot.Configuration/ConfigCache.cs b/Gigya.Microdot.Configuration/ConfigCache.cs index cccbcc8c..a1701d41 100644 --- a/Gigya.Microdot.Configuration/ConfigCache.cs +++ b/Gigya.Microdot.Configuration/ConfigCache.cs @@ -20,12 +20,12 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.Logging; +using Newtonsoft.Json.Linq; using System; using System.Linq; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; -using Gigya.Microdot.Interfaces.Logging; -using Newtonsoft.Json.Linq; namespace Gigya.Microdot.Configuration { diff --git a/Gigya.Microdot.Configuration/ConfigFileDeclaration.cs b/Gigya.Microdot.Configuration/ConfigFileDeclaration.cs index cc6589fe..22d9e611 100644 --- a/Gigya.Microdot.Configuration/ConfigFileDeclaration.cs +++ b/Gigya.Microdot.Configuration/ConfigFileDeclaration.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Newtonsoft.Json; +using System; namespace Gigya.Microdot.Configuration { diff --git a/Gigya.Microdot.Configuration/ConfigItem.cs b/Gigya.Microdot.Configuration/ConfigItem.cs index 12742e96..071455ff 100644 --- a/Gigya.Microdot.Configuration/ConfigItem.cs +++ b/Gigya.Microdot.Configuration/ConfigItem.cs @@ -20,14 +20,14 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.Interfaces.Configuration; +using Gigya.Microdot.SharedLogic.Exceptions; using System; using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; using System.Xml; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.Interfaces.Configuration; -using Gigya.Microdot.SharedLogic.Exceptions; namespace Gigya.Microdot.Configuration { @@ -89,15 +89,15 @@ public string Value public XmlNode Node { get; set; } - static readonly Regex MATCH_ENCRYPTED_CONFIG_STRING = new Regex(@"\$enc\((?.*?)\)", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled); + static readonly Regex MATCH_ENCRYPTED_CONFIG_STRING = new(@"\$enc\((?.*?)\)", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled); private string DecryptRawValue(string rawValue) { return MATCH_ENCRYPTED_CONFIG_STRING.Replace(rawValue, m => { - var inner = m.Groups[1].Value; - if (ConfigDecryptor. IsValidEncryptedStringFormat(inner)) + var inner = m.Groups["encrypted"].Value; + if (ConfigDecryptor.IsValidEncryptedStringFormat(inner)) { try { diff --git a/Gigya.Microdot.Configuration/ConfigurationFilesWatcher.cs b/Gigya.Microdot.Configuration/ConfigurationFilesWatcher.cs index 78168725..143fc997 100644 --- a/Gigya.Microdot.Configuration/ConfigurationFilesWatcher.cs +++ b/Gigya.Microdot.Configuration/ConfigurationFilesWatcher.cs @@ -20,12 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.LanguageExtensions; using System; using System.IO; using System.Threading; using System.Threading.Tasks.Dataflow; -using Gigya.Microdot.LanguageExtensions; -using Gigya.Microdot.SharedLogic.Utils; namespace Gigya.Microdot.Configuration { diff --git a/Gigya.Microdot.Configuration/ConfigurationLocationsParser.cs b/Gigya.Microdot.Configuration/ConfigurationLocationsParser.cs index 23dca0b3..d9867ba5 100644 --- a/Gigya.Microdot.Configuration/ConfigurationLocationsParser.cs +++ b/Gigya.Microdot.Configuration/ConfigurationLocationsParser.cs @@ -20,6 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.Interfaces.SystemWrappers; +using Gigya.Microdot.SharedLogic; +using Gigya.Microdot.SharedLogic.Exceptions; +using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; @@ -27,12 +32,6 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.Interfaces.SystemWrappers; -using Gigya.Microdot.SharedLogic; -using Gigya.Microdot.SharedLogic.Exceptions; -using Gigya.Microdot.SharedLogic.Utils; -using Newtonsoft.Json; namespace Gigya.Microdot.Configuration { diff --git a/Gigya.Microdot.Configuration/ConfigurationVerificator.cs b/Gigya.Microdot.Configuration/ConfigurationVerificator.cs index a65ad473..e1dfea2e 100644 --- a/Gigya.Microdot.Configuration/ConfigurationVerificator.cs +++ b/Gigya.Microdot.Configuration/ConfigurationVerificator.cs @@ -20,14 +20,14 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Linq; -using System.Collections.Generic; -using System.Diagnostics; -using Gigya.Microdot.Interfaces; using Gigya.Microdot.Configuration.Objects; +using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic.Exceptions; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; // ReSharper disable RedundantDefaultMemberInitializer #pragma warning disable 1591 // XML docs for public members diff --git a/Gigya.Microdot.Configuration/FileBasedConfigItemsSource.cs b/Gigya.Microdot.Configuration/FileBasedConfigItemsSource.cs index ce6feba7..8c4373ff 100644 --- a/Gigya.Microdot.Configuration/FileBasedConfigItemsSource.cs +++ b/Gigya.Microdot.Configuration/FileBasedConfigItemsSource.cs @@ -20,6 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.Interfaces.Configuration; +using Gigya.Microdot.Interfaces.SystemWrappers; +using Gigya.Microdot.SharedLogic.Exceptions; +using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; @@ -27,11 +32,6 @@ using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.Interfaces.Configuration; -using Gigya.Microdot.Interfaces.SystemWrappers; -using Gigya.Microdot.SharedLogic.Exceptions; -using Newtonsoft.Json.Linq; namespace Gigya.Microdot.Configuration { @@ -43,7 +43,7 @@ public class FileBasedConfigItemsSource : IConfigItemsSource private readonly IEnvironment _environment; private readonly ConfigDecryptor _configDecryptor; - private readonly Regex paramMatcher = new Regex(@"([^\\]|^)%(?[^%]+)%", RegexOptions.Compiled | RegexOptions.ExplicitCapture); + private readonly Regex paramMatcher = new(@"([^\\]|^)%(?[^%]+)%", RegexOptions.Compiled | RegexOptions.ExplicitCapture); /// @@ -87,8 +87,8 @@ public FileBasedConfigItemsSource( .Cast() .Select(match => new { - Placehodler = "%" + match.Groups[1].Value + "%", - Value = _environment[match.Groups[1].Value.ToUpperInvariant()] + Placehodler = $"%{match.Groups["envName"].Value}%", + Value = _environment[match.Groups["envName"].Value.ToUpperInvariant()] }).ToList(); if (list.Any()) @@ -111,7 +111,7 @@ public FileBasedConfigItemsSource( if (notFoundEnvVariables.Any()) { - throw new EnvironmentException("Configuration is dependent on following enviroment variables:" + string.Join("\n", notFoundEnvVariables) + "\n but they are not set."); + throw new EnvironmentException($"Configuration is dependent on following enviroment variables:{string.Join("\n", notFoundEnvVariables)}\n but they are not set."); } // return merged configuration @@ -161,19 +161,16 @@ private async Task ReadConfiguration(ConfigFile configFile, Dictionary } catch (FileNotFoundException ex) { - var errMsg = string.Format("Missing configuration file: " + configFile.FullName); - throw new ConfigurationException(errMsg, ex); + throw new ConfigurationException($"Missing configuration file: {configFile.FullName}", ex); } catch (IOException ex) { // the file didn't finish being written yet - var errMsg = string.Format("Error loading configuration file: " + configFile.FullName); - throw new ConfigurationException(errMsg, ex); + throw new ConfigurationException($"Error loading configuration file: {configFile.FullName}", ex); } catch (Exception ex) { - var errMsg = string.Format("Missing or invalid configuration file: " + configFile.FullName); - throw new ConfigurationException(errMsg, ex); + throw new ConfigurationException($"Missing or invalid configuration file: {configFile.FullName}", ex); } } diff --git a/Gigya.Microdot.Configuration/Gigya.Microdot.Configuration.csproj b/Gigya.Microdot.Configuration/Gigya.Microdot.Configuration.csproj index f4d916c9..1b4c9523 100644 --- a/Gigya.Microdot.Configuration/Gigya.Microdot.Configuration.csproj +++ b/Gigya.Microdot.Configuration/Gigya.Microdot.Configuration.csproj @@ -1,15 +1,19 @@  - - netstandard2.0 - 1591 - Gigya.Microdot.Configuration - true - $(SolutionDir)main.ruleset - - - - - - + + Gigya.Microdot.Configuration + + A configuration system based on a hierarchy of XML files, the values of + which are accessed using strongly-typed configuration objects. Supports + modification of the files on live service, environment variable substitution, + encryption and collections. Part of the Microdot framework. + + + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.Configuration/IConfigEventFactory.cs b/Gigya.Microdot.Configuration/IConfigEventFactory.cs index 65c8aa39..124fc907 100644 --- a/Gigya.Microdot.Configuration/IConfigEventFactory.cs +++ b/Gigya.Microdot.Configuration/IConfigEventFactory.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Threading.Tasks.Dataflow; using Gigya.Microdot.Interfaces.Configuration; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.Configuration { diff --git a/Gigya.Microdot.Configuration/Objects/ConfigObjectCreator.cs b/Gigya.Microdot.Configuration/Objects/ConfigObjectCreator.cs index 4cd27cea..4b944091 100644 --- a/Gigya.Microdot.Configuration/Objects/ConfigObjectCreator.cs +++ b/Gigya.Microdot.Configuration/Objects/ConfigObjectCreator.cs @@ -20,23 +20,22 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Text; -using System.Threading.Tasks.Dataflow; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.SharedLogic.Exceptions; using Gigya.Microdot.SharedLogic.Monitor; -using Metrics; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Linq.Expressions; +using System.Reflection; +using System.Text; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.Configuration.Objects { @@ -48,7 +47,7 @@ public class ConfigObjectCreator : IConfigObjectCreator /// public object ChangeNotifications { get; private set; } - private object Latest { get; set; } + private volatile object Latest; private UsageTracking UsageTracking { get; } private ILog Log { get; } private Type ObjectType { get; } @@ -200,6 +199,9 @@ public void Reload() { if (Latest != null) ValidationErrors = null; + + //if (ConfigPath.Contains("StackTraceEnhancerSettings")) + // Log.Info(_=> _($"RemoveThis: Decided that config was not changed for path {ConfigPath}. Old config :{LatestNode} new config: {config}")); return; } diff --git a/Gigya.Microdot.Configuration/Objects/ConfigObjectsCache.cs b/Gigya.Microdot.Configuration/Objects/ConfigObjectsCache.cs index e613cf42..9ef851e1 100644 --- a/Gigya.Microdot.Configuration/Objects/ConfigObjectsCache.cs +++ b/Gigya.Microdot.Configuration/Objects/ConfigObjectsCache.cs @@ -1,6 +1,6 @@ -using System; +using Gigya.Microdot.Interfaces; +using System; using System.Collections.Generic; -using Gigya.Microdot.Interfaces; namespace Gigya.Microdot.Configuration.Objects { diff --git a/Gigya.Microdot.Configuration/Objects/IConfigObjectsCache.cs b/Gigya.Microdot.Configuration/Objects/IConfigObjectsCache.cs index bf8fb82f..f2d6dd8c 100644 --- a/Gigya.Microdot.Configuration/Objects/IConfigObjectsCache.cs +++ b/Gigya.Microdot.Configuration/Objects/IConfigObjectsCache.cs @@ -1,9 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Gigya.Microdot.Interfaces; +using Gigya.Microdot.Interfaces; +using System; namespace Gigya.Microdot.Configuration.Objects { diff --git a/Gigya.Microdot.Configuration/Objects/RecursiveValidation.cs b/Gigya.Microdot.Configuration/Objects/RecursiveValidation.cs index c45f56b0..535efb44 100644 --- a/Gigya.Microdot.Configuration/Objects/RecursiveValidation.cs +++ b/Gigya.Microdot.Configuration/Objects/RecursiveValidation.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; -using System.Text; namespace Gigya.Microdot.Configuration.Objects { diff --git a/Gigya.Microdot.Configuration/Properties/AssemblyInfo.cs b/Gigya.Microdot.Configuration/Properties/AssemblyInfo.cs index 268f6c7d..41594e4e 100644 --- a/Gigya.Microdot.Configuration/Properties/AssemblyInfo.cs +++ b/Gigya.Microdot.Configuration/Properties/AssemblyInfo.cs @@ -21,6 +21,5 @@ #endregion using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; [assembly: InternalsVisibleTo("Gigya.Common.Configuration")] diff --git a/Gigya.Microdot.Configuration/ServicePointManagerDefaultConfig.cs b/Gigya.Microdot.Configuration/ServicePointManagerDefaultConfig.cs index f130916c..2f7420d5 100644 --- a/Gigya.Microdot.Configuration/ServicePointManagerDefaultConfig.cs +++ b/Gigya.Microdot.Configuration/ServicePointManagerDefaultConfig.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Gigya.Microdot.Interfaces.Configuration; +using System; namespace Gigya.Microdot.Configuration { diff --git a/Gigya.Microdot.Configuration/UsageTracking.cs b/Gigya.Microdot.Configuration/UsageTracking.cs index 805b54d6..706d3439 100644 --- a/Gigya.Microdot.Configuration/UsageTracking.cs +++ b/Gigya.Microdot.Configuration/UsageTracking.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.Logging; using System; using System.Collections.Concurrent; using System.Linq; -using Gigya.Microdot.Interfaces.Logging; namespace Gigya.Microdot.Configuration { diff --git a/Gigya.Microdot.Configuration/paket.references b/Gigya.Microdot.Configuration/paket.references deleted file mode 100644 index 70911872..00000000 --- a/Gigya.Microdot.Configuration/paket.references +++ /dev/null @@ -1,8 +0,0 @@ -Gigya.ServiceContract -System.Threading.Tasks.Dataflow -Newtonsoft.Json -System.ComponentModel.Annotations -System.Configuration.ConfigurationManager - -Microsoft.CSharp -System.Net.Http diff --git a/Gigya.Microdot.Configuration/paket.template b/Gigya.Microdot.Configuration/paket.template deleted file mode 100644 index c366c30f..00000000 --- a/Gigya.Microdot.Configuration/paket.template +++ /dev/null @@ -1,13 +0,0 @@ -type - project -description - A configuration system based on a hierarchy of XML files, the values of - which are accessed using strongly-typed configuration objects. Supports - modification of the files on live service, environment variable substitution, - encryption and collections. Part of the Microdot framework. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices configuration diff --git a/Gigya.Microdot.Fakes/ConsoleLog.cs b/Gigya.Microdot.Fakes/ConsoleLog.cs index 9f6039da..98b4d169 100644 --- a/Gigya.Microdot.Fakes/ConsoleLog.cs +++ b/Gigya.Microdot.Fakes/ConsoleLog.cs @@ -20,12 +20,12 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; -using Gigya.Microdot.SharedLogic.Logging; namespace Gigya.Microdot.Fakes { diff --git a/Gigya.Microdot.Fakes/ConsoleLogLoggersModules.cs b/Gigya.Microdot.Fakes/ConsoleLogLoggersModules.cs index bbfe9652..a54fc7ac 100644 --- a/Gigya.Microdot.Fakes/ConsoleLogLoggersModules.cs +++ b/Gigya.Microdot.Fakes/ConsoleLogLoggersModules.cs @@ -1,10 +1,10 @@ -using System; -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Ninject; using Ninject; using Ninject.Syntax; +using System; namespace Gigya.Microdot.UnitTests.Caching.Host { diff --git a/Gigya.Microdot.Fakes/DateTimeFake.cs b/Gigya.Microdot.Fakes/DateTimeFake.cs index 74417f4c..4c998586 100644 --- a/Gigya.Microdot.Fakes/DateTimeFake.cs +++ b/Gigya.Microdot.Fakes/DateTimeFake.cs @@ -20,11 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.SystemWrappers; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using Gigya.Microdot.Interfaces.SystemWrappers; namespace Gigya.Microdot.Fakes { diff --git a/Gigya.Microdot.Fakes/Discovery/AlwaysLocalHostDiscovery.cs b/Gigya.Microdot.Fakes/Discovery/AlwaysLocalHostDiscovery.cs index 9f0003fc..ca1a32d2 100644 --- a/Gigya.Microdot.Fakes/Discovery/AlwaysLocalHostDiscovery.cs +++ b/Gigya.Microdot.Fakes/Discovery/AlwaysLocalHostDiscovery.cs @@ -20,12 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Threading.Tasks; using Gigya.Microdot.ServiceDiscovery; -using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.ServiceDiscovery.Rewrite; using Gigya.Microdot.SharedLogic.Rewrite; +using System; +using System.Threading.Tasks; namespace Gigya.Microdot.Fakes.Discovery { diff --git a/Gigya.Microdot.Fakes/Discovery/LocalhostEndPointHandle.cs b/Gigya.Microdot.Fakes/Discovery/LocalhostEndPointHandle.cs index 283fc333..db3c526b 100644 --- a/Gigya.Microdot.Fakes/Discovery/LocalhostEndPointHandle.cs +++ b/Gigya.Microdot.Fakes/Discovery/LocalhostEndPointHandle.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Gigya.Microdot.ServiceDiscovery; using Gigya.Microdot.SharedLogic; +using System; namespace Gigya.Microdot.Fakes.Discovery { diff --git a/Gigya.Microdot.Fakes/Discovery/LocalhostServiceDiscovery.cs b/Gigya.Microdot.Fakes/Discovery/LocalhostServiceDiscovery.cs index a0fb76ba..fa8b6189 100644 --- a/Gigya.Microdot.Fakes/Discovery/LocalhostServiceDiscovery.cs +++ b/Gigya.Microdot.Fakes/Discovery/LocalhostServiceDiscovery.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Threading.Tasks; using Gigya.Microdot.ServiceDiscovery.Rewrite; using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.Rewrite; +using System.Threading.Tasks; namespace Gigya.Microdot.Fakes.Discovery { diff --git a/Gigya.Microdot.Fakes/FakeHealthMonitor.cs b/Gigya.Microdot.Fakes/FakeHealthMonitor.cs index 957bd384..9a3c947e 100644 --- a/Gigya.Microdot.Fakes/FakeHealthMonitor.cs +++ b/Gigya.Microdot.Fakes/FakeHealthMonitor.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; using Gigya.Microdot.SharedLogic.Monitor; using Metrics; +using System; +using System.Collections.Generic; namespace Gigya.Microdot.Fakes { diff --git a/Gigya.Microdot.Fakes/FakeLog.cs b/Gigya.Microdot.Fakes/FakeLog.cs index 57ab210a..cb9d6778 100644 --- a/Gigya.Microdot.Fakes/FakeLog.cs +++ b/Gigya.Microdot.Fakes/FakeLog.cs @@ -20,13 +20,13 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic.Events; +using Gigya.Microdot.SharedLogic.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; -using Gigya.Microdot.SharedLogic.Events; -using Gigya.Microdot.SharedLogic.Logging; namespace Gigya.Microdot.Fakes { diff --git a/Gigya.Microdot.Fakes/Gigya.Microdot.Fakes.csproj b/Gigya.Microdot.Fakes/Gigya.Microdot.Fakes.csproj index a9874476..663792b1 100644 --- a/Gigya.Microdot.Fakes/Gigya.Microdot.Fakes.csproj +++ b/Gigya.Microdot.Fakes/Gigya.Microdot.Fakes.csproj @@ -1,16 +1,16 @@  - - netstandard2.0 - Gigya.Microdot.Fakes - $(SolutionDir)main.ruleset - - - - - - - - - + + Gigya.Microdot.Fakes + Tools to help write tests for Microdot services. + gigya microdot microservice microservices fakes mocks mocking unit-testing + + + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.Fakes/LogSpy.cs b/Gigya.Microdot.Fakes/LogSpy.cs index a158e917..6e89f6d7 100644 --- a/Gigya.Microdot.Fakes/LogSpy.cs +++ b/Gigya.Microdot.Fakes/LogSpy.cs @@ -20,13 +20,13 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic.Events; +using Gigya.Microdot.SharedLogic.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; -using Gigya.Microdot.SharedLogic.Events; -using Gigya.Microdot.SharedLogic.Logging; namespace Gigya.Microdot.Fakes { @@ -54,6 +54,14 @@ public IEnumerable LogEntries } } + public void ClearLog() + { + lock (LogEntriesList) + { + LogEntriesList.Clear(); + } + } + protected override Task WriteLog(TraceEventType severity, LogCallSiteInfo logCallSiteInfo, string message, IDictionary encryptedTags, IDictionary unencryptedTags, Exception exception = null, string stackTrace = null) { diff --git a/Gigya.Microdot.Fakes/ManualConfigurationEvents.cs b/Gigya.Microdot.Fakes/ManualConfigurationEvents.cs index c92069af..5b3f18f8 100644 --- a/Gigya.Microdot.Fakes/ManualConfigurationEvents.cs +++ b/Gigya.Microdot.Fakes/ManualConfigurationEvents.cs @@ -20,16 +20,16 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Configuration; +using Gigya.Microdot.Interfaces.Configuration; using System; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; -using Gigya.Microdot.Configuration; -using Gigya.Microdot.Interfaces.Configuration; namespace Gigya.Microdot.Fakes { - public class ManualConfigurationEvents : IConfigurationDataWatcher + public class ManualConfigurationEvents : IConfigurationDataWatcher { private readonly IConfigEventFactory _eventFactory; private readonly BroadcastBlock block = new BroadcastBlock(null); diff --git a/Gigya.Microdot.Fakes/MetricsInitializerFake.cs b/Gigya.Microdot.Fakes/MetricsInitializerFake.cs index 6ade636d..983ecaa5 100644 --- a/Gigya.Microdot.Fakes/MetricsInitializerFake.cs +++ b/Gigya.Microdot.Fakes/MetricsInitializerFake.cs @@ -1,8 +1,8 @@ -using System; -using System.Threading.Tasks; -using Gigya.Microdot.Interfaces; +using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Logging; using Metrics; +using System; +using System.Threading.Tasks; namespace Gigya.Microdot.Fakes { diff --git a/Gigya.Microdot.Fakes/MockConfigItemsCollection.cs b/Gigya.Microdot.Fakes/MockConfigItemsCollection.cs index f6ed60f8..3268e850 100644 --- a/Gigya.Microdot.Fakes/MockConfigItemsCollection.cs +++ b/Gigya.Microdot.Fakes/MockConfigItemsCollection.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Configuration; using System; using System.Collections.Generic; using System.Linq; -using Gigya.Microdot.Configuration; namespace Gigya.Microdot.Fakes { diff --git a/Gigya.Microdot.Fakes/NullEventPublisher.cs b/Gigya.Microdot.Fakes/NullEventPublisher.cs index a9d024b3..79059cc8 100644 --- a/Gigya.Microdot.Fakes/NullEventPublisher.cs +++ b/Gigya.Microdot.Fakes/NullEventPublisher.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Threading.Tasks; using Gigya.Microdot.Interfaces.Events; +using System.Threading.Tasks; namespace Gigya.Microdot.Fakes { diff --git a/Gigya.Microdot.Fakes/NullLog.cs b/Gigya.Microdot.Fakes/NullLog.cs index 457acb19..8663352f 100644 --- a/Gigya.Microdot.Fakes/NullLog.cs +++ b/Gigya.Microdot.Fakes/NullLog.cs @@ -20,11 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; -using Gigya.Microdot.SharedLogic.Logging; namespace Gigya.Microdot.Fakes { diff --git a/Gigya.Microdot.Fakes/OverridableConfigItems.cs b/Gigya.Microdot.Fakes/OverridableConfigItems.cs index 036dae23..9d61c1d3 100644 --- a/Gigya.Microdot.Fakes/OverridableConfigItems.cs +++ b/Gigya.Microdot.Fakes/OverridableConfigItems.cs @@ -20,11 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Configuration; +using Gigya.Microdot.Interfaces.Configuration; using System; using System.Collections.Generic; using System.Threading.Tasks; -using Gigya.Microdot.Configuration; -using Gigya.Microdot.Interfaces.Configuration; namespace Gigya.Microdot.Fakes { diff --git a/Gigya.Microdot.Fakes/Properties/AssemblyInfo.cs b/Gigya.Microdot.Fakes/Properties/AssemblyInfo.cs index d625fc36..eed5f5ba 100644 --- a/Gigya.Microdot.Fakes/Properties/AssemblyInfo.cs +++ b/Gigya.Microdot.Fakes/Properties/AssemblyInfo.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Reflection; using System.Runtime.InteropServices; // The following GUID is for the ID of the typelib if this project is exposed to COM diff --git a/Gigya.Microdot.Fakes/TraceLog.cs b/Gigya.Microdot.Fakes/TraceLog.cs index 88b469f8..14928d53 100644 --- a/Gigya.Microdot.Fakes/TraceLog.cs +++ b/Gigya.Microdot.Fakes/TraceLog.cs @@ -20,12 +20,12 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; -using Gigya.Microdot.SharedLogic.Logging; namespace Gigya.Microdot.Fakes { diff --git a/Gigya.Microdot.Fakes/paket.references b/Gigya.Microdot.Fakes/paket.references deleted file mode 100644 index 8d51eaca..00000000 --- a/Gigya.Microdot.Fakes/paket.references +++ /dev/null @@ -1,3 +0,0 @@ -Ninject -System.Net.Http -System.Threading.Tasks.Dataflow diff --git a/Gigya.Microdot.Fakes/paket.template b/Gigya.Microdot.Fakes/paket.template deleted file mode 100644 index 7127d911..00000000 --- a/Gigya.Microdot.Fakes/paket.template +++ /dev/null @@ -1,10 +0,0 @@ -type - project -description - Tools to help write tests for Microdot services. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices fakes mocks mocking unit-testing \ No newline at end of file diff --git a/Gigya.Microdot.Hosting/CrashHandler.cs b/Gigya.Microdot.Hosting/CrashHandler.cs index c08eacfe..ca95ae07 100644 --- a/Gigya.Microdot.Hosting/CrashHandler.cs +++ b/Gigya.Microdot.Hosting/CrashHandler.cs @@ -20,11 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.Events; +using Gigya.Microdot.SharedLogic.Events; using System; using System.Diagnostics; using System.Threading; -using Gigya.Microdot.Interfaces.Events; -using Gigya.Microdot.SharedLogic.Events; namespace Gigya.Microdot.Hosting { diff --git a/Gigya.Microdot.Hosting/Environment/ApplicationInfoSource.cs b/Gigya.Microdot.Hosting/Environment/ApplicationInfoSource.cs index 2ab99619..7f3482fe 100644 --- a/Gigya.Microdot.Hosting/Environment/ApplicationInfoSource.cs +++ b/Gigya.Microdot.Hosting/Environment/ApplicationInfoSource.cs @@ -14,6 +14,10 @@ public sealed class ApplicationInfoSource : IHostEnvironmentSource public string ConsulAddress { get; } + public string HostIPAddress { get; } + + public string ContainerName { get; } + public string InstanceName { get; } public CurrentApplicationInfo ApplicationInfo { get; } diff --git a/Gigya.Microdot.Hosting/Environment/EnvironmentVarialbesConfigurationSource.cs b/Gigya.Microdot.Hosting/Environment/EnvironmentVarialbesConfigurationSource.cs index 4e0a94a9..e3377424 100644 --- a/Gigya.Microdot.Hosting/Environment/EnvironmentVarialbesConfigurationSource.cs +++ b/Gigya.Microdot.Hosting/Environment/EnvironmentVarialbesConfigurationSource.cs @@ -1,10 +1,8 @@ using Gigya.Microdot.LanguageExtensions; using Gigya.Microdot.SharedLogic; -using System; using System.Collections; using System.Collections.Generic; using System.IO; -using System.Text; namespace Gigya.Microdot.Hosting.Environment { @@ -18,6 +16,10 @@ public sealed class EnvironmentVarialbesConfigurationSource : IHostEnvironmentSo public string DeploymentEnvironment { get; } public string ConsulAddress { get; } + + public string HostIPAddress { get; } + + public string ContainerName { get; } public string InstanceName { get; } @@ -37,6 +39,8 @@ public EnvironmentVarialbesConfigurationSource() this.Region = System.Environment.GetEnvironmentVariable("REGION"); this.DeploymentEnvironment = System.Environment.GetEnvironmentVariable("ENV"); this.ConsulAddress = System.Environment.GetEnvironmentVariable("CONSUL"); + this.HostIPAddress = System.Environment.GetEnvironmentVariable("HOSTIPADDRESS"); + this.ContainerName = System.Environment.GetEnvironmentVariable("CONTAINERNAME"); this.InstanceName = System.Environment.GetEnvironmentVariable("GIGYA_SERVICE_INSTANCE_NAME"); this.ConfigRoot = System.Environment.GetEnvironmentVariable("GIGYA_CONFIG_ROOT")?.To(x => new DirectoryInfo(x)); this.LoadPathsFile = System.Environment.GetEnvironmentVariable("GIGYA_CONFIG_PATHS_FILE")?.To(x => new FileInfo(x)); diff --git a/Gigya.Microdot.Hosting/Environment/FreeHostEnvironmentSource.cs b/Gigya.Microdot.Hosting/Environment/FreeHostEnvironmentSource.cs index 5fb726a6..6e48d271 100644 --- a/Gigya.Microdot.Hosting/Environment/FreeHostEnvironmentSource.cs +++ b/Gigya.Microdot.Hosting/Environment/FreeHostEnvironmentSource.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic; using System.Collections.Generic; using System.IO; -using Gigya.Microdot.SharedLogic; namespace Gigya.Microdot.Hosting.Environment { @@ -35,6 +35,10 @@ public sealed class FreeHostEnvironmentSource : IHostEnvironmentSource public string DeploymentEnvironment { get; } public string ConsulAddress { get; } + + public string HostIPAddress { get; } + + public string ContainerName { get; } public string InstanceName { get; } @@ -51,6 +55,8 @@ public FreeHostEnvironmentSource( string region = null, string deploymentEnvironment = null, string consulAddress = null, + string HostIPAddress = null, + string containerName = null, string instanceName = null, CurrentApplicationInfo applicationInfo = null, DirectoryInfo configRoot = null, @@ -62,6 +68,8 @@ public FreeHostEnvironmentSource( this.Region = region; this.DeploymentEnvironment = deploymentEnvironment; this.ConsulAddress = consulAddress; + this.HostIPAddress = HostIPAddress; + this.ContainerName = ContainerName; this.InstanceName = instanceName; this.ApplicationInfo = applicationInfo; this.ConfigRoot = configRoot; diff --git a/Gigya.Microdot.Hosting/Environment/HostEnvironment.cs b/Gigya.Microdot.Hosting/Environment/HostEnvironment.cs index 4e45f34f..bb41d826 100644 --- a/Gigya.Microdot.Hosting/Environment/HostEnvironment.cs +++ b/Gigya.Microdot.Hosting/Environment/HostEnvironment.cs @@ -20,17 +20,16 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.IO; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.LanguageExtensions; using Gigya.Microdot.SharedLogic; -using Gigya.Microdot.SharedLogic.Utils; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; namespace Gigya.Microdot.Hosting.Environment { @@ -64,6 +63,8 @@ public HostEnvironment(IEnumerable sources) Region = pipeParameter(nameof(Region), Region, s.Region); DeploymentEnvironment = pipeParameter(nameof(DeploymentEnvironment), DeploymentEnvironment, s.DeploymentEnvironment); ConsulAddress = pipeParameter(nameof(ConsulAddress), ConsulAddress, s.ConsulAddress); + HostIPAddress = pipeParameter(nameof(HostIPAddress), HostIPAddress, s.HostIPAddress); + ContainerName = pipeParameter(nameof(ContainerName), ContainerName, s.ContainerName); ApplicationInfo = pipeParameter(nameof(ApplicationInfo), ApplicationInfo, s.ApplicationInfo); InstanceName = pipeParameter(nameof(InstanceName), InstanceName, s.InstanceName); ConfigRoot = pipeFsiParameter(nameof(ConfigRoot), ConfigRoot, s.ConfigRoot); @@ -154,6 +155,8 @@ private FileInfo GetDefaultPathsFile() => public string Region { get; } public string DeploymentEnvironment { get; } public string ConsulAddress { get; } + public string HostIPAddress { get; } + public string ContainerName { get; } public DirectoryInfo ConfigRoot { get; } public FileInfo LoadPathsFile { get; } public CurrentApplicationInfo ApplicationInfo { get; } @@ -178,9 +181,10 @@ public static HostEnvironment CreateDefaultEnvironment(string serviceName, Versi public static IEnumerable GetDefaultSources(string serviceName, Version infraVersion, ServiceArguments arguments = null) { - var l = new List(3); - - l.Add(new EnvironmentVarialbesConfigurationSource()); + var l = new List(3) + { + new EnvironmentVarialbesConfigurationSource() + }; if (System.Environment.GetEnvironmentVariable("GIGYA_ENVVARS_FILE") is string path) { @@ -194,8 +198,7 @@ public static IEnumerable GetDefaultSources(string servi if (arguments != null) { - l.Add(new FreeHostEnvironmentSource( - instanceName: arguments.InstanceName)); + l.Add(new FreeHostEnvironmentSource(instanceName: arguments.InstanceName)); } l.Add( @@ -204,7 +207,8 @@ public static IEnumerable GetDefaultSources(string servi serviceName, System.Environment.UserName, System.Net.Dns.GetHostName(), - infraVersion: infraVersion))); + infraVersion: infraVersion, + containerName: System.Environment.GetEnvironmentVariable("CONTAINERNAME")))); return l; } diff --git a/Gigya.Microdot.Hosting/Environment/IHostEnvironmentSource.cs b/Gigya.Microdot.Hosting/Environment/IHostEnvironmentSource.cs index 4048c533..55de90e4 100644 --- a/Gigya.Microdot.Hosting/Environment/IHostEnvironmentSource.cs +++ b/Gigya.Microdot.Hosting/Environment/IHostEnvironmentSource.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic; using System.Collections.Generic; using System.IO; -using Gigya.Microdot.SharedLogic; namespace Gigya.Microdot.Hosting.Environment { @@ -32,6 +32,8 @@ public interface IHostEnvironmentSource string Region { get; } string DeploymentEnvironment { get; } string ConsulAddress { get; } + string HostIPAddress { get; } + string ContainerName { get; } string InstanceName { get; } CurrentApplicationInfo ApplicationInfo { get; } DirectoryInfo ConfigRoot { get; } diff --git a/Gigya.Microdot.Hosting/Environment/LegacyFileHostConfigurationSource.cs b/Gigya.Microdot.Hosting/Environment/LegacyFileHostConfigurationSource.cs index a6fed439..36970724 100644 --- a/Gigya.Microdot.Hosting/Environment/LegacyFileHostConfigurationSource.cs +++ b/Gigya.Microdot.Hosting/Environment/LegacyFileHostConfigurationSource.cs @@ -19,6 +19,10 @@ public sealed class LegacyFileHostConfigurationSource : IHostEnvironmentSource public string DeploymentEnvironment { get; } public string ConsulAddress { get; } + + public string HostIPAddress { get; } + + public string ContainerName { get; } public string InstanceName { get; } @@ -40,6 +44,8 @@ public LegacyFileHostConfigurationSource(string path) Region = get("REGION"); DeploymentEnvironment = get("ENV"); ConsulAddress = get("CONSUL"); + HostIPAddress = get("HOSTIPADDRESS"); + ContainerName = get("CONTAINERNAME"); InstanceName = get("GIGYA_SERVICE_INSTANCE_NAME"); ConfigRoot = get("GIGYA_CONFIG_ROOT")?.To(x => new DirectoryInfo(x)); diff --git a/Gigya.Microdot.Hosting/Environment/TestHostEnvironmentSource.cs b/Gigya.Microdot.Hosting/Environment/TestHostEnvironmentSource.cs index 3ff8613f..d5e6e939 100644 --- a/Gigya.Microdot.Hosting/Environment/TestHostEnvironmentSource.cs +++ b/Gigya.Microdot.Hosting/Environment/TestHostEnvironmentSource.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Collections.Generic; -using System.IO; using Gigya.Microdot.LanguageExtensions; using Gigya.Microdot.SharedLogic; +using System.Collections.Generic; +using System.IO; namespace Gigya.Microdot.Hosting.Environment { @@ -36,6 +36,10 @@ public sealed class TestHostEnvironmentSource : IHostEnvironmentSource public string DeploymentEnvironment { get; } public string ConsulAddress { get; } + + public string HostIPAddress { get; } + + public string ContainerName { get; } public string InstanceName { get; } @@ -52,6 +56,8 @@ public TestHostEnvironmentSource( string region = null, string deploymentEnvironment = null, string consulAddress = null, + string hostIPAddress = null, + string containerName = null, string instanceName = null, CurrentApplicationInfo applicationInfo = null, DirectoryInfo configRoot = null, @@ -63,6 +69,8 @@ public TestHostEnvironmentSource( this.Region = region ?? "region"; this.DeploymentEnvironment = deploymentEnvironment ?? "env"; this.ConsulAddress = consulAddress ?? "addr"; + this.HostIPAddress = hostIPAddress; + this.ContainerName = containerName; this.InstanceName = instanceName ?? "test-instance"; this.ApplicationInfo = applicationInfo ?? new CurrentApplicationInfo(appName ?? "test", System.Environment.UserName, System.Net.Dns.GetHostName()); this.ConfigRoot = configRoot ?? new DirectoryInfo(this.GetType().Assembly.Location.To(Path.GetDirectoryName)); diff --git a/Gigya.Microdot.Hosting/Events/ServiceCallEvent.cs b/Gigya.Microdot.Hosting/Events/ServiceCallEvent.cs index da443625..7ead61b9 100644 --- a/Gigya.Microdot.Hosting/Events/ServiceCallEvent.cs +++ b/Gigya.Microdot.Hosting/Events/ServiceCallEvent.cs @@ -20,13 +20,12 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.HttpService; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; namespace Gigya.Microdot.Hosting.Events { diff --git a/Gigya.Microdot.Hosting/Events/StatsEvent.cs b/Gigya.Microdot.Hosting/Events/StatsEvent.cs index 310cbcde..3fe58c57 100644 --- a/Gigya.Microdot.Hosting/Events/StatsEvent.cs +++ b/Gigya.Microdot.Hosting/Events/StatsEvent.cs @@ -20,12 +20,12 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Globalization; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.Measurement; +using System; +using System.Collections.Generic; +using System.Globalization; namespace Gigya.Microdot.Hosting.Events { diff --git a/Gigya.Microdot.Hosting/Gigya.Microdot.Hosting.csproj b/Gigya.Microdot.Hosting/Gigya.Microdot.Hosting.csproj index 303cdb35..ccf23f24 100644 --- a/Gigya.Microdot.Hosting/Gigya.Microdot.Hosting.csproj +++ b/Gigya.Microdot.Hosting/Gigya.Microdot.Hosting.csproj @@ -1,19 +1,14 @@  - - netstandard2.0 - true - Gigya.Microdot.Hosting - CODE_ANALYSIS;DEBUG;TRACE - $(SolutionDir)main.ruleset - 8.0 - - - - - - - - - + + Gigya.Microdot.Hosting + Infrastructure used for hosting Microdot services, part of the Microdot framework. + gigya microdot microservice microservices + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.Hosting/HttpService/AbstractServiceActivator.cs b/Gigya.Microdot.Hosting/HttpService/AbstractServiceActivator.cs index 8cd28955..c3d4b022 100644 --- a/Gigya.Microdot.Hosting/HttpService/AbstractServiceActivator.cs +++ b/Gigya.Microdot.Hosting/HttpService/AbstractServiceActivator.cs @@ -20,11 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using System.Diagnostics; -using System.Reflection; using System.Threading.Tasks; -using Gigya.Common.Contracts; namespace Gigya.Microdot.Hosting.HttpService { diff --git a/Gigya.Microdot.Hosting/HttpService/EndPointMetaData.cs b/Gigya.Microdot.Hosting/HttpService/EndPointMetaData.cs index eb0bb234..3c52b46c 100644 --- a/Gigya.Microdot.Hosting/HttpService/EndPointMetaData.cs +++ b/Gigya.Microdot.Hosting/HttpService/EndPointMetaData.cs @@ -21,12 +21,11 @@ #endregion -using System; +using Gigya.Microdot.SharedLogic.Events; +using Gigya.ServiceContract.Attributes; using System.Collections.Immutable; using System.Linq; using System.Reflection; -using Gigya.Microdot.SharedLogic.Events; -using Gigya.ServiceContract.Attributes; namespace Gigya.Microdot.Hosting.HttpService { diff --git a/Gigya.Microdot.Hosting/HttpService/Endpoints/ConfigurationResponseBuilder.cs b/Gigya.Microdot.Hosting/HttpService/Endpoints/ConfigurationResponseBuilder.cs index ef71a859..df0d3a2e 100644 --- a/Gigya.Microdot.Hosting/HttpService/Endpoints/ConfigurationResponseBuilder.cs +++ b/Gigya.Microdot.Hosting/HttpService/Endpoints/ConfigurationResponseBuilder.cs @@ -20,6 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Configuration; +using Gigya.Microdot.Interfaces; +using Gigya.Microdot.Interfaces.SystemWrappers; +using Gigya.Microdot.SharedLogic; +using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; @@ -30,11 +35,6 @@ using System.Reflection; using System.Runtime; using System.Text; -using Gigya.Microdot.Configuration; -using Gigya.Microdot.Interfaces; -using Gigya.Microdot.Interfaces.SystemWrappers; -using Gigya.Microdot.SharedLogic; -using Newtonsoft.Json; namespace Gigya.Microdot.Hosting.HttpService.Endpoints { @@ -161,10 +161,15 @@ private Dictionary GetHashes() private Dictionary GetEnvironmentVariables() { + string[] envs = { "DC", "ZONE", "REGION", "ENV", "CONSUL", "OS" }; + return System.Environment.GetEnvironmentVariables() .OfType() .Select(x => new { Name = (string)x.Key, Value = (string)x.Value }) - .Where(x => x.Name.ToUpper() == "DC" || x.Name.ToUpper() == "ZONE" || x.Name.ToUpper() == "REGION" || x.Name.ToUpper() == "ENV" || x.Name.ToUpper().Contains("GIGYA")) + .Where(x => envs.Contains(x.Name.ToUpper()) + || x.Name.ToUpper().Contains("GIGYA") + || x.Name.ToUpper().Contains("DOTNET") + ) .OrderBy(x => x.Name) .ToDictionary(x => x.Name, x => x.Value); } @@ -173,7 +178,7 @@ private Dictionary GetAssemblyVersions() { var specialVersions = new[] { new { Name = "(service)", Version = GetVersion(Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()) } }; var assemblyVersions = AssemblyProvider.GetAssemblies() - .Where(x => x.GlobalAssemblyCache == false) + //.Where(x => x.GlobalAssemblyCache == false) .Select(a => new { a.GetName().Name, Version = GetVersion(a) }); return specialVersions diff --git a/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCCollectionResult.cs b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCCollectionResult.cs new file mode 100644 index 00000000..cd9f5bbf --- /dev/null +++ b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCCollectionResult.cs @@ -0,0 +1,16 @@ +namespace Gigya.Microdot.Hosting.HttpService.Endpoints.GCEndpoint +{ + public class GCCollectionResult + { + public long TotalMemoryBeforeGC { get; } + public long TotalMemoryAfterGC { get; } + public long ElapsedMilliseconds { get; } + + public GCCollectionResult(long totalMemoryBeforeGc, long totalMemoryAfterGc, long elapsedMilliseconds) + { + TotalMemoryBeforeGC = totalMemoryBeforeGc; + TotalMemoryAfterGC = totalMemoryAfterGc; + ElapsedMilliseconds = elapsedMilliseconds; + } + } +} \ No newline at end of file diff --git a/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCCustomEndpoint.cs b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCCustomEndpoint.cs new file mode 100644 index 00000000..b05f9510 --- /dev/null +++ b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCCustomEndpoint.cs @@ -0,0 +1,47 @@ +using System; +using System.Net; +using System.Threading.Tasks; +using Newtonsoft.Json; + +namespace Gigya.Microdot.Hosting.HttpService.Endpoints.GCEndpoint +{ + public class GCCustomEndpoint:ICustomEndpoint + { + private readonly IGCEndpointHandler _gcEndpointHandler; + + public GCCustomEndpoint(IGCEndpointHandler gcEndpointHandler) + { + _gcEndpointHandler = gcEndpointHandler; + } + public async Task TryHandle(HttpListenerContext context, WriteResponseDelegate writeResponse) + { + try + { + var url = context?.Request.Url; + var sourceIPAddress = context?.Request.RemoteEndPoint?.Address; + var queryString = context?.Request.QueryString; + + var gcHandleResult = await _gcEndpointHandler.Handle(url, queryString, sourceIPAddress); + + if (gcHandleResult.Successful) + { + await writeResponse( + JsonConvert.SerializeObject(new + { + gcHandleResult.Message, + gcHandleResult.GcCollectionResult + }) + ).ConfigureAwait(false); + + return true; + } + } + catch (Exception e) + { + // ignore exceptions + } + + return false; + } + } +} \ No newline at end of file diff --git a/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCEndpointHandler.cs b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCEndpointHandler.cs new file mode 100644 index 00000000..fc7dfc4c --- /dev/null +++ b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCEndpointHandler.cs @@ -0,0 +1,72 @@ +using System; +using System.Collections.Specialized; +using System.Net; +using System.Threading.Tasks; +using Gigya.Microdot.Hosting.Service; +using Gigya.Microdot.Interfaces.Logging; + +namespace Gigya.Microdot.Hosting.HttpService.Endpoints.GCEndpoint +{ + public interface IGCEndpointHandler + { + Task Handle(Uri url, NameValueCollection queryString, IPAddress ipAddress); + } + + public class GCEndpointHandler : IGCEndpointHandler + { + private readonly Func _microdotHostingConfigFactory; + private readonly ILog _logger; + private readonly IGCEndpointHandlerUtils _gcEndpointHandlerUtils; + + public GCEndpointHandler(Func microdotHostingConfigFactory, + ILog logger, + IGCEndpointHandlerUtils gcEndpointHandlerUtils) + { + _microdotHostingConfigFactory = microdotHostingConfigFactory; + _logger = logger; + _gcEndpointHandlerUtils = gcEndpointHandlerUtils; + } + + public async Task Handle(Uri url, NameValueCollection queryString, IPAddress ipAddress) + { + if (url.AbsolutePath != "/force-traffic-affecting-gc") + return new GCHandlingResult(false); + + var config = _microdotHostingConfigFactory(); + + if (config.GCEndpointEnabled) + { + + if (_gcEndpointHandlerUtils.TryProcessAsTokenGenerationRequest(queryString, ipAddress, out var additionalInfo)) + return new GCHandlingResult(true, additionalInfo); + + if (false == _gcEndpointHandlerUtils.ValidateToken(queryString, out additionalInfo)) + return new GCHandlingResult(true, additionalInfo); + + if (false == _gcEndpointHandlerUtils.ValidateGcType(queryString, out additionalInfo, out var gcType)) + return new GCHandlingResult(true, additionalInfo); + + var gcCollectionResult = _gcEndpointHandlerUtils.Collect(gcType); + + _logger.Warn(log=>log("GC endpoint was called",unencryptedTags:new + { + GcType = gcType, + TotalMemoryAfterGC = gcCollectionResult.TotalMemoryAfterGC, + TotalMemoryBeforeGC = gcCollectionResult.TotalMemoryBeforeGC, + GCDuration = gcCollectionResult.ElapsedMilliseconds, + IPAddress = ipAddress.ToString() + })); + + return new GCHandlingResult( + successful:true, + message:"GC ran successfully", + gcCollectionResult: gcCollectionResult); + + } + else + { + return new GCHandlingResult(false); + } + } + } +} \ No newline at end of file diff --git a/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCHandlingResult.cs b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCHandlingResult.cs new file mode 100644 index 00000000..020b3c51 --- /dev/null +++ b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCHandlingResult.cs @@ -0,0 +1,16 @@ +namespace Gigya.Microdot.Hosting.HttpService.Endpoints.GCEndpoint +{ + public class GCHandlingResult + { + public bool Successful { get; } + public string Message { get; } + public GCCollectionResult GcCollectionResult { get; } + + public GCHandlingResult(bool successful, string message = null, GCCollectionResult gcCollectionResult = null) + { + Successful = successful; + Message = message; + GcCollectionResult = gcCollectionResult; + } + } +} \ No newline at end of file diff --git a/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCTokenContainer.cs b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCTokenContainer.cs new file mode 100644 index 00000000..49493b6e --- /dev/null +++ b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCTokenContainer.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Concurrent; +using Gigya.Microdot.Interfaces.SystemWrappers; + +namespace Gigya.Microdot.Hosting.HttpService.Endpoints.GCEndpoint +{ + public interface IGCTokenContainer + { + Guid GenerateToken(); + bool ValidateToken(Guid tokenToValidate); + } + + public class GCTokenContainer : IGCTokenContainer + { + private readonly IDateTime _dateTimeFactory; + private ConcurrentDictionary _gcCollectionTokens = new ConcurrentDictionary(); + + + public GCTokenContainer(IDateTime _dateTimeFactory) + { + this._dateTimeFactory = _dateTimeFactory; + } + + + public Guid GenerateToken() + { + var now = _dateTimeFactory.UtcNow; + + foreach (var tokenKvp in _gcCollectionTokens) + { + if (now - tokenKvp.Value > TimeSpan.FromMinutes(30)) + { + _gcCollectionTokens.TryRemove(tokenKvp.Key, out _); + } + } + + var newToken = Guid.NewGuid(); + _gcCollectionTokens.TryAdd(newToken, now); + + return newToken; + } + + public bool ValidateToken(Guid tokenToValidate) + { + var now = _dateTimeFactory.UtcNow; + + if (_gcCollectionTokens.TryGetValue(tokenToValidate, out var toeknCreationTime)) + { + if (now - toeknCreationTime < TimeSpan.FromMinutes(30)) + return true; + + _gcCollectionTokens.TryRemove(tokenToValidate, out toeknCreationTime); + } + + return false; + } + } +} \ No newline at end of file diff --git a/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCTokenHandler.cs b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCTokenHandler.cs new file mode 100644 index 00000000..5a21cda4 --- /dev/null +++ b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCTokenHandler.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Specialized; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Runtime; +using Gigya.Microdot.Hosting.Service; +using Gigya.Microdot.Interfaces.Logging; +using Gigya.Microdot.Interfaces.SystemWrappers; + +namespace Gigya.Microdot.Hosting.HttpService.Endpoints.GCEndpoint +{ + public interface IGCEndpointHandlerUtils + { + bool TryProcessAsTokenGenerationRequest(NameValueCollection queryString, IPAddress ipAddress, + out string additionalInfo); + bool ValidateToken(NameValueCollection queryString, out string additionalInfo); + bool ValidateGcType(NameValueCollection queryString, out string additionalInfo, out GCType gcType); + GCCollectionResult Collect(GCType gcType); + } + + public class GCEndpointHandlerUtils : IGCEndpointHandlerUtils + { + private readonly Func _microdotHostingConfigFactory; + private readonly ILog _logger; + private readonly IDateTime _dateTimeFactory; + private readonly IGCTokenContainer _gcTokenContainer; + private DateTime _lastCalled = DateTime.MinValue; + + public GCEndpointHandlerUtils(Func microdotHostingConfigFactory, + ILog logger, IDateTime dateTimeFactory, IGCTokenContainer gcTokenContainer) + { + _microdotHostingConfigFactory = microdotHostingConfigFactory; + _logger = logger; + _dateTimeFactory = dateTimeFactory; + _gcTokenContainer = gcTokenContainer; + } + + public bool TryProcessAsTokenGenerationRequest(NameValueCollection queryString, IPAddress ipAddress, + out string additionalInfo) + { + var isGetTokenRequest = queryString.AllKeys.Any(x=> x=="getToken"); + + if (isGetTokenRequest) + { + var config = _microdotHostingConfigFactory(); + var configGcGetTokenCooldown = config.GCGetTokenCooldown; + var now = _dateTimeFactory.UtcNow; + + if (false == AssertCoolDownTime(configGcGetTokenCooldown, now, out var gcEndpointCooldownWaitTimeLeft)) + { + additionalInfo = $"GC getToken cooldown in effect, will be ready in {gcEndpointCooldownWaitTimeLeft}"; + return true; + } + + var token = _gcTokenContainer.GenerateToken(); + + _logger.Warn(log=>log("GC getToken was called, see result in Token tag",unencryptedTags:new + { + Token = token, + IPAddress = ipAddress.ToString() + })); + + _lastCalled = now; + + additionalInfo = $"GC token generated"; + return true; + } + + additionalInfo = null; + return false; + } + + public bool ValidateToken(NameValueCollection queryString, out string additionalInfo) + { + var requestToken = queryString.Get("token")?.ToUpper(); + + if ( requestToken == null + || false == Guid.TryParse(requestToken, out var parsedToken) + || false == _gcTokenContainer.ValidateToken(parsedToken) + ) + { + additionalInfo = "Illegal request"; + return false; + } + + additionalInfo = null; + return true; + } + + public bool ValidateGcType(NameValueCollection queryString, out string additionalInfo, out GCType gcType) + { + var gcTypeQueryParam = queryString.Get("gcType"); + + if (false == Enum.TryParse(gcTypeQueryParam, out gcType)) + { + additionalInfo = "GCEndpoint called with unsupported GCType"; + return false; + } + + additionalInfo = null; + return true; + } + + public GCCollectionResult Collect(GCType gcType) + { + var sp = Stopwatch.StartNew(); + var totalMemoryBeforeGC = System.GC.GetTotalMemory(false); + + switch (gcType) + { + case GCType.Gen0: + System.GC.Collect(0, GCCollectionMode.Forced); + break; + case GCType.Gen1: + System.GC.Collect(1, GCCollectionMode.Forced); + break; + case GCType.Gen2: + System.GC.Collect(2, GCCollectionMode.Forced); + break; + case GCType.LOHCompaction: + GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; + System.GC.Collect(2, GCCollectionMode.Forced,false, true); + break; + case GCType.BlockingLohCompaction: + GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; + System.GC.Collect(2, GCCollectionMode.Forced,true, true); + break; + default: + throw new ArgumentException("GCType"); + } + + var totalMemoryAfterGc = System.GC.GetTotalMemory(false); + + return new GCCollectionResult( + totalMemoryBeforeGc: totalMemoryBeforeGC, + totalMemoryAfterGc: totalMemoryAfterGc, + elapsedMilliseconds: sp.ElapsedMilliseconds + ); + } + + private bool AssertCoolDownTime(TimeSpan? configGcEndpointCooldown, DateTime now, out TimeSpan gcEndpointCooldownWaitTimeLeft) + { + if (configGcEndpointCooldown != null + && configGcEndpointCooldown.HasValue) + { + gcEndpointCooldownWaitTimeLeft = + now - this._lastCalled - configGcEndpointCooldown.Value; + + if (gcEndpointCooldownWaitTimeLeft < TimeSpan.Zero) + { + gcEndpointCooldownWaitTimeLeft = gcEndpointCooldownWaitTimeLeft.Negate(); + return false; + } + else + { + gcEndpointCooldownWaitTimeLeft = TimeSpan.Zero; + } + } + else + { + gcEndpointCooldownWaitTimeLeft = TimeSpan.MaxValue; + } + + return true; + } + } +} \ No newline at end of file diff --git a/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCType.cs b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCType.cs new file mode 100644 index 00000000..080c2016 --- /dev/null +++ b/Gigya.Microdot.Hosting/HttpService/Endpoints/GCEndpoint/GCType.cs @@ -0,0 +1,11 @@ +namespace Gigya.Microdot.Hosting.HttpService.Endpoints.GCEndpoint +{ + public enum GCType + { + Gen0, + Gen1, + Gen2, + LOHCompaction, + BlockingLohCompaction + } +} \ No newline at end of file diff --git a/Gigya.Microdot.Hosting/HttpService/Endpoints/HealthEndpoint.cs b/Gigya.Microdot.Hosting/HttpService/Endpoints/HealthEndpoint.cs index 5797bd57..e48586d1 100644 --- a/Gigya.Microdot.Hosting/HttpService/Endpoints/HealthEndpoint.cs +++ b/Gigya.Microdot.Hosting/HttpService/Endpoints/HealthEndpoint.cs @@ -20,12 +20,12 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.SharedLogic; using System; using System.Linq; using System.Net; using System.Threading.Tasks; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.SharedLogic; namespace Gigya.Microdot.Hosting.HttpService.Endpoints { @@ -68,7 +68,8 @@ public async Task TryHandle(HttpListenerContext context, WriteResponseDele else { var healthStatusResult = await CheckServiceHealth().ConfigureAwait(false); - + if (healthStatusResult == null) + return false; var status = healthStatusResult.IsHealthy ? HttpStatusCode.OK : HttpStatusCode.InternalServerError; var json = healthStatusResult.Message; await writeResponse(json, status).ConfigureAwait(false); diff --git a/Gigya.Microdot.Hosting/HttpService/Endpoints/SchemaEndpoint.cs b/Gigya.Microdot.Hosting/HttpService/Endpoints/SchemaEndpoint.cs index 26959527..720c4b01 100644 --- a/Gigya.Microdot.Hosting/HttpService/Endpoints/SchemaEndpoint.cs +++ b/Gigya.Microdot.Hosting/HttpService/Endpoints/SchemaEndpoint.cs @@ -20,21 +20,37 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Net; -using System.Threading.Tasks; using Gigya.Common.Contracts.HttpService; +using Gigya.Microdot.SharedLogic.HttpService; using Newtonsoft.Json; +using System.Net; +using System.Threading.Tasks; namespace Gigya.Microdot.Hosting.HttpService.Endpoints { public class SchemaEndpoint : ICustomEndpoint { private readonly string _jsonSchema; + + public SchemaEndpoint(ServiceSchema schemaProvider, IServiceSchemaPostProcessor serviceSchemaPostProcessor) + { + _jsonSchema = GenerateJsonSchema(schemaProvider, serviceSchemaPostProcessor); + } - public SchemaEndpoint(ServiceSchema schemaProvider) + private string GenerateJsonSchema(ServiceSchema schemaProvider, + IServiceSchemaPostProcessor serviceSchemaPostProcessor) { - _jsonSchema = JsonConvert.SerializeObject(schemaProvider, new JsonSerializerSettings{Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore}); - } + serviceSchemaPostProcessor.PostProcessServiceSchema(schemaProvider); + + var jsonSchema = JsonConvert.SerializeObject(schemaProvider, + new JsonSerializerSettings + { + NullValueHandling = NullValueHandling.Ignore, + Formatting = Formatting.Indented, + DateParseHandling = DateParseHandling.None, + }); + return jsonSchema; + } public async Task TryHandle(HttpListenerContext context, WriteResponseDelegate writeResponse) { diff --git a/Gigya.Microdot.Hosting/HttpService/Endpoints/StatusEndpoints.cs b/Gigya.Microdot.Hosting/HttpService/Endpoints/StatusEndpoints.cs new file mode 100644 index 00000000..33939d70 --- /dev/null +++ b/Gigya.Microdot.Hosting/HttpService/Endpoints/StatusEndpoints.cs @@ -0,0 +1,50 @@ +using System; +using System.Net; +using System.Threading.Tasks; +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.Hosting.Service; +using Gigya.Microdot.Interfaces.Logging; + +namespace Gigya.Microdot.Hosting.HttpService.Endpoints +{ + public class StatusEndpoints: ICustomEndpoint + { + private readonly Func _microdotHostingConfigFactory; + private readonly ILog _logger; + + public StatusEndpoints(Func microdotHostingConfigFactory, ILog logger) + { + _microdotHostingConfigFactory = microdotHostingConfigFactory; + _logger = logger; + } + + public async Task TryHandle(HttpListenerContext context, WriteResponseDelegate writeResponse) + { + var microdotHostingConfig = _microdotHostingConfigFactory(); + + foreach (var statusEndpoint in microdotHostingConfig.StatusEndpoints) + { + if (context.Request.Url.AbsolutePath.Equals(statusEndpoint, StringComparison.InvariantCultureIgnoreCase)) + { + if (microdotHostingConfig.ShouldLogStatusEndpoint) + { + _logger.Info(log => + { + log("Status", unencryptedTags: new Tags + { + { "RemoteIP", context?.Request?.RemoteEndPoint?.Address?.ToString() ?? "0" }, + { "RemotePort", context?.Request?.RemoteEndPoint?.Port.ToString() }, + { "StatusEndpoint", statusEndpoint } + }); + }); + } + + await writeResponse(string.Empty).ConfigureAwait(false); + return true; + } + } + + return false; + } + } +} \ No newline at end of file diff --git a/Gigya.Microdot.Hosting/HttpService/HttpServiceListener.cs b/Gigya.Microdot.Hosting/HttpService/HttpServiceListener.cs index 294545fe..df83e2be 100644 --- a/Gigya.Microdot.Hosting/HttpService/HttpServiceListener.cs +++ b/Gigya.Microdot.Hosting/HttpService/HttpServiceListener.cs @@ -20,17 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Net; -using System.Reflection; -using System.Text; -using System.Threading; -using System.Threading.Tasks; using Gigya.Common.Contracts; using Gigya.Common.Contracts.Exceptions; using Gigya.Common.Contracts.HttpService; @@ -51,6 +40,16 @@ using Gigya.ServiceContract.Exceptions; using Metrics; using Newtonsoft.Json; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; using Timer = Metrics.Timer; @@ -539,7 +538,17 @@ private void ValidateRequest(HttpListenerContext context) { context.Response.Headers.Add("Allow", "POST"); _failureCounter.Increment("NonPostRequest"); - throw new RequestException("Only POST calls are allowed."); + throw new RequestException( + "Only POST calls are allowed.", + unencrypted: new Tags + { + { "RemoteIP", context?.Request?.RemoteEndPoint?.Address?.ToString() ?? "0" }, + { "RemotePort", context?.Request?.RemoteEndPoint?.Port.ToString() } + }, + encrypted:new Tags() + { + { "requestedUrl", context?.Request?.Url?.ToString() } + }); } if (context.Request.ContentType == null || context.Request.ContentType.StartsWith("application/json") == false) diff --git a/Gigya.Microdot.Hosting/HttpService/IServiceEndPointDefinition.cs b/Gigya.Microdot.Hosting/HttpService/IServiceEndPointDefinition.cs index 23e37d3d..0d1c1e7e 100644 --- a/Gigya.Microdot.Hosting/HttpService/IServiceEndPointDefinition.cs +++ b/Gigya.Microdot.Hosting/HttpService/IServiceEndPointDefinition.cs @@ -20,16 +20,16 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.SharedLogic.HttpService; +using System; +using System.Collections.Generic; namespace Gigya.Microdot.Hosting.HttpService { - /// - /// Contains the metadata for establishing the service endpoing and resolving calls handled by a service. - /// + /// + /// Contains the metadata for establishing the service endpoing and resolving calls handled by a service. + /// public interface IServiceEndPointDefinition { /// diff --git a/Gigya.Microdot.Hosting/HttpService/IServiceInterfacesMapper.cs b/Gigya.Microdot.Hosting/HttpService/IServiceInterfacesMapper.cs index 0415eed1..812cfec9 100644 --- a/Gigya.Microdot.Hosting/HttpService/IServiceInterfacesMapper.cs +++ b/Gigya.Microdot.Hosting/HttpService/IServiceInterfacesMapper.cs @@ -25,10 +25,10 @@ namespace Gigya.Microdot.Hosting.HttpService { - /// - /// Mapping between service interfaces to grain interfaces. Used in Orleans for additional type information (for creating grain references). - /// The map is an identity map outside orleans. - /// + /// + /// Mapping between service interfaces to grain interfaces. Used in Orleans for additional type information (for creating grain references). + /// The map is an identity map outside orleans. + /// public interface IServiceInterfaceMapper { /// diff --git a/Gigya.Microdot.Hosting/HttpService/IWarmup.cs b/Gigya.Microdot.Hosting/HttpService/IWarmup.cs index 08b6ba93..78135131 100644 --- a/Gigya.Microdot.Hosting/HttpService/IWarmup.cs +++ b/Gigya.Microdot.Hosting/HttpService/IWarmup.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Threading.Tasks; namespace Gigya.Microdot.Hosting.HttpService { diff --git a/Gigya.Microdot.Hosting/HttpService/IdentityServiceInterfaceMapper.cs b/Gigya.Microdot.Hosting/HttpService/IdentityServiceInterfaceMapper.cs index a18f0e60..88b70248 100644 --- a/Gigya.Microdot.Hosting/HttpService/IdentityServiceInterfaceMapper.cs +++ b/Gigya.Microdot.Hosting/HttpService/IdentityServiceInterfaceMapper.cs @@ -20,15 +20,15 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.HttpService; using System; using System.Linq; using System.Reflection; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Common.Contracts.HttpService; namespace Gigya.Microdot.Hosting.HttpService { - public class IdentityServiceInterfaceMapper : ServiceInterfaceMapper + public class IdentityServiceInterfaceMapper : ServiceInterfaceMapper { public IdentityServiceInterfaceMapper(Type serviceInterfaceType) : this(new[] { serviceInterfaceType }) { } diff --git a/Gigya.Microdot.Hosting/HttpService/ServerRequestPublisher.cs b/Gigya.Microdot.Hosting/HttpService/ServerRequestPublisher.cs index 73a4d2f5..9dbaa6d9 100644 --- a/Gigya.Microdot.Hosting/HttpService/ServerRequestPublisher.cs +++ b/Gigya.Microdot.Hosting/HttpService/ServerRequestPublisher.cs @@ -1,9 +1,9 @@ -using System; -using System.Collections.Generic; -using Gigya.Microdot.Hosting.Events; +using Gigya.Microdot.Hosting.Events; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.SharedLogic.Events; +using System; +using System.Collections.Generic; namespace Gigya.Microdot.Hosting.HttpService { diff --git a/Gigya.Microdot.Hosting/HttpService/ServiceEndPointDefinition.cs b/Gigya.Microdot.Hosting/HttpService/ServiceEndPointDefinition.cs index d845d0a5..9b418d74 100644 --- a/Gigya.Microdot.Hosting/HttpService/ServiceEndPointDefinition.cs +++ b/Gigya.Microdot.Hosting/HttpService/ServiceEndPointDefinition.cs @@ -20,11 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; using Gigya.Common.Contracts.Exceptions; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.Interfaces; @@ -32,6 +27,11 @@ using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.Exceptions; using Gigya.Microdot.SharedLogic.HttpService; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; namespace Gigya.Microdot.Hosting.HttpService { diff --git a/Gigya.Microdot.Hosting/HttpService/ServiceInterfaceMapper.cs b/Gigya.Microdot.Hosting/HttpService/ServiceInterfaceMapper.cs index c6cae0f5..5ecb7302 100644 --- a/Gigya.Microdot.Hosting/HttpService/ServiceInterfaceMapper.cs +++ b/Gigya.Microdot.Hosting/HttpService/ServiceInterfaceMapper.cs @@ -20,11 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.Hosting.HttpService.Endpoints; using System; using System.Collections.Generic; using System.Linq; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.Hosting.HttpService.Endpoints; namespace Gigya.Microdot.Hosting.HttpService { diff --git a/Gigya.Microdot.Hosting/HttpService/ServiceMethod.cs b/Gigya.Microdot.Hosting/HttpService/ServiceMethod.cs index a1b86730..e80cd41e 100644 --- a/Gigya.Microdot.Hosting/HttpService/ServiceMethod.cs +++ b/Gigya.Microdot.Hosting/HttpService/ServiceMethod.cs @@ -20,16 +20,16 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.HttpService; using System; using System.Reflection; using System.Threading.Tasks; -using Gigya.Common.Contracts.HttpService; namespace Gigya.Microdot.Hosting.HttpService { - /// - /// A representation of a service method which contains the method to be invoked, and in Orleans, the grain interface type too. - /// + /// + /// A representation of a service method which contains the method to be invoked, and in Orleans, the grain interface type too. + /// public class ServiceMethod { /// The type of the grain interface, used in Orleans to create a grain reference (not used elsewhere) diff --git a/Gigya.Microdot.Hosting/HttpService/ServiceMethodResolver.cs b/Gigya.Microdot.Hosting/HttpService/ServiceMethodResolver.cs index 5ee6b13a..15480a9f 100644 --- a/Gigya.Microdot.Hosting/HttpService/ServiceMethodResolver.cs +++ b/Gigya.Microdot.Hosting/HttpService/ServiceMethodResolver.cs @@ -20,17 +20,17 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.SharedLogic.HttpService; using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Reflection; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.SharedLogic.HttpService; namespace Gigya.Microdot.Hosting.HttpService { - internal class ServiceMethodResolver + internal class ServiceMethodResolver { private Dictionary MethodCache { get; } diff --git a/Gigya.Microdot.Hosting/Metrics/MetricsConfiguration.cs b/Gigya.Microdot.Hosting/Metrics/MetricsConfiguration.cs index 23dc2e3c..8a4e5a7c 100644 --- a/Gigya.Microdot.Hosting/Metrics/MetricsConfiguration.cs +++ b/Gigya.Microdot.Hosting/Metrics/MetricsConfiguration.cs @@ -1,5 +1,5 @@ -using System; -using Gigya.Microdot.Interfaces.Configuration; +using Gigya.Microdot.Interfaces.Configuration; +using System; namespace Gigya.Microdot.Hosting.Metrics { diff --git a/Gigya.Microdot.Hosting/Metrics/MetricsInitializer.cs b/Gigya.Microdot.Hosting/Metrics/MetricsInitializer.cs index 08348280..cf475c69 100644 --- a/Gigya.Microdot.Hosting/Metrics/MetricsInitializer.cs +++ b/Gigya.Microdot.Hosting/Metrics/MetricsInitializer.cs @@ -1,13 +1,13 @@ -using System; -using System.Net; -using System.Threading.Tasks; -using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.Monitor; using Metrics; using Metrics.Logging; +using System; +using System.Net; +using System.Threading.Tasks; using ILog = Gigya.Microdot.Interfaces.Logging.ILog; namespace Gigya.Microdot.Hosting.Metrics diff --git a/Gigya.Microdot.Hosting/Properties/AssemblyInfo.cs b/Gigya.Microdot.Hosting/Properties/AssemblyInfo.cs index 261a4ceb..e0d5c3ec 100644 --- a/Gigya.Microdot.Hosting/Properties/AssemblyInfo.cs +++ b/Gigya.Microdot.Hosting/Properties/AssemblyInfo.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/Gigya.Microdot.Hosting/Service/ServiceHostBase.cs b/Gigya.Microdot.Hosting/Service/ServiceHostBase.cs index 95149e7f..1b80b1fc 100644 --- a/Gigya.Microdot.Hosting/Service/ServiceHostBase.cs +++ b/Gigya.Microdot.Hosting/Service/ServiceHostBase.cs @@ -1,59 +1,73 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Diagnostics; -using System.Linq; -using System.ServiceProcess; +#region Copyright +// Copyright 2017 Gigya Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; using System.Text; -using System.Threading; -using System.Threading.Tasks; +using System.Threading; +using System.Threading.Tasks; using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.Configuration; -using Gigya.Microdot.Hosting.HttpService; +using Gigya.Microdot.Configuration; using Gigya.Microdot.Interfaces.Configuration; -using Gigya.Microdot.Interfaces.SystemWrappers; -using Gigya.Microdot.SharedLogic; -using Gigya.Microdot.SharedLogic.SystemWrappers; +using Gigya.Microdot.SharedLogic; + -namespace Gigya.Microdot.Hosting.Service +namespace Gigya.Microdot.Hosting.Service { [ConfigurationRoot("Microdot.Hosting", RootStrategy.ReplaceClassNameWithPath)] public class MicrodotHostingConfig : IConfigObject { public bool FailServiceStartOnConfigError = true; public bool ExtendedDelaysTimeLogging = true; + public List StatusEndpoints = new List(); + public bool ShouldLogStatusEndpoint = false; + public bool GCEndpointEnabled = false; + public TimeSpan? GCGetTokenCooldown = TimeSpan.FromHours(1); } + [ConfigurationRoot("Microdot.Hosting.ThreadPool", RootStrategy.ReplaceClassNameWithPath)] + public class MicrodotHostingThreadPoolConfig : IConfigObject + { + public bool MinThreadOverrideEnabled = true; + public bool MaxThreadOverrideEnabled = false; + public int MinWorkerThreads = 64; + public int MinCompletionPortThreads = 64; + public int MaxWorkerThreads = 32767; + public int MaxCompletionPortThreads = 1000; + } + + + public abstract class ServiceHostBase : IDisposable { - private bool disposed; - private object syncRoot = new object(); + private bool _disposed; + private readonly object _syncRoot = new object(); public abstract string ServiceName { get; } public ServiceArguments Arguments { get; private set; } - private DelegatingServiceBase WindowsService { get; set; } private ManualResetEvent StopEvent { get; } protected TaskCompletionSource ServiceStartedEvent { get; set; } private TaskCompletionSource ServiceGracefullyStopped { get; set; } @@ -61,10 +75,8 @@ public abstract class ServiceHostBase : IDisposable protected ICrashHandler CrashHandler { get; set; } public virtual Version InfraVersion { get; } - - private IRequestListener requestListener; - - public bool? FailServiceStartOnConfigError { get; set; } = null; + + public bool? FailServiceStartOnConfigError { get; set; } public ServiceHostBase() { @@ -108,17 +120,7 @@ public void Run(ServiceArguments argumentsOverride = null) return; } - if (Arguments.ServiceStartupMode == ServiceStartupMode.WindowsService) - { - Trace.WriteLine("Service starting as a Windows service..."); - WindowsService = new DelegatingServiceBase(ServiceName, OnWindowsServiceStart, OnWindowsServiceStop); - - if (argumentsOverride == null) - Arguments = null; // Ensures OnWindowsServiceStart reloads parameters passed from Windows Service Manager. - - ServiceBase.Run(WindowsService); // This calls OnWindowsServiceStart() on a different thread and blocks until the service stops. - } - else if (Arguments.ServiceStartupMode == ServiceStartupMode.VerifyConfigurations) + if (Arguments.ServiceStartupMode == ServiceStartupMode.VerifyConfigurations) { OnVerifyConfiguration(); } @@ -285,7 +287,6 @@ protected void VerifyConfiguration(ConfigurationVerificator ConfigurationVerific } } - protected void VerifyConfigurationsIfNeeded( MicrodotHostingConfig hostingConfig, ConfigurationVerificator configurationVerificator) { @@ -294,11 +295,10 @@ protected void VerifyConfigurationsIfNeeded( var badConfigs = configurationVerificator.Verify().Where(c => !c.Success).ToList(); if (badConfigs.Any()) throw new EnvironmentException("Bad configuration(s) detected. Stopping service startup. You can disable this behavior through the Microdot.Hosting.FailServiceStartOnConfigError configuration. Errors:\n" - + badConfigs.Aggregate(new StringBuilder(), (sb, bc) => sb.Append(bc).Append("\n"))); + + badConfigs.Aggregate(new StringBuilder(), (sb, bc) => sb.Append(bc).Append('\n'))); } } - /// /// Waits for the service to finish starting. Mainly used from tests. /// @@ -330,73 +330,35 @@ protected void OnCrash() Dispose(); } - - private void OnWindowsServiceStart(string[] args) + protected void SetThreadPoolConfigurations(MicrodotHostingThreadPoolConfig config) { - if (Arguments == null) + if (config != null) { - Arguments = new ServiceArguments(args); - } - - try - { - if (Arguments.ServiceStartupMode != ServiceStartupMode.WindowsService) - throw new InvalidOperationException($"Cannot start in {Arguments.ServiceStartupMode} mode when starting as a Windows service."); - - if (System.Environment.UserInteractive == false) + if (config.MinThreadOverrideEnabled == true) { - throw new InvalidOperationException( - "This Windows service requires to be run with 'user interactive' enabled to correctly read certificates. " + - "Either the service wasn't configure with the 'Allow service to interact with desktop' option enabled " + - "or the OS is ignoring the checkbox due to a registry settings. " + - "Make sure both the checkbox is checked and following registry key is set to DWORD '0':\n" + - @"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\NoInteractiveServices"); + ThreadPool.SetMinThreads(config.MinWorkerThreads, config.MinCompletionPortThreads); + } + if (config.MaxThreadOverrideEnabled == true) + { + ThreadPool.SetMaxThreads(config.MaxWorkerThreads, config.MaxCompletionPortThreads); } - - WindowsService.RequestAdditionalTime(60000); - - OnStart(); - } - catch - { - WindowsService.ExitCode = 1064; // "An exception occurred in the service when handling the control request." (net helpmsg 1064) - throw; - } - } - - - private void OnWindowsServiceStop() - { - WindowsService.RequestAdditionalTime(60000); - - try - { - OnStop(); - } - catch - { - WindowsService.ExitCode = 1064; // "An exception occurred in the service when handling the control request." (net helpmsg 1064) - throw; } - } - protected virtual void Dispose(bool disposing) { SafeDispose(StopEvent); - SafeDispose(WindowsService); SafeDispose(MonitoredShutdownProcess); } public void Dispose() { - lock (this.syncRoot) + lock (this._syncRoot) { try { - if (this.disposed) + if (this._disposed) return; Dispose(false); @@ -404,7 +366,7 @@ public void Dispose() finally { - this.disposed = true; + this._disposed = true; } } } @@ -421,34 +383,8 @@ protected void SafeDispose(IDisposable disposable) } } - - private class DelegatingServiceBase : ServiceBase - { - private readonly Action _onStart; - private readonly Action _onStop; - - - public DelegatingServiceBase(string serviceName, Action onStart, Action onStop) - { - ServiceName = serviceName; // Required for auto-logging to event viewer of start/stop event and exceptions. - _onStart = onStart; - _onStop = onStop; - } - - - protected override void OnStart(string[] args) - { - _onStart(args); - } - - - protected override void OnStop() - { - _onStop(); - } - } } - public enum StopResult { None, Graceful, Force} - -} + public enum StopResult { None, Graceful, Force} + +} diff --git a/Gigya.Microdot.Hosting/Service/ServiceWarmup.cs b/Gigya.Microdot.Hosting/Service/ServiceWarmup.cs index cbd6c673..7c13ddbf 100644 --- a/Gigya.Microdot.Hosting/Service/ServiceWarmup.cs +++ b/Gigya.Microdot.Hosting/Service/ServiceWarmup.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Threading.Tasks; using Gigya.Microdot.Hosting.HttpService; namespace Gigya.Microdot.Hosting.Service diff --git a/Gigya.Microdot.Hosting/Validators/ConfigObjectTypeValidator.cs b/Gigya.Microdot.Hosting/Validators/ConfigObjectTypeValidator.cs index ff9b0526..27287c6d 100644 --- a/Gigya.Microdot.Hosting/Validators/ConfigObjectTypeValidator.cs +++ b/Gigya.Microdot.Hosting/Validators/ConfigObjectTypeValidator.cs @@ -20,14 +20,13 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.Interfaces; +using Gigya.Microdot.Interfaces.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.Configuration.Objects; -using Gigya.Microdot.Interfaces; -using Gigya.Microdot.Interfaces.Configuration; namespace Gigya.Microdot.Hosting.Validators { diff --git a/Gigya.Microdot.Hosting/Validators/LogFieldAttributeValidator.cs b/Gigya.Microdot.Hosting/Validators/LogFieldAttributeValidator.cs index a625387f..6c7393ea 100644 --- a/Gigya.Microdot.Hosting/Validators/LogFieldAttributeValidator.cs +++ b/Gigya.Microdot.Hosting/Validators/LogFieldAttributeValidator.cs @@ -20,13 +20,13 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Linq; -using System.Reflection; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Hosting.HttpService; using Gigya.ServiceContract.Attributes; using Newtonsoft.Json.Linq; +using System; +using System.Linq; +using System.Reflection; namespace Gigya.Microdot.Hosting.Validators { diff --git a/Gigya.Microdot.Hosting/Validators/SensitivityAttributesValidator.cs b/Gigya.Microdot.Hosting/Validators/SensitivityAttributesValidator.cs index f6ecc536..d1198314 100644 --- a/Gigya.Microdot.Hosting/Validators/SensitivityAttributesValidator.cs +++ b/Gigya.Microdot.Hosting/Validators/SensitivityAttributesValidator.cs @@ -20,13 +20,13 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.Hosting.HttpService; +using Gigya.ServiceContract.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.Hosting.HttpService; -using Gigya.ServiceContract.Attributes; namespace Gigya.Microdot.Hosting.Validators { diff --git a/Gigya.Microdot.Hosting/app.config b/Gigya.Microdot.Hosting/app.config deleted file mode 100644 index 4e15c3f7..00000000 --- a/Gigya.Microdot.Hosting/app.config +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/Gigya.Microdot.Hosting/paket.references b/Gigya.Microdot.Hosting/paket.references deleted file mode 100644 index 87720d28..00000000 --- a/Gigya.Microdot.Hosting/paket.references +++ /dev/null @@ -1,9 +0,0 @@ -Gigya.ServiceContract -Newtonsoft.Json -System.Threading.Tasks.Dataflow -System.Collections.Immutable -System.ValueTuple -Microsoft.Orleans.Core.Abstractions -System.ComponentModel.Annotations -System.Net.Http -System.ServiceProcess.ServiceController diff --git a/Gigya.Microdot.Hosting/paket.template b/Gigya.Microdot.Hosting/paket.template deleted file mode 100644 index 98e351cb..00000000 --- a/Gigya.Microdot.Hosting/paket.template +++ /dev/null @@ -1,11 +0,0 @@ -type - project -description - Infrastructure used for hosting Microdot services, part of the Microdot - framework. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices \ No newline at end of file diff --git a/Gigya.Microdot.Interfaces/CurrentApplicationInfo.cs b/Gigya.Microdot.Interfaces/CurrentApplicationInfo.cs index caf1c976..c68b2e43 100644 --- a/Gigya.Microdot.Interfaces/CurrentApplicationInfo.cs +++ b/Gigya.Microdot.Interfaces/CurrentApplicationInfo.cs @@ -1,8 +1,7 @@ -using System; -using System.Collections.Generic; +using Gigya.Microdot.LanguageExtensions; +using System; using System.Reflection; -using System.Text; -using Gigya.Microdot.LanguageExtensions; +using System.Runtime.InteropServices; namespace Gigya.Microdot.SharedLogic { @@ -26,15 +25,14 @@ public class CurrentApplicationInfo /// The Infrastructure version. public Version InfraVersion { get; } + /// Is this Linux + public static bool IsLinux = false; + /// /// Name of host, the current process is running on. /// public static string HostName { get; private set; } - - /// - /// Indicates if the current process is running as a Windows service. - /// - public bool IsRunningAsWindowsService { get; } + public static string ContainerName { get; private set; } = null; /// /// Indicates whether current process has an interactive console window. @@ -47,14 +45,16 @@ public class CurrentApplicationInfo internal string InstanceName { get; } public CurrentApplicationInfo(string name, string instanceName = null, Version infraVersion = null) - : this(name, Environment.UserName, System.Net.Dns.GetHostName(), instanceName, infraVersion) + : this(name, Environment.UserName, System.Net.Dns.GetHostName(), instanceName, infraVersion, containerName: null) { } public CurrentApplicationInfo( string name, string osUser, string hostName, - string instanceName = null, Version infraVersion = null) + string instanceName = null, + Version infraVersion = null, + string containerName = null) { Name = name ?? throw new ArgumentNullException(nameof(name)); OsUser = osUser.NullWhenEmpty() ?? throw new ArgumentNullException(nameof(osUser)); @@ -62,18 +62,15 @@ public CurrentApplicationInfo( Version = (Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()).GetName().Version; - // ReSharper disable once PossibleNullReferenceException - // TODO: Test whether this code is still correct or remove outright - IsRunningAsWindowsService = Environment.OSVersion.Platform == PlatformID.Win32NT && - OsUser == @"NT AUTHORITY\SYSTEM"; - // TODO: Consider using Environment.UserInteractive - HasConsoleWindow = !IsRunningAsWindowsService && !Console.IsInputRedirected; + HasConsoleWindow = !Console.IsInputRedirected; // TODO: Possible error: Microdot version assigned to Infra version InfraVersion = infraVersion ?? typeof(CurrentApplicationInfo).Assembly.GetName().Version; InstanceName = instanceName; + ContainerName = string.IsNullOrEmpty(containerName) ? null : containerName; + IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux); } } } diff --git a/Gigya.Microdot.Interfaces/Events/EventConfiguration.cs b/Gigya.Microdot.Interfaces/Events/EventConfiguration.cs index 3aa9eda4..48e60447 100644 --- a/Gigya.Microdot.Interfaces/Events/EventConfiguration.cs +++ b/Gigya.Microdot.Interfaces/Events/EventConfiguration.cs @@ -1,5 +1,5 @@ -using System.Text.RegularExpressions; -using Gigya.Microdot.Interfaces.Configuration; +using Gigya.Microdot.Interfaces.Configuration; +using System.Text.RegularExpressions; namespace Gigya.Microdot.Interfaces.Events { diff --git a/Gigya.Microdot.Interfaces/Events/EventFieldAttribute.cs b/Gigya.Microdot.Interfaces/Events/EventFieldAttribute.cs index 9ba749a4..f2de068e 100644 --- a/Gigya.Microdot.Interfaces/Events/EventFieldAttribute.cs +++ b/Gigya.Microdot.Interfaces/Events/EventFieldAttribute.cs @@ -23,7 +23,7 @@ using System; namespace Gigya.Microdot.Interfaces.Events -{ +{ /// Indicates this field should be written, and what name to use for the field name. [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public class EventFieldAttribute : Attribute diff --git a/Gigya.Microdot.Interfaces/Events/IEvent.cs b/Gigya.Microdot.Interfaces/Events/IEvent.cs index 0c69fd1c..f69ebc6f 100644 --- a/Gigya.Microdot.Interfaces/Events/IEvent.cs +++ b/Gigya.Microdot.Interfaces/Events/IEvent.cs @@ -20,10 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; +using System; namespace Gigya.Microdot.Interfaces.Events { diff --git a/Gigya.Microdot.Interfaces/Gigya.Microdot.Interfaces.csproj b/Gigya.Microdot.Interfaces/Gigya.Microdot.Interfaces.csproj index 304eeb66..ae76d5e0 100644 --- a/Gigya.Microdot.Interfaces/Gigya.Microdot.Interfaces.csproj +++ b/Gigya.Microdot.Interfaces/Gigya.Microdot.Interfaces.csproj @@ -1,12 +1,17 @@  - - netstandard2.0 - Gigya.Microdot.Interfaces - $(SolutionDir)main.ruleset - - - - - + + Gigya.Microdot.Interfaces + + Interface abstractions used by various Microdot components, seperated from + their implementations to allow easy unit testing with mocks (see + Gigya.Microdot.Fakes). Part of the Microdot Framework. + + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.Interfaces/IApplicationDirectoryProvider.cs b/Gigya.Microdot.Interfaces/IApplicationDirectoryProvider.cs index 8ce8f030..e2785939 100644 --- a/Gigya.Microdot.Interfaces/IApplicationDirectoryProvider.cs +++ b/Gigya.Microdot.Interfaces/IApplicationDirectoryProvider.cs @@ -21,7 +21,7 @@ #endregion namespace Gigya.Microdot.Interfaces { - public interface IApplicationDirectoryProvider + public interface IApplicationDirectoryProvider { string GetApplicationDirectory(); } diff --git a/Gigya.Microdot.Interfaces/IAssemblyProvider.cs b/Gigya.Microdot.Interfaces/IAssemblyProvider.cs index ec0612b6..6cbd1fea 100644 --- a/Gigya.Microdot.Interfaces/IAssemblyProvider.cs +++ b/Gigya.Microdot.Interfaces/IAssemblyProvider.cs @@ -25,10 +25,10 @@ namespace Gigya.Microdot.Interfaces { - /// - /// Provides a list of assemblies that should be used for discovery via reflection. - /// - public interface IAssemblyProvider + /// + /// Provides a list of assemblies that should be used for discovery via reflection. + /// + public interface IAssemblyProvider { /// /// GetObject a list of assemblies hat should be used for discovery via reflection. diff --git a/Gigya.Microdot.Interfaces/Logging/IStackTraceEnhancer.cs b/Gigya.Microdot.Interfaces/Logging/IStackTraceEnhancer.cs index 20cd114e..5038b874 100644 --- a/Gigya.Microdot.Interfaces/Logging/IStackTraceEnhancer.cs +++ b/Gigya.Microdot.Interfaces/Logging/IStackTraceEnhancer.cs @@ -1,5 +1,5 @@ -using System; -using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Linq; +using System; namespace Gigya.Microdot.Interfaces.Logging { diff --git a/Gigya.Microdot.Interfaces/SystemWrappers/IEnvironment.cs b/Gigya.Microdot.Interfaces/SystemWrappers/IEnvironment.cs index 40987e0a..b92c603f 100644 --- a/Gigya.Microdot.Interfaces/SystemWrappers/IEnvironment.cs +++ b/Gigya.Microdot.Interfaces/SystemWrappers/IEnvironment.cs @@ -21,7 +21,6 @@ #endregion using Gigya.Microdot.SharedLogic; -using System; using System.IO; namespace Gigya.Microdot.Interfaces.SystemWrappers @@ -50,6 +49,10 @@ public interface IEnvironment // TODO: Abstract away string ConsulAddress { get; } + string HostIPAddress { get; } + + string ContainerName { get; } + /// /// Logical instance name for the current application, which can be used to differentiate between /// multiple identical applications running on the same host. diff --git a/Gigya.Microdot.Interfaces/paket.references b/Gigya.Microdot.Interfaces/paket.references deleted file mode 100644 index 1063d003..00000000 --- a/Gigya.Microdot.Interfaces/paket.references +++ /dev/null @@ -1 +0,0 @@ -Newtonsoft.Json \ No newline at end of file diff --git a/Gigya.Microdot.Interfaces/paket.template b/Gigya.Microdot.Interfaces/paket.template deleted file mode 100644 index f249f59a..00000000 --- a/Gigya.Microdot.Interfaces/paket.template +++ /dev/null @@ -1,12 +0,0 @@ -type - project -description - Interface abstractions used by various Microdot components, seperated from - their implementations to allow easy unit testing with mocks (see - Gigya.Microdot.Fakes). Part of the Microdot Framework. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices \ No newline at end of file diff --git a/Gigya.Microdot.LanguageExtensions/Gigya.Microdot.LanguageExtensions.csproj b/Gigya.Microdot.LanguageExtensions/Gigya.Microdot.LanguageExtensions.csproj index ded7e0d4..41be3306 100644 --- a/Gigya.Microdot.LanguageExtensions/Gigya.Microdot.LanguageExtensions.csproj +++ b/Gigya.Microdot.LanguageExtensions/Gigya.Microdot.LanguageExtensions.csproj @@ -1,9 +1,6 @@ - - - - netstandard2.0 - Gigya.Microdot.LanguageExtensions - $(SolutionDir)main.ruleset - - + + + Gigya.Microdot.LanguageExtensions + Language and system library extensions for Microdot + diff --git a/Gigya.Microdot.LanguageExtensions/MiscExtensions.cs b/Gigya.Microdot.LanguageExtensions/MiscExtensions.cs index ba20d74e..281c2247 100644 --- a/Gigya.Microdot.LanguageExtensions/MiscExtensions.cs +++ b/Gigya.Microdot.LanguageExtensions/MiscExtensions.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace Gigya.Microdot.LanguageExtensions { diff --git a/Gigya.Microdot.LanguageExtensions/StringExtensions.cs b/Gigya.Microdot.LanguageExtensions/StringExtensions.cs index d41894dc..021b58af 100644 --- a/Gigya.Microdot.LanguageExtensions/StringExtensions.cs +++ b/Gigya.Microdot.LanguageExtensions/StringExtensions.cs @@ -12,11 +12,9 @@ public static class StringExtensions /// public static bool IsSubPathOf(this string path, string baseDirPath) { - string normalizedPath = Path.GetFullPath(path.Replace('/', '\\') - .WithEnding("\\")); + string normalizedPath = Path.GetFullPath(path.Replace('/', '\\').WithEnding("\\")); - string normalizedBaseDirPath = Path.GetFullPath(baseDirPath.Replace('/', '\\') - .WithEnding("\\")); + string normalizedBaseDirPath = Path.GetFullPath(baseDirPath.Replace('/', '\\').WithEnding("\\")); return normalizedPath.StartsWith(normalizedBaseDirPath, StringComparison.OrdinalIgnoreCase); } @@ -66,10 +64,25 @@ public static string Right(this string value, int length) public static string NullWhenEmpty(this string self) { - return - string.IsNullOrEmpty(self) == false - ? self - : null; + return string.IsNullOrEmpty(self) == false ? self : null; + } + + //In .net >= core, GetHashCode() returns a different result on every application run (it uses randomization to avoid hash flooding) + //In cases in which you need a deterministic hash code, you can use the following method + public static int GetDeterministicHashCode(this string str) + { + if (str == null) + throw new ArgumentNullException(nameof(str)); + + unchecked + { + int hash = 23; + + foreach (char c in str) + hash = (hash << 5) - hash + c; // same as "hash = hash * 31 + c", but faster. + + return hash; + } } } } diff --git a/Gigya.Microdot.LanguageExtensions/paket.template b/Gigya.Microdot.LanguageExtensions/paket.template deleted file mode 100644 index d77748fc..00000000 --- a/Gigya.Microdot.LanguageExtensions/paket.template +++ /dev/null @@ -1,10 +0,0 @@ -type - project -description - Language and system library extensions for Microdot -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices \ No newline at end of file diff --git a/Gigya.Microdot.Logging.NLog/Gigya.Microdot.Logging.NLog.csproj b/Gigya.Microdot.Logging.NLog/Gigya.Microdot.Logging.NLog.csproj index eee97683..960f6ac5 100644 --- a/Gigya.Microdot.Logging.NLog/Gigya.Microdot.Logging.NLog.csproj +++ b/Gigya.Microdot.Logging.NLog/Gigya.Microdot.Logging.NLog.csproj @@ -1,14 +1,18 @@  - - netstandard2.0 - Gigya.Microdot.Logging.NLog - $(SolutionDir)main.ruleset - - - - - - - + + Gigya.Microdot.Logging.NLog + An implementation of Microdot's logging and tracing using NLog. + gigya microdot microservice microservices NLog logging tracing + + + + + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.Logging.NLog/LogEventPublisher.cs b/Gigya.Microdot.Logging.NLog/LogEventPublisher.cs index be16435f..9151a121 100644 --- a/Gigya.Microdot.Logging.NLog/LogEventPublisher.cs +++ b/Gigya.Microdot.Logging.NLog/LogEventPublisher.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; +using Gigya.Microdot.Interfaces.Events; +using Gigya.Microdot.Interfaces.Logging; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Gigya.Microdot.Interfaces.Events; -using Gigya.Microdot.Interfaces.Logging; namespace Gigya.Microdot.Logging.NLog { diff --git a/Gigya.Microdot.Logging.NLog/NLogLogger.cs b/Gigya.Microdot.Logging.NLog/NLogLogger.cs index f578fb93..f2f98fbf 100644 --- a/Gigya.Microdot.Logging.NLog/NLogLogger.cs +++ b/Gigya.Microdot.Logging.NLog/NLogLogger.cs @@ -1,12 +1,12 @@ -using System; +using Gigya.Microdot.SharedLogic.Events; +using Gigya.Microdot.SharedLogic.Logging; +using NLog; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading.Tasks; -using Gigya.Microdot.SharedLogic.Events; -using Gigya.Microdot.SharedLogic.Logging; -using NLog; namespace Gigya.Microdot.Logging.NLog { diff --git a/Gigya.Microdot.Logging.NLog/NLogModule.cs b/Gigya.Microdot.Logging.NLog/NLogModule.cs index 149c9073..ca5bc2c6 100644 --- a/Gigya.Microdot.Logging.NLog/NLogModule.cs +++ b/Gigya.Microdot.Logging.NLog/NLogModule.cs @@ -1,4 +1,3 @@ -using System; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Ninject; @@ -7,6 +6,7 @@ using Ninject.Modules; using Ninject.Parameters; using Ninject.Syntax; +using System; namespace Gigya.Microdot.Logging.NLog { diff --git a/Gigya.Microdot.Logging.NLog/Properties/AssemblyInfo.cs b/Gigya.Microdot.Logging.NLog/Properties/AssemblyInfo.cs index 13dd5ecc..46a0be1f 100644 --- a/Gigya.Microdot.Logging.NLog/Properties/AssemblyInfo.cs +++ b/Gigya.Microdot.Logging.NLog/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ -using System.Reflection; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("06e45085-5a54-4bfe-bd24-e9c3983a2689")] diff --git a/Gigya.Microdot.Logging.NLog/paket.references b/Gigya.Microdot.Logging.NLog/paket.references deleted file mode 100644 index c51fcf0a..00000000 --- a/Gigya.Microdot.Logging.NLog/paket.references +++ /dev/null @@ -1,3 +0,0 @@ -NLog -Ninject -System.Net.Http \ No newline at end of file diff --git a/Gigya.Microdot.Logging.NLog/paket.template b/Gigya.Microdot.Logging.NLog/paket.template deleted file mode 100644 index a438dc31..00000000 --- a/Gigya.Microdot.Logging.NLog/paket.template +++ /dev/null @@ -1,10 +0,0 @@ -type - project -description - An implementation of Microdot's logging and tracing using NLog. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices NLog logging tracing \ No newline at end of file diff --git a/Gigya.Microdot.Ninject.Host/App.config b/Gigya.Microdot.Ninject.Host/App.config deleted file mode 100644 index 8b274594..00000000 --- a/Gigya.Microdot.Ninject.Host/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/Gigya.Microdot.Ninject.Host/Gigya.Microdot.Ninject.Host.csproj b/Gigya.Microdot.Ninject.Host/Gigya.Microdot.Ninject.Host.csproj index 78ca3c6d..0114a167 100644 --- a/Gigya.Microdot.Ninject.Host/Gigya.Microdot.Ninject.Host.csproj +++ b/Gigya.Microdot.Ninject.Host/Gigya.Microdot.Ninject.Host.csproj @@ -1,17 +1,20 @@  - - netstandard2.0 - true - Gigya.Microdot.Ninject.Host - $(SolutionDir)main.ruleset - - - - - - - - - + + Gigya.Microdot.Ninject.Host + + A container used to host non-Orleans Microdot service which uses Ninject + for dependency injection. Incoming HTTP calls (via Gigya.Microdot.ServiceProxy) + are dispatched to a specified class instance. Part of the Microdot framework. + + gigya microdot microservice microservices ninject ioc di + + + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.Ninject.Host/MicrodotServiceHost.cs b/Gigya.Microdot.Ninject.Host/MicrodotServiceHost.cs index d89152d6..9524f8fb 100644 --- a/Gigya.Microdot.Ninject.Host/MicrodotServiceHost.cs +++ b/Gigya.Microdot.Ninject.Host/MicrodotServiceHost.cs @@ -20,10 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Gigya.Microdot.Configuration; using Gigya.Microdot.Hosting; using Gigya.Microdot.Hosting.Environment; @@ -36,7 +32,8 @@ using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.Measurement.Workload; using Ninject; -using Ninject.Syntax; +using System; +using System.Threading; namespace Gigya.Microdot.Ninject.Host { @@ -78,6 +75,7 @@ protected override void OnStart() CrashHandler = Kernel.Get(); CrashHandler.Init(OnCrash); + IWorkloadMetrics workloadMetrics = Kernel.Get(); workloadMetrics.Init(); @@ -90,6 +88,8 @@ protected override void OnStart() VerifyConfigurationsIfNeeded(Kernel.Get(), Kernel.Get()); + this.SetThreadPoolConfigurations(Kernel); + this.Warmup(Kernel); //don't move up the get should be after all the binding are done @@ -125,6 +125,14 @@ protected override void OnStop() Dispose(); } + /// + /// An extensibility point - used to change default values of .Net ThreadPool. + /// + protected virtual void SetThreadPoolConfigurations(IKernel kernel) + { + base.SetThreadPoolConfigurations(kernel.Get()); + } + /// /// An extensibility point - this method is called in process of configuration objects verification. /// diff --git a/Gigya.Microdot.Ninject.Host/Properties/AssemblyInfo.cs b/Gigya.Microdot.Ninject.Host/Properties/AssemblyInfo.cs index ec737702..8f35548d 100644 --- a/Gigya.Microdot.Ninject.Host/Properties/AssemblyInfo.cs +++ b/Gigya.Microdot.Ninject.Host/Properties/AssemblyInfo.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Reflection; using System.Runtime.InteropServices; // The following GUID is for the ID of the typelib if this project is exposed to COM diff --git a/Gigya.Microdot.Ninject.Host/paket.references b/Gigya.Microdot.Ninject.Host/paket.references deleted file mode 100644 index 312287eb..00000000 --- a/Gigya.Microdot.Ninject.Host/paket.references +++ /dev/null @@ -1,6 +0,0 @@ -Ninject -Ninject.Extensions.Conventions -Ninject.Extensions.Factory -System.Threading.Tasks.Dataflow -Microsoft.CSharp -System.Net.Http diff --git a/Gigya.Microdot.Ninject.Host/paket.template b/Gigya.Microdot.Ninject.Host/paket.template deleted file mode 100644 index cc26f4cb..00000000 --- a/Gigya.Microdot.Ninject.Host/paket.template +++ /dev/null @@ -1,12 +0,0 @@ -type - project -description - A container used to host non-Orleans Microdot service which uses Ninject - for dependency injection. Incoming HTTP calls (via Gigya.Microdot.ServiceProxy) - are dispatched to a specified class instance. Part of the Microdot framework. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices ninject ioc di \ No newline at end of file diff --git a/Gigya.Microdot.Ninject/ConfigEventFactory.cs b/Gigya.Microdot.Ninject/ConfigEventFactory.cs index b88d027d..b0c8f622 100644 --- a/Gigya.Microdot.Ninject/ConfigEventFactory.cs +++ b/Gigya.Microdot.Ninject/ConfigEventFactory.cs @@ -1,8 +1,8 @@ -using System.Threading.Tasks.Dataflow; -using Gigya.Microdot.Configuration; +using Gigya.Microdot.Configuration; using Gigya.Microdot.Interfaces.Configuration; using Ninject; using Ninject.Syntax; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.Ninject { diff --git a/Gigya.Microdot.Ninject/ConfigVerificationModule.cs b/Gigya.Microdot.Ninject/ConfigVerificationModule.cs index 97f5c51f..39c47790 100644 --- a/Gigya.Microdot.Ninject/ConfigVerificationModule.cs +++ b/Gigya.Microdot.Ninject/ConfigVerificationModule.cs @@ -20,17 +20,16 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Threading.Tasks; -using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.Logging; using Ninject; using Ninject.Modules; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading.Tasks; namespace Gigya.Microdot.Ninject { diff --git a/Gigya.Microdot.Ninject/Gigya.Microdot.Ninject.csproj b/Gigya.Microdot.Ninject/Gigya.Microdot.Ninject.csproj index b23b74c6..6445ffbf 100644 --- a/Gigya.Microdot.Ninject/Gigya.Microdot.Ninject.csproj +++ b/Gigya.Microdot.Ninject/Gigya.Microdot.Ninject.csproj @@ -1,18 +1,23 @@  - - netstandard2.0 - Gigya.Microdot.Ninject - $(SolutionDir)main.ruleset - - - - - - - - - - - + + Gigya.Microdot.Ninject + Ninject modules, providers and binding resolvers for various Microdotcomponents, part of the Microdot framework. + gigya microdot microservice microservices ninject ioc di + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.Ninject/ILoggingModule.cs b/Gigya.Microdot.Ninject/ILoggingModule.cs index 7d381926..7239ce71 100644 --- a/Gigya.Microdot.Ninject/ILoggingModule.cs +++ b/Gigya.Microdot.Ninject/ILoggingModule.cs @@ -20,14 +20,14 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Ninject.Syntax; +using System; namespace Gigya.Microdot.Ninject { - public interface ILoggingModule + public interface ILoggingModule { void Bind(IBindingToSyntax logBinding, IBindingToSyntax eventPublisherBinding, IBindingToSyntax> funLog); } diff --git a/Gigya.Microdot.Ninject/MicrodotConventions.cs b/Gigya.Microdot.Ninject/MicrodotConventions.cs index db3540ef..cebb7293 100644 --- a/Gigya.Microdot.Ninject/MicrodotConventions.cs +++ b/Gigya.Microdot.Ninject/MicrodotConventions.cs @@ -20,16 +20,17 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.Orleans.Hosting; +using Gigya.Microdot.SharedLogic.HttpService; using Ninject.Extensions.Conventions; using Ninject.Syntax; +using System; +using System.Collections.Generic; +using System.Linq; namespace Gigya.Microdot.Ninject { @@ -44,6 +45,7 @@ public static void BindClassesAsSingleton( { typeof(IConfigObject), typeof(IEvent), + typeof(ICertificateLocator), typeof(HttpServiceListener), typeof(GigyaSiloHost) }; @@ -79,6 +81,7 @@ public static void BindInterfacesAsSingleton( typeof(IConfigObject), typeof(IEvent), typeof(IEnvironment), + typeof(ICertificateLocator), typeof(HttpServiceListener), typeof(GigyaSiloHost) }; diff --git a/Gigya.Microdot.Ninject/MicrodotHostingModule.cs b/Gigya.Microdot.Ninject/MicrodotHostingModule.cs index d6ab7a3b..79a3a0b3 100644 --- a/Gigya.Microdot.Ninject/MicrodotHostingModule.cs +++ b/Gigya.Microdot.Ninject/MicrodotHostingModule.cs @@ -20,13 +20,18 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Hosting; using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.SharedLogic; +using Gigya.Microdot.SharedLogic.HttpService; +using Gigya.Microdot.SharedLogic.Measurement.Workload; +using Gigya.Microdot.SharedLogic.Security; using Ninject.Modules; +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; namespace Gigya.Microdot.Ninject { @@ -44,6 +49,22 @@ public override void Load() bindInterfacesInAssemblies: new List{typeof(ILog)}, assemblies: new[] { typeof(HostingAssembly) }); + // Good location for Orleans, NotOrleans and Tests hosts + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + Kernel.Bind().To().InSingletonScope(); + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + Kernel.Bind().To().InSingletonScope(); + else + throw new EnvironmentException($"Only Windows or Linux allowed for ICertificateLocator - {nameof(MicrodotHostingModule)}"); + + +#if NET5_0_OR_GREATER + Kernel.Rebind().To().InSingletonScope(); + Kernel.Rebind().To().InSingletonScope(); +#else + Kernel.Rebind().To().InSingletonScope(); +#endif + Bind().To().InSingletonScope(); } } diff --git a/Gigya.Microdot.Ninject/MicrodotInitializer.cs b/Gigya.Microdot.Ninject/MicrodotInitializer.cs index 1a224160..1776a8c1 100644 --- a/Gigya.Microdot.Ninject/MicrodotInitializer.cs +++ b/Gigya.Microdot.Ninject/MicrodotInitializer.cs @@ -1,10 +1,10 @@ -using System; -using Gigya.Microdot.Hosting.Environment; +using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic; using Ninject; +using System; namespace Gigya.Microdot.Ninject { diff --git a/Gigya.Microdot.Ninject/MicrodotModule.cs b/Gigya.Microdot.Ninject/MicrodotModule.cs index 4bbe19c7..0e315a29 100644 --- a/Gigya.Microdot.Ninject/MicrodotModule.cs +++ b/Gigya.Microdot.Ninject/MicrodotModule.cs @@ -20,11 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.Configuration; using Gigya.Microdot.Configuration.Objects; @@ -41,16 +36,17 @@ using Gigya.Microdot.ServiceProxy.Caching; using Gigya.Microdot.ServiceProxy.Caching.RevokeNotifier; using Gigya.Microdot.SharedLogic; -using Gigya.Microdot.SharedLogic.Events; -using Gigya.Microdot.SharedLogic.Exceptions; using Gigya.Microdot.SharedLogic.HttpService; using Gigya.Microdot.SharedLogic.Monitor; -using Gigya.Microdot.SharedLogic.Security; using Metrics; using Ninject; using Ninject.Activation; using Ninject.Extensions.Factory; using Ninject.Modules; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; using ConsulClient = Gigya.Microdot.ServiceDiscovery.ConsulClient; using IConsulClient = Gigya.Microdot.ServiceDiscovery.IConsulClient; diff --git a/Gigya.Microdot.Ninject/NinjectExtensions.cs b/Gigya.Microdot.Ninject/NinjectExtensions.cs index 60efef59..910c13ad 100644 --- a/Gigya.Microdot.Ninject/NinjectExtensions.cs +++ b/Gigya.Microdot.Ninject/NinjectExtensions.cs @@ -20,11 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Ninject; +using Ninject.Planning.Bindings; using System; using System.Collections.Concurrent; using System.Linq; -using Ninject; -using Ninject.Planning.Bindings; #pragma warning disable 1574 diff --git a/Gigya.Microdot.Ninject/Properties/AssemblyInfo.cs b/Gigya.Microdot.Ninject/Properties/AssemblyInfo.cs index 70bcf07f..77c1ec4e 100644 --- a/Gigya.Microdot.Ninject/Properties/AssemblyInfo.cs +++ b/Gigya.Microdot.Ninject/Properties/AssemblyInfo.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Reflection; using System.Runtime.InteropServices; // The following GUID is for the ID of the typelib if this project is exposed to COM diff --git a/Gigya.Microdot.Ninject/RegexTimeoutInitializer.cs b/Gigya.Microdot.Ninject/RegexTimeoutInitializer.cs index 4742f3c4..8bce1d06 100644 --- a/Gigya.Microdot.Ninject/RegexTimeoutInitializer.cs +++ b/Gigya.Microdot.Ninject/RegexTimeoutInitializer.cs @@ -1,5 +1,4 @@ using System; -using System.Configuration; namespace Gigya.Microdot.Ninject { diff --git a/Gigya.Microdot.Ninject/ServiceProxyModule.cs b/Gigya.Microdot.Ninject/ServiceProxyModule.cs index 03870b59..bf3e3fdc 100644 --- a/Gigya.Microdot.Ninject/ServiceProxyModule.cs +++ b/Gigya.Microdot.Ninject/ServiceProxyModule.cs @@ -20,10 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.ServiceProxy; using Gigya.Microdot.ServiceProxy.Caching; @@ -34,6 +30,10 @@ using Ninject.Parameters; using Ninject.Planning.Bindings; using Ninject.Planning.Bindings.Resolvers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; namespace Gigya.Microdot.Ninject { diff --git a/Gigya.Microdot.Ninject/SystemInitializer/SystemInitializer.cs b/Gigya.Microdot.Ninject/SystemInitializer/SystemInitializer.cs index 06aaeacb..e3b80f69 100644 --- a/Gigya.Microdot.Ninject/SystemInitializer/SystemInitializer.cs +++ b/Gigya.Microdot.Ninject/SystemInitializer/SystemInitializer.cs @@ -20,15 +20,15 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Linq; -using System.Net; -using System.Threading.Tasks.Dataflow; using Gigya.Microdot.Configuration; using Gigya.Microdot.Configuration.Objects; using Gigya.Microdot.Hosting.Validators; using Gigya.Microdot.Interfaces; using Ninject; +using System; +using System.Linq; +using System.Net; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.Ninject.SystemInitializer { diff --git a/Gigya.Microdot.Ninject/paket.references b/Gigya.Microdot.Ninject/paket.references deleted file mode 100644 index 5b14413e..00000000 --- a/Gigya.Microdot.Ninject/paket.references +++ /dev/null @@ -1,8 +0,0 @@ -Gigya.ServiceContract -Ninject -Ninject.Extensions.Conventions -Ninject.Extensions.Factory -System.Threading.Tasks.Dataflow -Castle.Core -Microsoft.CSharp -System.Net.Http diff --git a/Gigya.Microdot.Ninject/paket.template b/Gigya.Microdot.Ninject/paket.template deleted file mode 100644 index 564ca36b..00000000 --- a/Gigya.Microdot.Ninject/paket.template +++ /dev/null @@ -1,11 +0,0 @@ -type - project -description - Ninject modules, providers and binding resolvers for various Microdot - components, part of the Microdot framework. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices ninject ioc di \ No newline at end of file diff --git a/Gigya.Microdot.Orleans.Hosting/ClusterIdentity.cs b/Gigya.Microdot.Orleans.Hosting/ClusterIdentity.cs index 85ebbdf0..da733011 100644 --- a/Gigya.Microdot.Orleans.Hosting/ClusterIdentity.cs +++ b/Gigya.Microdot.Orleans.Hosting/ClusterIdentity.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic; @@ -35,7 +34,7 @@ public class ClusterIdentity /// ServiceId's are intended to be long lived Id values for a particular service which will remain constant /// even if the service is started / redeployed multiple times during its operations life. /// - public Guid ServiceId { get; } + public string ServiceId { get; } /// /// Provides the SiloDeploymentId for this orleans cluster. @@ -52,12 +51,10 @@ public ClusterIdentity(ILog log, IEnvironment environment, CurrentApplicationInf string dc = environment.Zone; string env = environment.DeploymentEnvironment; - var serviceIdSourceString = string.Join("_", dc, env, appInfo.Name, environment.InstanceName); - ServiceId = Guid.Parse(serviceIdSourceString.GetHashCode().ToString("X32")); + ServiceId = string.Join("_", dc, appInfo.Name).ToLower(); + DeploymentId = string.Join("_", dc, env, appInfo.Name, environment.InstanceName, appInfo.Version).ToLower(); - DeploymentId = serviceIdSourceString + "_" + appInfo.Version; - - log.Info(_ => _("Orleans Cluster Identity Information (see tags)", unencryptedTags: new { OrleansDeploymentId = DeploymentId, OrleansServiceId = ServiceId, serviceIdSourceString })); + log.Info(_ => _("Orleans Cluster Identity Information", unencryptedTags: new { OrleansDeploymentId = DeploymentId, OrleansServiceId = ServiceId })); } } } \ No newline at end of file diff --git a/Gigya.Microdot.Orleans.Hosting/Events/GrainCallEvent.cs b/Gigya.Microdot.Orleans.Hosting/Events/GrainCallEvent.cs index f2cf5c42..97bdb313 100644 --- a/Gigya.Microdot.Orleans.Hosting/Events/GrainCallEvent.cs +++ b/Gigya.Microdot.Orleans.Hosting/Events/GrainCallEvent.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Gigya.Microdot.Hosting.Events; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.SharedLogic.Events; diff --git a/Gigya.Microdot.Orleans.Hosting/Gigya.Microdot.Orleans.Hosting.csproj b/Gigya.Microdot.Orleans.Hosting/Gigya.Microdot.Orleans.Hosting.csproj index 31157911..f06878fb 100644 --- a/Gigya.Microdot.Orleans.Hosting/Gigya.Microdot.Orleans.Hosting.csproj +++ b/Gigya.Microdot.Orleans.Hosting/Gigya.Microdot.Orleans.Hosting.csproj @@ -1,14 +1,37 @@  - - netstandard2.0 - Gigya.Microdot.Orleans.Host - $(SolutionDir)main.ruleset - - - - - - - - \ No newline at end of file + + Gigya.Microdot.Orleans.Host + Infrastructure used for hosting Orleans Microdot services, part of the Microdot framework. + gigya microdot microservice microservices + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.Orleans.Hosting/GrainActivator.cs b/Gigya.Microdot.Orleans.Hosting/GrainActivator.cs index 299a65bc..3b31a79b 100644 --- a/Gigya.Microdot.Orleans.Hosting/GrainActivator.cs +++ b/Gigya.Microdot.Orleans.Hosting/GrainActivator.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Concurrent; using Gigya.Microdot.Hosting.HttpService; using Orleans; +using System; +using System.Collections.Concurrent; namespace Gigya.Microdot.Orleans.Hosting { diff --git a/Gigya.Microdot.Orleans.Hosting/GrainLoggingConfig.cs b/Gigya.Microdot.Orleans.Hosting/GrainLoggingConfig.cs index 19c166ba..5ef55c1f 100644 --- a/Gigya.Microdot.Orleans.Hosting/GrainLoggingConfig.cs +++ b/Gigya.Microdot.Orleans.Hosting/GrainLoggingConfig.cs @@ -1,5 +1,5 @@ -using System.ComponentModel.DataAnnotations; using Gigya.Microdot.Interfaces.Configuration; +using System.ComponentModel.DataAnnotations; namespace Gigya.Microdot.Orleans.Hosting { diff --git a/Gigya.Microdot.Orleans.Hosting/IOrleansConfigurationBuilderConfigurator.cs b/Gigya.Microdot.Orleans.Hosting/IOrleansConfigurationBuilderConfigurator.cs index 2d65f8b4..3651c298 100644 --- a/Gigya.Microdot.Orleans.Hosting/IOrleansConfigurationBuilderConfigurator.cs +++ b/Gigya.Microdot.Orleans.Hosting/IOrleansConfigurationBuilderConfigurator.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Orleans.Hosting; +using Orleans.Hosting; namespace Gigya.Microdot.Orleans.Hosting { diff --git a/Gigya.Microdot.Orleans.Hosting/InfraProcessingGrain.cs b/Gigya.Microdot.Orleans.Hosting/InfraProcessingGrain.cs index 09142734..27006c8c 100644 --- a/Gigya.Microdot.Orleans.Hosting/InfraProcessingGrain.cs +++ b/Gigya.Microdot.Orleans.Hosting/InfraProcessingGrain.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Threading.Tasks; using Orleans; using Orleans.Concurrency; +using System.Threading.Tasks; namespace Gigya.Microdot.Orleans.Hosting { diff --git a/Gigya.Microdot.Orleans.Hosting/Logging/OrleansLogAdapter.cs b/Gigya.Microdot.Orleans.Hosting/Logging/OrleansLogAdapter.cs index d9ed6148..9941b87d 100644 --- a/Gigya.Microdot.Orleans.Hosting/Logging/OrleansLogAdapter.cs +++ b/Gigya.Microdot.Orleans.Hosting/Logging/OrleansLogAdapter.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Diagnostics; using Gigya.Microdot.Interfaces.Logging; using Microsoft.Extensions.Logging; +using System; +using System.Diagnostics; namespace Gigya.Microdot.Orleans.Hosting.Logging diff --git a/Gigya.Microdot.Orleans.Hosting/Logging/OrleansLogEnrichment.cs b/Gigya.Microdot.Orleans.Hosting/Logging/OrleansLogEnrichment.cs index 8a6c7d22..fa26dd93 100644 --- a/Gigya.Microdot.Orleans.Hosting/Logging/OrleansLogEnrichment.cs +++ b/Gigya.Microdot.Orleans.Hosting/Logging/OrleansLogEnrichment.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Orleans.Runtime; using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using Orleans.Runtime; namespace Gigya.Microdot.Orleans.Hosting.Logging { diff --git a/Gigya.Microdot.Orleans.Hosting/Logging/OrleansLogProvider.cs b/Gigya.Microdot.Orleans.Hosting/Logging/OrleansLogProvider.cs index 017d0f29..63a20654 100644 --- a/Gigya.Microdot.Orleans.Hosting/Logging/OrleansLogProvider.cs +++ b/Gigya.Microdot.Orleans.Hosting/Logging/OrleansLogProvider.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Microsoft.Extensions.Logging; +using System; namespace Gigya.Microdot.Orleans.Hosting.Logging { diff --git a/Gigya.Microdot.Orleans.Hosting/Logging/ZooKeeperLogConsumer.cs b/Gigya.Microdot.Orleans.Hosting/Logging/ZooKeeperLogConsumer.cs index 6cb30f1f..95476aa0 100644 --- a/Gigya.Microdot.Orleans.Hosting/Logging/ZooKeeperLogConsumer.cs +++ b/Gigya.Microdot.Orleans.Hosting/Logging/ZooKeeperLogConsumer.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Diagnostics; using Gigya.Microdot.Interfaces.Logging; using org.apache.utils; +using System; +using System.Diagnostics; namespace Gigya.Microdot.Orleans.Hosting.Logging { diff --git a/Gigya.Microdot.Orleans.Hosting/MicrodotIncomingGrainCallFilter.cs b/Gigya.Microdot.Orleans.Hosting/MicrodotIncomingGrainCallFilter.cs index b4472408..357f6445 100644 --- a/Gigya.Microdot.Orleans.Hosting/MicrodotIncomingGrainCallFilter.cs +++ b/Gigya.Microdot.Orleans.Hosting/MicrodotIncomingGrainCallFilter.cs @@ -7,10 +7,10 @@ using Gigya.Microdot.SharedLogic.Measurement; using Metrics; using Orleans; +using Orleans.Statistics; using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; -using Orleans.Statistics; namespace Gigya.Microdot.Orleans.Hosting { diff --git a/Gigya.Microdot.Orleans.Hosting/NonSerializedExceptionsSerializer.cs b/Gigya.Microdot.Orleans.Hosting/NonSerializedExceptionsSerializer.cs index 718c98f9..0c44010b 100644 --- a/Gigya.Microdot.Orleans.Hosting/NonSerializedExceptionsSerializer.cs +++ b/Gigya.Microdot.Orleans.Hosting/NonSerializedExceptionsSerializer.cs @@ -26,7 +26,6 @@ using System; using System.Net.Http; using System.Reflection; -using System.Runtime.CompilerServices; // ReSharper disable AssignNullToNotNullAttribute diff --git a/Gigya.Microdot.Orleans.Hosting/OrleansConfig.cs b/Gigya.Microdot.Orleans.Hosting/OrleansConfig.cs index a57322a3..6586792f 100644 --- a/Gigya.Microdot.Orleans.Hosting/OrleansConfig.cs +++ b/Gigya.Microdot.Orleans.Hosting/OrleansConfig.cs @@ -1,11 +1,11 @@ -using System; -using Gigya.Microdot.Interfaces.Configuration; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; +using Gigya.Microdot.Interfaces.Configuration; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Converters; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; namespace Gigya.Microdot.Orleans.Hosting { diff --git a/Gigya.Microdot.Orleans.Hosting/OrleansConfigurationBuilder.cs b/Gigya.Microdot.Orleans.Hosting/OrleansConfigurationBuilder.cs index 923c5b69..287f2291 100644 --- a/Gigya.Microdot.Orleans.Hosting/OrleansConfigurationBuilder.cs +++ b/Gigya.Microdot.Orleans.Hosting/OrleansConfigurationBuilder.cs @@ -23,21 +23,22 @@ #endregion Copyright using Gigya.Microdot.Hosting.HttpService; +using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic; +using Gigya.Microdot.SharedLogic.HttpService; +using Microsoft.AspNetCore.Connections; +using Orleans; using Orleans.Configuration; +using Orleans.Connections.Security; using Orleans.Hosting; +using Orleans.Providers; using Orleans.Statistics; using System; using System.Diagnostics; using System.Linq; using System.Net; +using System.Runtime.InteropServices; using System.Security.Authentication; -using Gigya.Microdot.SharedLogic.HttpService; -using Orleans.Providers; -using Orleans; -using Orleans.Connections.Security; -using Gigya.Microdot.Interfaces.SystemWrappers; -using Microsoft.AspNetCore.Connections; namespace Gigya.Microdot.Orleans.Hosting { @@ -245,15 +246,36 @@ private void SetSiloSource(ISiloHostBuilder silo) switch (_serviceArguments.SiloClusterMode) { case SiloClusterMode.ZooKeeper: - silo.UseZooKeeperClustering(options => + IPAddress hostIPAddress = null; + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + IPAddress.TryParse(_environment.HostIPAddress, out hostIPAddress); + + if (hostIPAddress == null) { - options.ConnectionString = _orleansConfig.ZooKeeper.ConnectionString; - }).ConfigureEndpoints(siloPort: _endPointDefinition.SiloNetworkingPort, gatewayPort: _endPointDefinition.SiloGatewayPort) - .Configure(options => + silo.UseZooKeeperClustering(options => + { + options.ConnectionString = _orleansConfig.ZooKeeper.ConnectionString; + }).ConfigureEndpoints(siloPort: _endPointDefinition.SiloNetworkingPort, gatewayPort: _endPointDefinition.SiloGatewayPort) + .Configure(options => + { + options.ClusterId = _clusterIdentity.DeploymentId; + options.ServiceId = _clusterIdentity.ServiceId; + }); + } + else { - options.ClusterId = _clusterIdentity.DeploymentId; - options.ServiceId = _clusterIdentity.ServiceId.ToString(); - }); + silo.UseZooKeeperClustering(options => + { + options.ConnectionString = _orleansConfig.ZooKeeper.ConnectionString; + }).ConfigureEndpoints(advertisedIP: hostIPAddress, siloPort: _endPointDefinition.SiloNetworkingPort, gatewayPort: _endPointDefinition.SiloGatewayPort, listenOnAnyHostAddress: true) + .Configure(options => + { + options.ClusterId = _clusterIdentity.DeploymentId; + options.ServiceId = _clusterIdentity.ServiceId; + }); + } + break; case SiloClusterMode.Unspecified: diff --git a/Gigya.Microdot.Orleans.Hosting/OrleansCustomSerialization.cs b/Gigya.Microdot.Orleans.Hosting/OrleansCustomSerialization.cs index 6ee04958..9e5432b2 100644 --- a/Gigya.Microdot.Orleans.Hosting/OrleansCustomSerialization.cs +++ b/Gigya.Microdot.Orleans.Hosting/OrleansCustomSerialization.cs @@ -22,14 +22,13 @@ #endregion Copyright +using Gigya.Microdot.SharedLogic.Security; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Orleans.Serialization; using System; -using System.Linq; using System.Collections.Generic; -using Gigya.Microdot.SharedLogic.Configurations; -using Gigya.Microdot.SharedLogic.Security; +using System.Linq; // ReSharper disable AssignNullToNotNullAttribute diff --git a/Gigya.Microdot.Orleans.Hosting/OrleansServiceInterfaceMapper.cs b/Gigya.Microdot.Orleans.Hosting/OrleansServiceInterfaceMapper.cs index 47b35da8..0e0b4cf5 100644 --- a/Gigya.Microdot.Orleans.Hosting/OrleansServiceInterfaceMapper.cs +++ b/Gigya.Microdot.Orleans.Hosting/OrleansServiceInterfaceMapper.cs @@ -20,14 +20,14 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.Interfaces; using Orleans; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; namespace Gigya.Microdot.Orleans.Hosting { diff --git a/Gigya.Microdot.Orleans.Hosting/OrleansTracingContext.cs b/Gigya.Microdot.Orleans.Hosting/OrleansTracingContext.cs index d8882abc..1e8a69b9 100644 --- a/Gigya.Microdot.Orleans.Hosting/OrleansTracingContext.cs +++ b/Gigya.Microdot.Orleans.Hosting/OrleansTracingContext.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using Gigya.Microdot.SharedLogic.Events; using Orleans.Runtime; namespace Gigya.Microdot.Orleans.Hosting diff --git a/Gigya.Microdot.Orleans.Hosting/ProcessingGrainWorker.cs b/Gigya.Microdot.Orleans.Hosting/ProcessingGrainWorker.cs index a7ce63ee..db49bc45 100644 --- a/Gigya.Microdot.Orleans.Hosting/ProcessingGrainWorker.cs +++ b/Gigya.Microdot.Orleans.Hosting/ProcessingGrainWorker.cs @@ -20,14 +20,12 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Diagnostics; -using System.Threading.Tasks; -using Gigya.Microdot.Configuration; using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.Hosting.Service; using Orleans; using Orleans.Concurrency; +using System; +using System.Threading.Tasks; namespace Gigya.Microdot.Orleans.Hosting { diff --git a/Gigya.Microdot.Orleans.Hosting/Properties/AssemblyInfo.cs b/Gigya.Microdot.Orleans.Hosting/Properties/AssemblyInfo.cs index 456ed247..c3a09297 100644 --- a/Gigya.Microdot.Orleans.Hosting/Properties/AssemblyInfo.cs +++ b/Gigya.Microdot.Orleans.Hosting/Properties/AssemblyInfo.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/Gigya.Microdot.Orleans.Hosting/paket.references b/Gigya.Microdot.Orleans.Hosting/paket.references deleted file mode 100644 index 63286697..00000000 --- a/Gigya.Microdot.Orleans.Hosting/paket.references +++ /dev/null @@ -1,36 +0,0 @@ -Gigya.ServiceContract -Microsoft.CodeAnalysis.CSharp -Microsoft.CodeAnalysis.Common -Microsoft.CSharp -System.Net.Http - -Microsoft.Orleans.Connections.Security -Microsoft.Orleans.Core -Microsoft.Orleans.Core.Abstractions -Microsoft.Orleans.OrleansCodeGenerator -Microsoft.Orleans.CodeGenerator.MSBuild -Microsoft.Orleans.OrleansRuntime -Microsoft.Orleans.OrleansProviders -Microsoft.Orleans.OrleansSqlUtils -Microsoft.Orleans.OrleansZooKeeperUtils -Microsoft.Orleans.Server -Microsoft.Orleans.OrleansTelemetryConsumers.Counters -Gigya.OrleansDashboard.NetStandard -# TODO: remove this dependency once we move to dotnet core and go back to using the original dashboard -System.Text.Json - - - -# lock dependcy in nuspac -Microsoft.Extensions.Configuration -Microsoft.AspNetCore.Connections.Abstractions -Microsoft.AspNetCore.Hosting -Microsoft.AspNetCore.Server.Kestrel -Microsoft.Extensions.Logging.Abstractions -Microsoft.Extensions.ObjectPool -Microsoft.Extensions.DependencyModel -Microsoft.Extensions.FileSystemGlobbing -Microsoft.Extensions.Primitives -System.Diagnostics.PerformanceCounter -System.Threading.Tasks.Dataflow -Microsoft.AspNetCore.Http.Features diff --git a/Gigya.Microdot.Orleans.Hosting/paket.template b/Gigya.Microdot.Orleans.Hosting/paket.template deleted file mode 100644 index ebe36861..00000000 --- a/Gigya.Microdot.Orleans.Hosting/paket.template +++ /dev/null @@ -1,11 +0,0 @@ -type - project -description - Infrastructure used for hosting Orleans Microdot services, part of the - Microdot framework. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices \ No newline at end of file diff --git a/Gigya.Microdot.Orleans.Ninject.Host/Gigya.Microdot.Orleans.Ninject.Host.csproj b/Gigya.Microdot.Orleans.Ninject.Host/Gigya.Microdot.Orleans.Ninject.Host.csproj index 8bcdc32d..2d17ab3e 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/Gigya.Microdot.Orleans.Ninject.Host.csproj +++ b/Gigya.Microdot.Orleans.Ninject.Host/Gigya.Microdot.Orleans.Ninject.Host.csproj @@ -1,19 +1,22 @@  - - netstandard2.0 - true - Gigya.Microdot.Orleans.Ninject.Host - $(SolutionDir)main.ruleset - - - - - - - - - - - + + Gigya.Microdot.Orleans.Ninject.Host + + A container used to host an Orleans Microdot service which uses Ninject for + dependency injection. Incoming HTTP calls (via Gigya.Microdot.ServiceProxy) + are handled and processed inside Orleans and are then dispatched to + specific Grains. Part of the Microdot framework. + + gigya microdot microservice microservices + + + + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.Orleans.Ninject.Host/GrainsWarmup.cs b/Gigya.Microdot.Orleans.Ninject.Host/GrainsWarmup.cs index 72e0264b..b6db10be 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/GrainsWarmup.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/GrainsWarmup.cs @@ -20,15 +20,15 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.Interfaces.Logging; using Ninject; using Orleans; using Orleans.Core; using Orleans.Runtime; +using System; +using System.Collections.Generic; +using System.Linq; namespace Gigya.Microdot.Orleans.Ninject.Host { diff --git a/Gigya.Microdot.Orleans.Ninject.Host/MicrodotOrleansHostModule.cs b/Gigya.Microdot.Orleans.Ninject.Host/MicrodotOrleansHostModule.cs index 323710f7..d2027244 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/MicrodotOrleansHostModule.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/MicrodotOrleansHostModule.cs @@ -21,21 +21,18 @@ #endregion using Gigya.Microdot.Hosting.HttpService; +using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Ninject; using Gigya.Microdot.Orleans.Hosting; +using Gigya.Microdot.Orleans.Hosting.Logging; +using Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding; using Gigya.Microdot.SharedLogic; using Ninject.Modules; using Orleans; -using System; -using System.Collections.Generic; -using Gigya.Microdot.Interfaces.Logging; -using Gigya.Microdot.Orleans.Hosting.Logging; -using Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding; -using Gigya.Microdot.SharedLogic.Configurations; -using Gigya.Microdot.SharedLogic.Security; -using Ninject; using Orleans.Runtime; using Orleans.Serialization; +using System; +using System.Collections.Generic; namespace Gigya.Microdot.Orleans.Ninject.Host { diff --git a/Gigya.Microdot.Orleans.Ninject.Host/MicrodotOrleansServiceHost.cs b/Gigya.Microdot.Orleans.Ninject.Host/MicrodotOrleansServiceHost.cs index 30d88e5e..fa93db8b 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/MicrodotOrleansServiceHost.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/MicrodotOrleansServiceHost.cs @@ -20,9 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Threading; -using System.Threading.Tasks; using Gigya.Microdot.Configuration; using Gigya.Microdot.Hosting; using Gigya.Microdot.Hosting.Environment; @@ -38,10 +35,13 @@ using Gigya.Microdot.Orleans.Hosting.Utils; using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.Measurement.Workload; +using Microsoft.Extensions.DependencyInjection; using Ninject; using Orleans; using Orleans.Hosting; -using Microsoft.Extensions.DependencyInjection; +using System; +using System.Threading; +using System.Threading.Tasks; namespace Gigya.Microdot.Orleans.Ninject.Host { @@ -67,7 +67,7 @@ protected override void OnStart() var env = HostEnvironment.CreateDefaultEnvironment(ServiceName, InfraVersion, Arguments); Kernel.Bind().ToConstant(env).InSingletonScope(); Kernel.Bind().ToConstant(env.ApplicationInfo).InSingletonScope(); - + this.PreConfigure(Kernel, Arguments); this.Configure(Kernel); @@ -92,6 +92,8 @@ protected override void OnStart() VerifyConfigurationsIfNeeded(Kernel.Get(), Kernel.Get()); + this.SetThreadPoolConfigurations(Kernel); + this.Warmup(Kernel); //don't move up the get should be after all the binding are done @@ -127,6 +129,15 @@ protected override void OnStop() Dispose(); } + /// + /// An extensibility point - used to change default values of .Net ThreadPool. + /// + protected virtual void SetThreadPoolConfigurations(IKernel kernel) + { + base.SetThreadPoolConfigurations(kernel.Get()); + } + + /// /// An extensibility point - this method is called in process of configuration objects verification. /// diff --git a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/DeadlockDetector.cs b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/DeadlockDetector.cs index 172e851d..3581fa72 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/DeadlockDetector.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/DeadlockDetector.cs @@ -20,22 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Linq; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; -using Gigya.Microdot.Orleans.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Ninject; -using Ninject.Activation; -using Ninject.Activation.Caching; -using Ninject.Parameters; -using Ninject.Planning.Bindings; -using Ninject.Planning.Targets; -using Ninject.Syntax; -using Orleans.Runtime; namespace Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding { diff --git a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/DeadlockDetectorExeption.cs b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/DeadlockDetectorExeption.cs index 6bc4bee0..d76a02f0 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/DeadlockDetectorExeption.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/DeadlockDetectorExeption.cs @@ -21,21 +21,7 @@ #endregion using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.InteropServices; using System.Runtime.Serialization; -using Gigya.Microdot.Orleans.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Ninject; -using Ninject.Activation; -using Ninject.Activation.Caching; -using Ninject.Parameters; -using Ninject.Planning.Bindings; -using Ninject.Planning.Targets; -using Ninject.Syntax; -using Orleans.Runtime; diff --git a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/GlobalScopeNotSupportFromNinject.cs b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/GlobalScopeNotSupportFromNinject.cs index 3af3c63e..c525f108 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/GlobalScopeNotSupportFromNinject.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/GlobalScopeNotSupportFromNinject.cs @@ -21,30 +21,7 @@ #endregion using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel.Design; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; using System.Runtime.Serialization; -using Microsoft.Extensions.DependencyInjection; -using Ninject; -using Ninject.Activation; -using Ninject.Activation.Caching; -using Ninject.Activation.Strategies; -using Ninject.Injection; -using Ninject.Modules; -using Ninject.Parameters; -using Ninject.Planning; -using Ninject.Planning.Bindings; -using Ninject.Planning.Bindings.Resolvers; -using Ninject.Planning.Strategies; -using Ninject.Planning.Targets; -using Ninject.Selection; -using Ninject.Selection.Heuristics; -using Ninject.Syntax; -using static Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding.ScopeCache; namespace Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding { diff --git a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/IGlobalServiceProvider.cs b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/IGlobalServiceProvider.cs index 2ff6a810..bfba4297 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/IGlobalServiceProvider.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/IGlobalServiceProvider.cs @@ -21,28 +21,6 @@ #endregion using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel.Design; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; -using Microsoft.Extensions.DependencyInjection; -using Ninject; -using Ninject.Activation; -using Ninject.Activation.Caching; -using Ninject.Activation.Strategies; -using Ninject.Injection; -using Ninject.Modules; -using Ninject.Parameters; -using Ninject.Planning; -using Ninject.Planning.Bindings; -using Ninject.Planning.Bindings.Resolvers; -using Ninject.Planning.Strategies; -using Ninject.Planning.Targets; -using Ninject.Selection; -using Ninject.Selection.Heuristics; -using Ninject.Syntax; namespace Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding { diff --git a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/MicrodotNinectScopeParameter.cs b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/MicrodotNinectScopeParameter.cs index ad426a72..3e9b71bd 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/MicrodotNinectScopeParameter.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/MicrodotNinectScopeParameter.cs @@ -20,30 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel.Design; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; -using Microsoft.Extensions.DependencyInjection; -using Ninject; using Ninject.Activation; -using Ninject.Activation.Caching; -using Ninject.Activation.Strategies; -using Ninject.Injection; -using Ninject.Modules; using Ninject.Parameters; -using Ninject.Planning; -using Ninject.Planning.Bindings; -using Ninject.Planning.Bindings.Resolvers; -using Ninject.Planning.Strategies; using Ninject.Planning.Targets; -using Ninject.Selection; -using Ninject.Selection.Heuristics; -using Ninject.Syntax; -using static Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding.ScopeCache; +using System; namespace Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding { diff --git a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/MicrodotServiceProviderWithScope.cs b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/MicrodotServiceProviderWithScope.cs index 7b7639b8..1fd9f605 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/MicrodotServiceProviderWithScope.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/MicrodotServiceProviderWithScope.cs @@ -20,29 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel.Design; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; using Microsoft.Extensions.DependencyInjection; using Ninject; -using Ninject.Activation; -using Ninject.Activation.Caching; -using Ninject.Activation.Strategies; -using Ninject.Injection; -using Ninject.Modules; -using Ninject.Parameters; -using Ninject.Planning; -using Ninject.Planning.Bindings; -using Ninject.Planning.Bindings.Resolvers; -using Ninject.Planning.Strategies; -using Ninject.Planning.Targets; -using Ninject.Selection; -using Ninject.Selection.Heuristics; using Ninject.Syntax; +using System; namespace Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding { diff --git a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/MicrodotServiceScopeFactory.cs b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/MicrodotServiceScopeFactory.cs index e1c3d852..0d704b44 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/MicrodotServiceScopeFactory.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/MicrodotServiceScopeFactory.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Microsoft.Extensions.DependencyInjection; +using System; namespace Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding { diff --git a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/OrleansToNinjectBinding.cs b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/OrleansToNinjectBinding.cs index 0dc30df1..9a1bf445 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/OrleansToNinjectBinding.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/OrleansToNinjectBinding.cs @@ -20,22 +20,15 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; using Gigya.Microdot.Orleans.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Ninject; using Ninject.Activation; -using Ninject.Activation.Caching; -using Ninject.Parameters; -using Ninject.Planning.Bindings; -using Ninject.Planning.Targets; using Ninject.Syntax; using Orleans.Runtime; +using System; +using System.Linq; namespace Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding { diff --git a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/ResolveRealParameter.cs b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/ResolveRealParameter.cs index a56f3135..b4c37fc9 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/ResolveRealParameter.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/ResolveRealParameter.cs @@ -20,19 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; -using Gigya.Microdot.Orleans.Hosting; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Ninject; using Ninject.Activation; using Ninject.Parameters; -using Ninject.Planning.Bindings; using Ninject.Planning.Targets; -using Ninject.Syntax; -using Orleans.Runtime; +using System; namespace Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding { diff --git a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/ScopeCache.cs b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/ScopeCache.cs index bf70acb9..37f3ad53 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/ScopeCache.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/NinjectOrleansBinding/ScopeCache.cs @@ -21,30 +21,9 @@ #endregion using System; -using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; -using System.ComponentModel.Design; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; using System.Threading; -using Microsoft.Extensions.DependencyInjection; -using Ninject; -using Ninject.Activation; -using Ninject.Activation.Caching; -using Ninject.Activation.Strategies; -using Ninject.Injection; -using Ninject.Modules; -using Ninject.Parameters; -using Ninject.Planning; -using Ninject.Planning.Bindings; -using Ninject.Planning.Bindings.Resolvers; -using Ninject.Planning.Strategies; -using Ninject.Planning.Targets; -using Ninject.Selection; -using Ninject.Selection.Heuristics; -using Ninject.Syntax; namespace Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding { diff --git a/Gigya.Microdot.Orleans.Ninject.Host/Properties/AssemblyInfo.cs b/Gigya.Microdot.Orleans.Ninject.Host/Properties/AssemblyInfo.cs index 4a25890d..082e83a3 100644 --- a/Gigya.Microdot.Orleans.Ninject.Host/Properties/AssemblyInfo.cs +++ b/Gigya.Microdot.Orleans.Ninject.Host/Properties/AssemblyInfo.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/Gigya.Microdot.Orleans.Ninject.Host/app.config b/Gigya.Microdot.Orleans.Ninject.Host/app.config deleted file mode 100644 index 1b7a89ad..00000000 --- a/Gigya.Microdot.Orleans.Ninject.Host/app.config +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - True - - - - diff --git a/Gigya.Microdot.Orleans.Ninject.Host/paket.references b/Gigya.Microdot.Orleans.Ninject.Host/paket.references deleted file mode 100644 index 1a7f9014..00000000 --- a/Gigya.Microdot.Orleans.Ninject.Host/paket.references +++ /dev/null @@ -1,13 +0,0 @@ -Gigya.ServiceContract -Microsoft.Extensions.DependencyInjection -Microsoft.Extensions.DependencyInjection.Abstractions -Microsoft.Orleans.Core -Microsoft.Orleans.OrleansRuntime -Microsoft.Orleans.OrleansProviders -Ninject -Ninject.Extensions.Conventions -Ninject.Extensions.Factory -Microsoft.Orleans.Server - -Microsoft.CSharp -System.Net.Http \ No newline at end of file diff --git a/Gigya.Microdot.Orleans.Ninject.Host/paket.template b/Gigya.Microdot.Orleans.Ninject.Host/paket.template deleted file mode 100644 index ec14f493..00000000 --- a/Gigya.Microdot.Orleans.Ninject.Host/paket.template +++ /dev/null @@ -1,13 +0,0 @@ -type - project -description - A container used to host an Orleans Microdot service which uses Ninject for - dependency injection. Incoming HTTP calls (via Gigya.Microdot.ServiceProxy) - are handled and processed inside Orleans and are then dispatched to - specific Grains. Part of the Microdot framework. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices \ No newline at end of file diff --git a/Gigya.Microdot.ServiceDiscovery/AvailabilityZoneServiceDiscovery/AvailabilityZoneServiceDiscovery.cs b/Gigya.Microdot.ServiceDiscovery/AvailabilityZoneServiceDiscovery/AvailabilityZoneServiceDiscovery.cs index 48c07e1d..64ed837a 100644 --- a/Gigya.Microdot.ServiceDiscovery/AvailabilityZoneServiceDiscovery/AvailabilityZoneServiceDiscovery.cs +++ b/Gigya.Microdot.ServiceDiscovery/AvailabilityZoneServiceDiscovery/AvailabilityZoneServiceDiscovery.cs @@ -1,10 +1,10 @@ using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.ServiceDiscovery.Rewrite; using System; using System.Collections.Generic; using System.Net; using System.Threading; using System.Threading.Tasks; -using Gigya.Microdot.ServiceDiscovery.Rewrite; namespace Gigya.Microdot.ServiceDiscovery.AvailabilityZoneServiceDiscovery { diff --git a/Gigya.Microdot.ServiceDiscovery/AvailabilityZoneServiceDiscovery/IAvailabilityZoneServiceDiscovery.cs b/Gigya.Microdot.ServiceDiscovery/AvailabilityZoneServiceDiscovery/IAvailabilityZoneServiceDiscovery.cs index 4b52f64a..fc1da90b 100644 --- a/Gigya.Microdot.ServiceDiscovery/AvailabilityZoneServiceDiscovery/IAvailabilityZoneServiceDiscovery.cs +++ b/Gigya.Microdot.ServiceDiscovery/AvailabilityZoneServiceDiscovery/IAvailabilityZoneServiceDiscovery.cs @@ -1,7 +1,5 @@ -using System; -using System.Collections.Generic; +using Gigya.Common.Contracts.Exceptions; using System.Threading.Tasks; -using Gigya.Common.Contracts.Exceptions; namespace Gigya.Microdot.ServiceDiscovery.AvailabilityZoneServiceDiscovery { diff --git a/Gigya.Microdot.ServiceDiscovery/Config/CachingPolicyConfig.cs b/Gigya.Microdot.ServiceDiscovery/Config/CachingPolicyConfig.cs index db689149..2e234762 100644 --- a/Gigya.Microdot.ServiceDiscovery/Config/CachingPolicyConfig.cs +++ b/Gigya.Microdot.ServiceDiscovery/Config/CachingPolicyConfig.cs @@ -20,11 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Attributes; using System; -using System.Collections.Generic; using System.Collections.Immutable; using System.Runtime.Serialization; -using Gigya.Common.Contracts.Attributes; namespace Gigya.Microdot.ServiceDiscovery.Config { diff --git a/Gigya.Microdot.ServiceDiscovery/Config/ConsulConfig.cs b/Gigya.Microdot.ServiceDiscovery/Config/ConsulConfig.cs index 14e0c6b3..b1f1faa0 100644 --- a/Gigya.Microdot.ServiceDiscovery/Config/ConsulConfig.cs +++ b/Gigya.Microdot.ServiceDiscovery/Config/ConsulConfig.cs @@ -1,5 +1,5 @@ -using System; using Gigya.Microdot.Interfaces.Configuration; +using System; namespace Gigya.Microdot.ServiceDiscovery.Config { diff --git a/Gigya.Microdot.ServiceDiscovery/Config/DiscoveryConfig.cs b/Gigya.Microdot.ServiceDiscovery/Config/DiscoveryConfig.cs index 88cecd72..2cd38874 100644 --- a/Gigya.Microdot.ServiceDiscovery/Config/DiscoveryConfig.cs +++ b/Gigya.Microdot.ServiceDiscovery/Config/DiscoveryConfig.cs @@ -20,14 +20,14 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.Configuration; +using Gigya.Microdot.SharedLogic.HttpService; +using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; -using Gigya.Microdot.Interfaces.Configuration; -using Gigya.Microdot.SharedLogic.HttpService; -using Newtonsoft.Json; namespace Gigya.Microdot.ServiceDiscovery.Config { @@ -130,6 +130,11 @@ public class DiscoveryConfig : IConfigObject public string EnvironmentFallbackTarget { get; set; } + public List CertificateErrorMessageSubstrings { get; set; } = new List() + { + "Element not found" + }; + [OnDeserialized] private void OnDeserialized(StreamingContext context) { diff --git a/Gigya.Microdot.ServiceDiscovery/Config/MethodCachingPolicyConfig.cs b/Gigya.Microdot.ServiceDiscovery/Config/MethodCachingPolicyConfig.cs index e3ff435e..08035c5e 100644 --- a/Gigya.Microdot.ServiceDiscovery/Config/MethodCachingPolicyConfig.cs +++ b/Gigya.Microdot.ServiceDiscovery/Config/MethodCachingPolicyConfig.cs @@ -1,6 +1,6 @@ +using Gigya.Common.Contracts.Attributes; using System; using System.Runtime.Serialization; -using Gigya.Common.Contracts.Attributes; namespace Gigya.Microdot.ServiceDiscovery.Config { diff --git a/Gigya.Microdot.ServiceDiscovery/Config/PortAllocationConfig.cs b/Gigya.Microdot.ServiceDiscovery/Config/PortAllocationConfig.cs index 56f3cc67..ee05bbb4 100644 --- a/Gigya.Microdot.ServiceDiscovery/Config/PortAllocationConfig.cs +++ b/Gigya.Microdot.ServiceDiscovery/Config/PortAllocationConfig.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.ComponentModel.DataAnnotations; using Gigya.Microdot.SharedLogic; +using System.ComponentModel.DataAnnotations; namespace Gigya.Microdot.ServiceDiscovery.Config { diff --git a/Gigya.Microdot.ServiceDiscovery/Config/ServiceDiscoveryCollection.cs b/Gigya.Microdot.ServiceDiscovery/Config/ServiceDiscoveryCollection.cs index aa0961bd..31b430cc 100644 --- a/Gigya.Microdot.ServiceDiscovery/Config/ServiceDiscoveryCollection.cs +++ b/Gigya.Microdot.ServiceDiscovery/Config/ServiceDiscoveryCollection.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Collections.Generic; using Gigya.Microdot.SharedLogic; +using System.Collections.Generic; namespace Gigya.Microdot.ServiceDiscovery.Config { diff --git a/Gigya.Microdot.ServiceDiscovery/Config/ServiceDiscoveryConfig.cs b/Gigya.Microdot.ServiceDiscovery/Config/ServiceDiscoveryConfig.cs index 50ee3c56..65954ab8 100644 --- a/Gigya.Microdot.ServiceDiscovery/Config/ServiceDiscoveryConfig.cs +++ b/Gigya.Microdot.ServiceDiscovery/Config/ServiceDiscoveryConfig.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.SharedLogic.HttpService; +using System; namespace Gigya.Microdot.ServiceDiscovery.Config { diff --git a/Gigya.Microdot.ServiceDiscovery/ConfigDiscoverySource.cs b/Gigya.Microdot.ServiceDiscovery/ConfigDiscoverySource.cs index 3f2c1ba3..dfb4b7e2 100644 --- a/Gigya.Microdot.ServiceDiscovery/ConfigDiscoverySource.cs +++ b/Gigya.Microdot.ServiceDiscovery/ConfigDiscoverySource.cs @@ -20,12 +20,12 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Linq; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.ServiceDiscovery.HostManagement; +using System; +using System.Linq; namespace Gigya.Microdot.ServiceDiscovery { diff --git a/Gigya.Microdot.ServiceDiscovery/ConsulClient.cs b/Gigya.Microdot.ServiceDiscovery/ConsulClient.cs index 42a1d48d..f71193a9 100644 --- a/Gigya.Microdot.ServiceDiscovery/ConsulClient.cs +++ b/Gigya.Microdot.ServiceDiscovery/ConsulClient.cs @@ -22,13 +22,6 @@ #endregion -using System; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; @@ -37,6 +30,13 @@ using Gigya.Microdot.SharedLogic.Monitor; using Metrics; using Newtonsoft.Json; +using System; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; #pragma warning disable 1591 namespace Gigya.Microdot.ServiceDiscovery @@ -131,7 +131,7 @@ private async Task LoadVersionLoop() else if (response.Error != null) delay = config.ErrorRetryInterval; - await _dateTime.Delay(delay).ConfigureAwait(false); + await _dateTime.Delay(delay, CancellationToken.None).ConfigureAwait(false); } else { @@ -162,7 +162,7 @@ private async Task LoadEndpointsLoop() if (consulResponse.Error != null) delay = config.ErrorRetryInterval; - await _dateTime.Delay(delay).ConfigureAwait(false); + await _dateTime.Delay(delay, CancellationToken.None).ConfigureAwait(false); } } diff --git a/Gigya.Microdot.ServiceDiscovery/ConsulContracts.cs b/Gigya.Microdot.ServiceDiscovery/ConsulContracts.cs index e2301981..24310826 100644 --- a/Gigya.Microdot.ServiceDiscovery/ConsulContracts.cs +++ b/Gigya.Microdot.ServiceDiscovery/ConsulContracts.cs @@ -1,9 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; +using Newtonsoft.Json; +using System; using System.Text; -using Gigya.Microdot.ServiceDiscovery.Rewrite; -using Newtonsoft.Json; namespace Gigya.Microdot.ServiceDiscovery { diff --git a/Gigya.Microdot.ServiceDiscovery/ConsulDiscoverySource.cs b/Gigya.Microdot.ServiceDiscovery/ConsulDiscoverySource.cs index a0c30eca..e8a2456e 100644 --- a/Gigya.Microdot.ServiceDiscovery/ConsulDiscoverySource.cs +++ b/Gigya.Microdot.ServiceDiscovery/ConsulDiscoverySource.cs @@ -20,17 +20,18 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.ServiceDiscovery.HostManagement; using Gigya.Microdot.ServiceDiscovery.Rewrite; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.ServiceDiscovery { @@ -91,7 +92,7 @@ public override Task Init() private async Task TimeoutIfNotReceivedFirstResult() { - await DateTime.Delay(TimeSpan.FromSeconds(10)); + await DateTime.Delay(TimeSpan.FromSeconds(10), CancellationToken.None); if (_firstResultInitialized.Task.GetAwaiter().IsCompleted) return; ConsulResultChanged(new EndPointsResult diff --git a/Gigya.Microdot.ServiceDiscovery/DeploymentIdentifier.cs b/Gigya.Microdot.ServiceDiscovery/DeploymentIdentifier.cs index a187cd8f..34bf4f64 100644 --- a/Gigya.Microdot.ServiceDiscovery/DeploymentIdentifier.cs +++ b/Gigya.Microdot.ServiceDiscovery/DeploymentIdentifier.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Gigya.Microdot.Interfaces.SystemWrappers; +using System; namespace Gigya.Microdot.ServiceDiscovery { @@ -68,7 +68,7 @@ public override string ToString() public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) + if (obj is null) return false; if (ReferenceEquals(this, obj)) diff --git a/Gigya.Microdot.ServiceDiscovery/DiscoverySourceLoader.cs b/Gigya.Microdot.ServiceDiscovery/DiscoverySourceLoader.cs index f67dd3e6..861f2885 100644 --- a/Gigya.Microdot.ServiceDiscovery/DiscoverySourceLoader.cs +++ b/Gigya.Microdot.ServiceDiscovery/DiscoverySourceLoader.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Linq; using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.SharedLogic.Exceptions; +using System; +using System.Linq; namespace Gigya.Microdot.ServiceDiscovery { diff --git a/Gigya.Microdot.ServiceDiscovery/Gigya.Microdot.ServiceDiscovery.csproj b/Gigya.Microdot.ServiceDiscovery/Gigya.Microdot.ServiceDiscovery.csproj index 6382dab6..a8d4e6d0 100644 --- a/Gigya.Microdot.ServiceDiscovery/Gigya.Microdot.ServiceDiscovery.csproj +++ b/Gigya.Microdot.ServiceDiscovery/Gigya.Microdot.ServiceDiscovery.csproj @@ -1,18 +1,28 @@  - - netstandard2.0 - Gigya.Microdot.ServiceDiscovery - $(SolutionDir)main.ruleset - - - - - - - - - - - + + Gigya.Microdot.ServiceDiscovery + + Using this component you can find other Microdot services (and any other + remote system), perform client-side load balancing between multiple + servers, detect and skip unresponsive servers and resume using them + when they return to full operation. Discovery is typically perfomed with + Consul by HashiCorp (http://consul.io) but it also supports manual server + lists specified in Microdot configuration (see NuGet package + Gigya.Microdot.Configuration) and can be expanded to support additional + service discovery systems. + + gigya microdot microservice microservices discovery service-discovery consul + + + + + + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.ServiceDiscovery/HostManagement/MissingHostException.cs b/Gigya.Microdot.ServiceDiscovery/HostManagement/MissingHostException.cs index a8d7d90d..d88c1462 100644 --- a/Gigya.Microdot.ServiceDiscovery/HostManagement/MissingHostException.cs +++ b/Gigya.Microdot.ServiceDiscovery/HostManagement/MissingHostException.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; using System; using System.Runtime.Serialization; -using Gigya.Common.Contracts.Exceptions; namespace Gigya.Microdot.ServiceDiscovery.HostManagement { diff --git a/Gigya.Microdot.ServiceDiscovery/HostManagement/OverriddenRemoteHost.cs b/Gigya.Microdot.ServiceDiscovery/HostManagement/OverriddenRemoteHost.cs index 055b53ad..2eb11667 100644 --- a/Gigya.Microdot.ServiceDiscovery/HostManagement/OverriddenRemoteHost.cs +++ b/Gigya.Microdot.ServiceDiscovery/HostManagement/OverriddenRemoteHost.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Gigya.Common.Contracts.Exceptions; +using System; namespace Gigya.Microdot.ServiceDiscovery.HostManagement { diff --git a/Gigya.Microdot.ServiceDiscovery/HostManagement/RemoteHost.cs b/Gigya.Microdot.ServiceDiscovery/HostManagement/RemoteHost.cs index 6d478947..46a2f2b8 100644 --- a/Gigya.Microdot.ServiceDiscovery/HostManagement/RemoteHost.cs +++ b/Gigya.Microdot.ServiceDiscovery/HostManagement/RemoteHost.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.Logging; using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; -using Gigya.Microdot.Interfaces.Logging; namespace Gigya.Microdot.ServiceDiscovery.HostManagement { diff --git a/Gigya.Microdot.ServiceDiscovery/HostManagement/RemoteHostPool.cs b/Gigya.Microdot.ServiceDiscovery/HostManagement/RemoteHostPool.cs index a553a10a..9482c6a2 100644 --- a/Gigya.Microdot.ServiceDiscovery/HostManagement/RemoteHostPool.cs +++ b/Gigya.Microdot.ServiceDiscovery/HostManagement/RemoteHostPool.cs @@ -20,12 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.ServiceDiscovery.Config; @@ -33,6 +27,12 @@ using Gigya.Microdot.SharedLogic.HttpService; using Gigya.Microdot.SharedLogic.Monitor; using Metrics; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.ServiceDiscovery.HostManagement { diff --git a/Gigya.Microdot.ServiceDiscovery/IServiceDiscovery.cs b/Gigya.Microdot.ServiceDiscovery/IServiceDiscovery.cs index e68a797f..b8f08ce5 100644 --- a/Gigya.Microdot.ServiceDiscovery/IServiceDiscovery.cs +++ b/Gigya.Microdot.ServiceDiscovery/IServiceDiscovery.cs @@ -20,12 +20,12 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.SharedLogic.HttpService; using System; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.SharedLogic.HttpService; namespace Gigya.Microdot.ServiceDiscovery { diff --git a/Gigya.Microdot.ServiceDiscovery/LocalDiscoverySource.cs b/Gigya.Microdot.ServiceDiscovery/LocalDiscoverySource.cs index 827f5e6b..2e0e6a80 100644 --- a/Gigya.Microdot.ServiceDiscovery/LocalDiscoverySource.cs +++ b/Gigya.Microdot.ServiceDiscovery/LocalDiscoverySource.cs @@ -20,11 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Net; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.ServiceDiscovery.HostManagement; using Gigya.Microdot.SharedLogic; +using System; namespace Gigya.Microdot.ServiceDiscovery { diff --git a/Gigya.Microdot.ServiceDiscovery/Properties/AssemblyInfo.cs b/Gigya.Microdot.ServiceDiscovery/Properties/AssemblyInfo.cs index 6026e14f..403dc97a 100644 --- a/Gigya.Microdot.ServiceDiscovery/Properties/AssemblyInfo.cs +++ b/Gigya.Microdot.ServiceDiscovery/Properties/AssemblyInfo.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/ConfigNodeSource.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/ConfigNodeSource.cs index b0ece487..21b413f6 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/ConfigNodeSource.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/ConfigNodeSource.cs @@ -20,13 +20,13 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Linq; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.ServiceDiscovery.HostManagement; using Gigya.Microdot.SharedLogic.Rewrite; +using System; +using System.Linq; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulClient.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulClient.cs index cbb31009..71035607 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulClient.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulClient.cs @@ -20,18 +20,18 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.SharedLogic; using Newtonsoft.Json; +using System; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { @@ -283,10 +283,7 @@ public void Dispose() { _httpClient.Dispose(); } - catch (Exception e) - { - - } + catch{} } } diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulNodeSource.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulNodeSource.cs index c8542c96..7f065c3e 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulNodeSource.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulNodeSource.cs @@ -20,26 +20,25 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.SharedLogic.Monitor; using Gigya.Microdot.SharedLogic.Rewrite; -using Metrics; +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { - /// - /// Monitors Consul using Health API and KeyValue API to find the current active version/instancename of a service, - /// and provides a list of up-to-date, healthy nodes. - /// - internal class ConsulNodeSource : INodeSource + /// + /// Monitors Consul using Health API and KeyValue API to find the current active version/instancename of a service, + /// and provides a list of up-to-date, healthy nodes. + /// + internal class ConsulNodeSource : INodeSource { private const int InitialModifyIndex = 0; private ILog Log { get; } diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulNodeSourceFactory.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulNodeSourceFactory.cs index ee669f98..265f5d6b 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulNodeSourceFactory.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulNodeSourceFactory.cs @@ -20,16 +20,15 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.SharedLogic.Monitor; using Metrics; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { @@ -117,7 +116,7 @@ private async void GetAllLoop() _initCompleted.TrySetResult(true); // If we got an error, we don't want to spam Consul so we wait a bit - if (consulResponse.Error != null) + if (consulResponse.Error != null && !_shutdownToken.IsCancellationRequested) await DateTime.Delay(GetConfig().ErrorRetryInterval, _shutdownToken.Token).ConfigureAwait(false); } } diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulResponse.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulResponse.cs index 0c4c35ad..7157ba65 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulResponse.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/ConsulResponse.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; using System; using System.Net; -using Gigya.Common.Contracts.Exceptions; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/Discovery.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/Discovery.cs index 5894c953..7acfbe42 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/Discovery.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/Discovery.cs @@ -20,16 +20,16 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.SystemWrappers; +using Gigya.Microdot.ServiceDiscovery.Config; +using Gigya.Microdot.SharedLogic.Exceptions; +using Gigya.Microdot.SharedLogic.Rewrite; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; -using Gigya.Microdot.Interfaces.SystemWrappers; -using Gigya.Microdot.ServiceDiscovery.Config; -using Gigya.Microdot.SharedLogic.Exceptions; -using Gigya.Microdot.SharedLogic.Rewrite; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { @@ -169,27 +169,37 @@ private string GetConfiguredSourceType(DeploymentIdentifier deploymentIdentifier // differs from configuration. private async void CleanupLoop() { - while (!_shutdownTokenSource.Token.IsCancellationRequested) + try { - try + while (!_shutdownTokenSource.Token.IsCancellationRequested) { - var expiryTime = DateTime.UtcNow - GetConfig().MonitoringLifetime; - - foreach (var nodeSource in _nodeSources) - if ( nodeSource.Value.Value.LastAccessTime < expiryTime - || nodeSource.Value.Value.NodeSourceType != GetConfiguredSourceType(nodeSource.Key) - || !await IsServiceDeployed(nodeSource.Key).ConfigureAwait(false)) - { - #pragma warning disable 4014 - nodeSource.Value.Value.NodeSourceTask.ContinueWith(t => t.Result.Dispose()); - #pragma warning restore 4014 - _nodeSources.TryRemove(nodeSource.Key, out _); - } - - await DateTime.Delay(TimeSpan.FromSeconds(1), _shutdownTokenSource.Token); + try + { + var expiryTime = DateTime.UtcNow - GetConfig().MonitoringLifetime; + + foreach (var nodeSource in _nodeSources) + if (nodeSource.Value.Value.LastAccessTime < expiryTime + || nodeSource.Value.Value.NodeSourceType != GetConfiguredSourceType(nodeSource.Key) + || !await IsServiceDeployed(nodeSource.Key).ConfigureAwait(false)) + { +#pragma warning disable 4014 + nodeSource.Value.Value.NodeSourceTask.ContinueWith(t => t.Result.Dispose()); +#pragma warning restore 4014 + _nodeSources.TryRemove(nodeSource.Key, out _); + } + + await DateTime.Delay(TimeSpan.FromSeconds(1), _shutdownTokenSource.Token); + } + catch + { + } // Shouldn't happen, but just in case. Cleanup musn't stop. } - catch {} // Shouldn't happen, but just in case. Cleanup musn't stop. } + catch(ObjectDisposedException) + { + //Can happen on host shutdown. + } + } diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/IDiscovery.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/IDiscovery.cs index c381ac10..04061a05 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/IDiscovery.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/IDiscovery.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic.Rewrite; using System; using System.Threading.Tasks; -using Gigya.Microdot.SharedLogic.Rewrite; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/ILoadBalancer.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/ILoadBalancer.cs index 76d065b5..1130713f 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/ILoadBalancer.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/ILoadBalancer.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Threading.Tasks; using Gigya.Microdot.ServiceDiscovery.HostManagement; using Gigya.Microdot.SharedLogic.Rewrite; +using System; +using System.Threading.Tasks; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/IMultiEnvironmentServiceDiscovery.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/IMultiEnvironmentServiceDiscovery.cs index 120ee5d9..9aeae2b5 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/IMultiEnvironmentServiceDiscovery.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/IMultiEnvironmentServiceDiscovery.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Threading.Tasks; using Gigya.Microdot.ServiceDiscovery.HostManagement; using Gigya.Microdot.SharedLogic.Rewrite; +using System; +using System.Threading.Tasks; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/INodeSource.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/INodeSource.cs index c5b43dc0..f675f4b9 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/INodeSource.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/INodeSource.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.SharedLogic.Rewrite; +using System; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/LoadBalancer.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/LoadBalancer.cs index b2da7227..af205bb2 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/LoadBalancer.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/LoadBalancer.cs @@ -20,20 +20,21 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Threading; -using System.Threading.Tasks; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; +using Gigya.Microdot.LanguageExtensions; using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.ServiceDiscovery.HostManagement; using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.Monitor; using Gigya.Microdot.SharedLogic.Rewrite; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Threading; +using System.Threading.Tasks; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { @@ -136,7 +137,7 @@ private uint GetIndexByTrafficRoutingStrategy() case TrafficRoutingStrategy.RoundRobin: return (uint)Interlocked.Increment(ref _roundRobinIndex); case TrafficRoutingStrategy.RandomByRequestID: - return (uint?)TracingContext.TryGetRequestID()?.GetHashCode() ?? (uint)Interlocked.Increment(ref _roundRobinIndex); + return (uint?)TracingContext.TryGetRequestID()?.GetDeterministicHashCode() ?? (uint)Interlocked.Increment(ref _roundRobinIndex); default: throw new ProgrammaticException($"The {nameof(TrafficRoutingStrategy)} '{TrafficRoutingStrategy}' is not supported by LoadBalancer."); } diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/MultiEnvironmentServiceDiscovery.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/MultiEnvironmentServiceDiscovery.cs index a239050f..ca8013e9 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/MultiEnvironmentServiceDiscovery.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/MultiEnvironmentServiceDiscovery.cs @@ -20,9 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Concurrent; -using System.Threading.Tasks; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery.Config; @@ -30,7 +27,9 @@ using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.Monitor; using Gigya.Microdot.SharedLogic.Rewrite; -using Metrics; +using System; +using System.Collections.Concurrent; +using System.Threading.Tasks; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/NodeMonitoringState.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/NodeMonitoringState.cs index 06cc4d25..172937c4 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/NodeMonitoringState.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/NodeMonitoringState.cs @@ -20,11 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.Logging; +using Gigya.Microdot.SharedLogic.Rewrite; using System; using System.Threading; using System.Threading.Tasks; -using Gigya.Microdot.Interfaces.Logging; -using Gigya.Microdot.SharedLogic.Rewrite; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { diff --git a/Gigya.Microdot.ServiceDiscovery/Rewrite/ReachabilityCheck.cs b/Gigya.Microdot.ServiceDiscovery/Rewrite/ReachabilityCheck.cs index 36dd4e4d..35b27cb6 100644 --- a/Gigya.Microdot.ServiceDiscovery/Rewrite/ReachabilityCheck.cs +++ b/Gigya.Microdot.ServiceDiscovery/Rewrite/ReachabilityCheck.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic.Rewrite; using System.Threading; using System.Threading.Tasks; -using Gigya.Microdot.SharedLogic.Rewrite; namespace Gigya.Microdot.ServiceDiscovery.Rewrite { diff --git a/Gigya.Microdot.ServiceDiscovery/ServiceDiscovery.cs b/Gigya.Microdot.ServiceDiscovery/ServiceDiscovery.cs index 5defd0bf..cadcaf66 100644 --- a/Gigya.Microdot.ServiceDiscovery/ServiceDiscovery.cs +++ b/Gigya.Microdot.ServiceDiscovery/ServiceDiscovery.cs @@ -20,19 +20,17 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.Logging; +using Gigya.Microdot.Interfaces.SystemWrappers; +using Gigya.Microdot.ServiceDiscovery.Config; +using Gigya.Microdot.ServiceDiscovery.HostManagement; +using Gigya.Microdot.SharedLogic.HttpService; using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; -using Gigya.Microdot.Interfaces.Configuration; -using Gigya.Microdot.Interfaces.Logging; -using Gigya.Microdot.Interfaces.SystemWrappers; -using Gigya.Microdot.ServiceDiscovery.Config; -using Gigya.Microdot.ServiceDiscovery.HostManagement; -using Gigya.Microdot.SharedLogic.HttpService; namespace Gigya.Microdot.ServiceDiscovery { @@ -88,7 +86,8 @@ public ServiceDiscovery(string serviceName, _environment = environment; // Must be run in Task.Run() because of incorrect Orleans scheduling - _initTask = Task.Run(() => ReloadRemoteHost(discoveryConfigFactory())); + // todo: this is temporary, we need to figure out whether we want this change or not + _initTask = Task.Run(async () => await ReloadRemoteHost(discoveryConfigFactory())); _configBlockLink = configListener.LinkTo(new ActionBlock(ReloadRemoteHost)); } diff --git a/Gigya.Microdot.ServiceDiscovery/paket.references b/Gigya.Microdot.ServiceDiscovery/paket.references deleted file mode 100644 index 1d0f7ca8..00000000 --- a/Gigya.Microdot.ServiceDiscovery/paket.references +++ /dev/null @@ -1,9 +0,0 @@ -Gigya.ServiceContract -Nito.AsyncEx -Newtonsoft.Json -Microsoft.CSharp -System.Collections.Immutable -System.ComponentModel.Annotations -System.Net.Http -System.Threading.Tasks.Dataflow -System.ValueTuple diff --git a/Gigya.Microdot.ServiceDiscovery/paket.template b/Gigya.Microdot.ServiceDiscovery/paket.template deleted file mode 100644 index d72605bc..00000000 --- a/Gigya.Microdot.ServiceDiscovery/paket.template +++ /dev/null @@ -1,17 +0,0 @@ -type - project -description - Using this component you can find other Microdot services (and any other - remote system), perform client-side load balancing between multiple - servers, detect and skip unresponsive servers and resume using them - when they return to full operation. Discovery is typically perfomed with - Consul by HashiCorp (http://consul.io) but it also supports manual server - lists specified in Microdot configuration (see NuGet package - Gigya.Microdot.Configuration) and can be expanded to support additional - service discovery systems. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices discovery service-discovery consul \ No newline at end of file diff --git a/Gigya.Microdot.ServiceProxy/Caching/AsyncCache.cs b/Gigya.Microdot.ServiceProxy/Caching/AsyncCache.cs index e1f29d8c..cfa2e8c3 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/AsyncCache.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/AsyncCache.cs @@ -20,6 +20,13 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Attributes; +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.Interfaces.Logging; +using Gigya.Microdot.Interfaces.SystemWrappers; +using Gigya.Microdot.SharedLogic.Events; +using Gigya.ServiceContract.HttpService; +using Metrics; using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -29,15 +36,7 @@ using System.Runtime.Caching.Hosting; using System.Threading; using System.Threading.Tasks; -using Gigya.Microdot.Interfaces.Logging; -using Gigya.Microdot.Interfaces.SystemWrappers; -using Gigya.ServiceContract.HttpService; -using Metrics; using System.Threading.Tasks.Dataflow; -using Gigya.Common.Contracts.Attributes; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.SharedLogic.Events; -using Gigya.Microdot.ServiceDiscovery.Config; namespace Gigya.Microdot.ServiceProxy.Caching { diff --git a/Gigya.Microdot.ServiceProxy/Caching/AsyncMemoizer.cs b/Gigya.Microdot.ServiceProxy/Caching/AsyncMemoizer.cs index 80349880..27ee7229 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/AsyncMemoizer.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/AsyncMemoizer.cs @@ -20,18 +20,16 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.IO; -using System.Reflection; -using System.Security.Cryptography; -using System.Threading.Tasks; using Gigya.Common.Contracts.Attributes; using Gigya.Microdot.LanguageExtensions; -using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.SharedLogic.HttpService; -using Gigya.ServiceContract.HttpService; using Metrics; using Newtonsoft.Json; +using System; +using System.IO; +using System.Reflection; +using System.Security.Cryptography; +using System.Threading.Tasks; namespace Gigya.Microdot.ServiceProxy.Caching { @@ -78,8 +76,8 @@ private string GetArgumentHash(object[] args) { var stream = new MemoryStream(); using (ComputeArgumentHash.NewContext()) - using (var writer = new StreamWriter(stream) { AutoFlush = true }) - using (SHA1 sha = new SHA1CryptoServiceProvider()) + using (var writer = new StreamWriter(stream) { AutoFlush = true }) + using (SHA1 sha = SHA1.Create()) { JsonSerializer.Create().Serialize(writer, args); stream.Seek(0, SeekOrigin.Begin); @@ -91,6 +89,7 @@ public void Dispose() { Cache.TryDispose(); Metrics.TryDispose(); + GC.SuppressFinalize(this); } } } \ No newline at end of file diff --git a/Gigya.Microdot.ServiceProxy/Caching/CacheConfig.cs b/Gigya.Microdot.ServiceProxy/Caching/CacheConfig.cs index 8b67fcc1..41b23441 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/CacheConfig.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/CacheConfig.cs @@ -1,6 +1,6 @@ -using System; +using Gigya.Microdot.Interfaces.Configuration; +using System; using System.Collections.Generic; -using Gigya.Microdot.Interfaces.Configuration; namespace Gigya.Microdot.ServiceProxy.Caching { diff --git a/Gigya.Microdot.ServiceProxy/Caching/CachingProxyProvider.cs b/Gigya.Microdot.ServiceProxy/Caching/CachingProxyProvider.cs index fb37d4e4..eb9a698a 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/CachingProxyProvider.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/CachingProxyProvider.cs @@ -20,15 +20,14 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Concurrent; -using System.Reflection; using Gigya.Common.Contracts.Attributes; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery.Config; -using Gigya.Microdot.System_Reflection.DispatchProxy; using Gigya.ServiceContract.HttpService; +using System; +using System.Collections.Concurrent; +using System.Reflection; namespace Gigya.Microdot.ServiceProxy.Caching { @@ -41,13 +40,13 @@ public class CachingProxyProvider : ICachingProxyProvider public TInterface Proxy { get; } - + /// /// The instance of the actual data source, used when the data is not present in the cache. /// public TInterface DataSource { get; } - - + + private IMemoizer Memoizer { get; } private IMetadataProvider MetadataProvider { get; } private ILog Log { get; } @@ -56,8 +55,8 @@ public class CachingProxyProvider : ICachingProxyProvider CachingConfigPerMethod = new ConcurrentDictionary(); - - + + public CachingProxyProvider(TInterface dataSource, IMemoizer memoizer, IMetadataProvider metadataProvider, Func getDiscoveryConfig, ILog log, IDateTime dateTime, string serviceName) { DataSource = dataSource; @@ -66,22 +65,22 @@ public CachingProxyProvider(TInterface dataSource, IMemoizer memoizer, IMetadata GetDiscoveryConfig = getDiscoveryConfig; Log = log; DateTime = dateTime; - + Proxy = DispatchProxy.Create(); ((DelegatingDispatchProxy)(object)Proxy).InvokeDelegate = Invoke; ServiceName = serviceName ?? typeof(TInterface).GetServiceName(); } - - + + private MethodCachingPolicyConfig GetConfig(MethodInfo targetMethod, string methodName, object[] args) { GetDiscoveryConfig().Services.TryGetValue(ServiceName, out ServiceDiscoveryConfig discoveryConfig); - + var serviceCachingConfig = discoveryConfig?.CachingPolicy; - + MethodCachingPolicyConfig methodCachingConfig = null; serviceCachingConfig?.Methods?.TryGetValue(methodName, out methodCachingConfig); - + if (CachingConfigPerMethod.TryGetValue(methodName, out var cachedMethodConfigTuple) && ReferenceEquals(serviceCachingConfig, cachedMethodConfigTuple.serviceConfig) && ReferenceEquals(methodCachingConfig, cachedMethodConfigTuple.methodConfig)) @@ -91,80 +90,80 @@ private MethodCachingPolicyConfig GetConfig(MethodInfo targetMethod, string meth else { var effMethodConfig = new MethodCachingPolicyConfig(); - + //method config if (methodCachingConfig != null) MethodCachingPolicyConfig.Merge(methodCachingConfig, effMethodConfig); - + //attribute var cachedAttribute = TryGetCachedAttribute(targetMethod, args); if (cachedAttribute != null) MethodCachingPolicyConfig.Merge(new MethodCachingPolicyConfig(cachedAttribute), effMethodConfig); - + //service config if (serviceCachingConfig != null) MethodCachingPolicyConfig.Merge(serviceCachingConfig, effMethodConfig); - + //defaults MethodCachingPolicyConfig.Merge(CachingPolicyConfig.Default, effMethodConfig); ApplyDynamicDefaults(targetMethod, effMethodConfig, args); - + //Note: In case we want to add config validations (like we have in CacheAttribute), we can do it here and use Func getAggregatedHealthCheck //If validation failed, we wont update the cache, and preserve the error in CachingConfigPerMethod entry value //HealthCheck func will set 'Bad' state in case an error exist in any entry. Otherwise it will set 'Good' //The error will be cleaned (after config fix), either by a call made to GetConfig with specific methodName //Or (if no call to the specific methodName was made), by a timer that cleans old errors from CachingConfigPerMethod - + // Add to cache and return CachingConfigPerMethod[methodName] = (serviceCachingConfig, methodCachingConfig, effMethodConfig); return effMethodConfig; } } - + //Note! Following methods are overriden in Gator as it is not using MetadataProvider in 'Generic' flow - + protected virtual string GetMethodNameForCachingPolicy(MethodInfo targetMethod, object[] args) { return targetMethod.Name; } - + protected virtual bool IsMethodCached(MethodInfo targetMethod, object[] args) { return MetadataProvider.IsCached(targetMethod); } - + protected virtual CachedAttribute TryGetCachedAttribute(MethodInfo targetMethod, object[] args) { return MetadataProvider.GetCachedAttribute(targetMethod); } - + protected virtual Type TryGetMethodTaskResultType(MethodInfo targetMethod, object[] args) { return MetadataProvider.GetMethodTaskResultType(targetMethod); } - + ///////////////////////////////////////////////////////////////////////////////////////////////////////// - - + + private object Invoke(MethodInfo targetMethod, object[] args) { var config = GetConfig(targetMethod, GetMethodNameForCachingPolicy(targetMethod, args), args); bool useCache = config.Enabled == true && IsMethodCached(targetMethod, args); - + if (useCache) return Memoizer.Memoize(DataSource, targetMethod, args, config); else return targetMethod.Invoke(DataSource, args); } - - + + // For methods returning Revocable<> responses, we assume they issue manual cache revokes. If the caching settings do not // define explicit RefreshMode and ExpirationBehavior, then for Revocable<> methods we don't use refreshes and use a sliding // expiration. For non-Revocable<> we do use refreshes and a fixed expiration. private void ApplyDynamicDefaults(MethodInfo targetMethod, MethodCachingPolicyConfig effMethodConfig, object[] args) { bool isRevocable = false; - + try { var taskResultType = TryGetMethodTaskResultType(targetMethod, args); @@ -174,16 +173,16 @@ private void ApplyDynamicDefaults(MethodInfo targetMethod, MethodCachingPolicyCo { Log.Error("Error retrieving result type", exception: e); } - + if (effMethodConfig.RefreshMode == 0) if (isRevocable) effMethodConfig.RefreshMode = RefreshMode.UseRefreshes; //TODO: change to RefreshMode.UseRefreshesWhenDisconnectedFromCacheRevokesBus after disconnect from bus feature is developed else effMethodConfig.RefreshMode = RefreshMode.UseRefreshes; - + if (effMethodConfig.ExpirationBehavior == 0) if (isRevocable) effMethodConfig.ExpirationBehavior = ExpirationBehavior.DoNotExtendExpirationWhenReadFromCache; //TODO: change to ExpirationBehavior.ExtendExpirationWhenReadFromCache after disconnect from bus feature is developed else effMethodConfig.ExpirationBehavior = ExpirationBehavior.DoNotExtendExpirationWhenReadFromCache; } } -} +} \ No newline at end of file diff --git a/Gigya.Microdot.ServiceProxy/Caching/ICache.cs b/Gigya.Microdot.ServiceProxy/Caching/ICache.cs index 614da599..bb9d2c73 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/ICache.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/ICache.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Runtime.Caching; using Nito.AsyncEx; +using System.Runtime.Caching; namespace Gigya.Microdot.ServiceProxy.Caching { diff --git a/Gigya.Microdot.ServiceProxy/Caching/IMemoizer.cs b/Gigya.Microdot.ServiceProxy/Caching/IMemoizer.cs index 03552186..fcb53612 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/IMemoizer.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/IMemoizer.cs @@ -20,10 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Attributes; using System; using System.Reflection; -using Gigya.Common.Contracts.Attributes; -using Gigya.Microdot.ServiceDiscovery.Config; namespace Gigya.Microdot.ServiceProxy.Caching { diff --git a/Gigya.Microdot.ServiceProxy/Caching/IRevokeListener.cs b/Gigya.Microdot.ServiceProxy/Caching/IRevokeListener.cs index 4af83153..74b089a8 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/IRevokeListener.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/IRevokeListener.cs @@ -24,7 +24,7 @@ namespace Gigya.Microdot.ServiceProxy.Caching { - public interface IRevokeListener + public interface IRevokeListener { ISourceBlock RevokeSource { get; } } diff --git a/Gigya.Microdot.ServiceProxy/Caching/MetadataProvider.cs b/Gigya.Microdot.ServiceProxy/Caching/MetadataProvider.cs index 7efe2a13..8229bf27 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/MetadataProvider.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/MetadataProvider.cs @@ -20,12 +20,12 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Attributes; using System; using System.Collections.Concurrent; using System.Linq; using System.Reflection; using System.Threading.Tasks; -using Gigya.Common.Contracts.Attributes; namespace Gigya.Microdot.ServiceProxy.Caching { diff --git a/Gigya.Microdot.ServiceProxy/Caching/MetricsExtensions.cs b/Gigya.Microdot.ServiceProxy/Caching/MetricsExtensions.cs index 930a6d96..850a68fa 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/MetricsExtensions.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/MetricsExtensions.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Linq; using Metrics; +using System.Linq; namespace Gigya.Microdot.ServiceProxy.Caching { diff --git a/Gigya.Microdot.ServiceProxy/Caching/RecentRevokesCache.cs b/Gigya.Microdot.ServiceProxy/Caching/RecentRevokesCache.cs index 73107602..0db41fc1 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/RecentRevokesCache.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/RecentRevokesCache.cs @@ -1,12 +1,10 @@ -using System; +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.Interfaces.Logging; +using Metrics; +using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Text; using System.Threading; using System.Threading.Tasks; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.Interfaces.Logging; -using Metrics; namespace Gigya.Microdot.ServiceProxy.Caching { diff --git a/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/IRevokeKey.cs b/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/IRevokeKey.cs index 5036ed6e..ea621b79 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/IRevokeKey.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/IRevokeKey.cs @@ -1,5 +1,4 @@ -using System; -using System.Threading.Tasks; +using System.Threading.Tasks; namespace Gigya.Microdot.ServiceProxy.Caching.RevokeNotifier { diff --git a/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/IRevokeKeyIndexerFactory.cs b/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/IRevokeKeyIndexerFactory.cs index 0b529e8c..42fbff56 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/IRevokeKeyIndexerFactory.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/IRevokeKeyIndexerFactory.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Gigya.Microdot.ServiceProxy.Caching.RevokeNotifier +namespace Gigya.Microdot.ServiceProxy.Caching.RevokeNotifier { public interface IRevokeKeyIndexerFactory { diff --git a/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/IRevokeNotifier.cs b/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/IRevokeNotifier.cs index 051f1d39..7be003e9 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/IRevokeNotifier.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/IRevokeNotifier.cs @@ -1,7 +1,4 @@ -using System; -using System.Threading.Tasks; - -namespace Gigya.Microdot.ServiceProxy.Caching.RevokeNotifier +namespace Gigya.Microdot.ServiceProxy.Caching.RevokeNotifier { public interface IRevokeNotifier { diff --git a/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/RevokeKeyIndexer.cs b/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/RevokeKeyIndexer.cs index 72812dd0..11559a65 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/RevokeKeyIndexer.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/RevokeKeyIndexer.cs @@ -1,8 +1,8 @@ -using System; +using Gigya.Microdot.Interfaces.Logging; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using Gigya.Microdot.Interfaces.Logging; namespace Gigya.Microdot.ServiceProxy.Caching.RevokeNotifier { diff --git a/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/RevokeNotifier.cs b/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/RevokeNotifier.cs index ef5a3baa..6346f963 100644 --- a/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/RevokeNotifier.cs +++ b/Gigya.Microdot.ServiceProxy/Caching/RevokeNotifier/RevokeNotifier.cs @@ -1,8 +1,7 @@ -using System; +using Gigya.Microdot.Interfaces.Logging; +using System; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; -using Gigya.Microdot.Interfaces.Logging; -using Metrics; using Timer = System.Threading.Timer; namespace Gigya.Microdot.ServiceProxy.Caching.RevokeNotifier diff --git a/Gigya.Microdot.ServiceProxy/CoreFX/DispatchProxy/DispatchProxy.cs b/Gigya.Microdot.ServiceProxy/CoreFX/DispatchProxy/DispatchProxy.cs deleted file mode 100644 index 9a476636..00000000 --- a/Gigya.Microdot.ServiceProxy/CoreFX/DispatchProxy/DispatchProxy.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Reflection; - -namespace Gigya.Microdot.System_Reflection.DispatchProxy -{ - /// - /// DispatchProxy provides a mechanism for the instantiation of proxy objects and handling of - /// their method dispatch. - /// - public abstract class DispatchProxy - { - protected DispatchProxy() - { - } - - /// - /// Whenever any method on the generated proxy type is called, this method - /// will be invoked to dispatch control. - /// - /// The method the caller invoked - /// The arguments the caller passed to the method - /// The object to return to the caller, or null for void methods - protected abstract object Invoke(MethodInfo targetMethod, object[] args); - - /// - /// Creates an object instance that derives from class - /// and implements interface . - /// - /// The interface the proxy should implement. - /// The base class to use for the proxy class. - /// An object instance that implements . - /// is a class, - /// or is sealed or does not have a parameterless constructor - public static T Create() - where TProxy : DispatchProxy - { - return (T)DispatchProxyGenerator.CreateProxyInstance(typeof(TProxy), typeof(T)); - } - } -} - diff --git a/Gigya.Microdot.ServiceProxy/CoreFX/DispatchProxy/DispatchProxyGenerator.cs b/Gigya.Microdot.ServiceProxy/CoreFX/DispatchProxy/DispatchProxyGenerator.cs deleted file mode 100644 index 3615d34b..00000000 --- a/Gigya.Microdot.ServiceProxy/CoreFX/DispatchProxy/DispatchProxyGenerator.cs +++ /dev/null @@ -1,832 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.ExceptionServices; -using System.Threading; - -namespace Gigya.Microdot.System_Reflection.DispatchProxy -{ - // Helper class to handle the IL EMIT for the generation of proxies. - // Much of this code was taken directly from the Silverlight proxy generation. - // Differences beteen this and the Silverlight version are: - // 1. This version is based on DispatchProxy from NET Native and CoreCLR, not RealProxy in Silverlight ServiceModel. - // There are several notable differences between them. - // 2. Both DispatchProxy and RealProxy permit the caller to ask for a proxy specifying a pair of types: - // the interface type to implement, and a base type. But they behave slightly differently: - // - RealProxy generates a proxy type that derives from Object and *implements" all the base type's - // interfaces plus all the interface type's interfaces. - // - DispatchProxy generates a proxy type that *derives* from the base type and implements all - // the interface type's interfaces. This is true for both the CLR version in NET Native and this - // version for CoreCLR. - // 3. DispatchProxy and RealProxy use different type hierarchies for the generated proxies: - // - RealProxy type hierarchy is: - // proxyType : proxyBaseType : object - // Presumably the 'proxyBaseType' in the middle is to allow it to implement the base type's interfaces - // explicitly, preventing collision for same name methods on the base and interface types. - // - DispatchProxy hierarchy is: - // proxyType : baseType (where baseType : DispatchProxy) - // The generated DispatchProxy proxy type does not need to generate implementation methods - // for the base type's interfaces, because the base type already must have implemented them. - // 4. RealProxy required a proxy instance to hold a backpointer to the RealProxy instance to mirror - // the .Net Remoting design that required the proxy and RealProxy to be separate instances. - // But the DispatchProxy design encourages the proxy type to *be* an DispatchProxy. Therefore, - // the proxy's 'this' becomes the equivalent of RealProxy's backpointer to RealProxy, so we were - // able to remove an extraneous field and ctor arg from the DispatchProxy proxies. - // - internal static class DispatchProxyGenerator - { - // Generated proxies have a private Action field that all generated methods - // invoke. It is the first field in the class and the first ctor parameter. - private const int InvokeActionFieldAndCtorParameterIndex = 0; - - // Proxies are requested for a pair of types: base type and interface type. - // The generated proxy will subclass the given base type and implement the interface type. - // We maintain a cache keyed by 'base type' containing a dictionary keyed by interface type, - // containing the generated proxy type for that pair. There are likely to be few (maybe only 1) - // base type in use for many interface types. - // Note: this differs from Silverlight's RealProxy implementation which keys strictly off the - // interface type. But this does not allow the same interface type to be used with more than a - // single base type. The implementation here permits multiple interface types to be used with - // multiple base types, and the generated proxy types will be unique. - // This cache of generated types grows unbounded, one element per unique T/ProxyT pair. - // This approach is used to prevent regenerating identical proxy types for identical T/Proxy pairs, - // which would ultimately be a more expensive leak. - // Proxy instances are not cached. Their lifetime is entirely owned by the caller of DispatchProxy.Create. - private static readonly Dictionary> s_baseTypeAndInterfaceToGeneratedProxyType = new Dictionary>(); - private static readonly ProxyAssembly s_proxyAssembly = new ProxyAssembly(); - private static readonly MethodInfo s_dispatchProxyInvokeMethod = typeof(DispatchProxy).GetTypeInfo().GetDeclaredMethod("Invoke"); - - // Returns a new instance of a proxy the derives from 'baseType' and implements 'interfaceType' - internal static object CreateProxyInstance(Type baseType, Type interfaceType) - { - Debug.Assert(baseType != null); - Debug.Assert(interfaceType != null); - - Type proxiedType = GetProxyType(baseType, interfaceType); - return Activator.CreateInstance(proxiedType, (Action)DispatchProxyGenerator.Invoke); - } - - private static Type GetProxyType(Type baseType, Type interfaceType) - { - lock (s_baseTypeAndInterfaceToGeneratedProxyType) - { - if (!s_baseTypeAndInterfaceToGeneratedProxyType.TryGetValue(baseType, out Dictionary interfaceToProxy)) - { - interfaceToProxy = new Dictionary(); - s_baseTypeAndInterfaceToGeneratedProxyType[baseType] = interfaceToProxy; - } - - if (!interfaceToProxy.TryGetValue(interfaceType, out Type generatedProxy)) - { - generatedProxy = GenerateProxyType(baseType, interfaceType); - interfaceToProxy[interfaceType] = generatedProxy; - } - - return generatedProxy; - } - } - - // Unconditionally generates a new proxy type derived from 'baseType' and implements 'interfaceType' - private static Type GenerateProxyType(Type baseType, Type interfaceType) - { - // Parameter validation is deferred until the point we need to create the proxy. - // This prevents unnecessary overhead revalidating cached proxy types. - TypeInfo baseTypeInfo = baseType.GetTypeInfo(); - - // The interface type must be an interface, not a class - if (!interfaceType.GetTypeInfo().IsInterface) - { - // "T" is the generic parameter seen via the public contract - throw new ArgumentException(String.Format("The type '{0}' must be an interface, not a class.", interfaceType.FullName), "T"); - } - - // The base type cannot be sealed because the proxy needs to subclass it. - if (baseTypeInfo.IsSealed) - { - // "TProxy" is the generic parameter seen via the public contract - throw new ArgumentException(String.Format("The base type '{0}' cannot be sealed.", baseTypeInfo.FullName), "TProxy"); - } - - // The base type cannot be abstract - if (baseTypeInfo.IsAbstract) - { - throw new ArgumentException(String.Format("The base type '{0}' cannot be abstract.", baseType.FullName), "TProxy"); - } - - // The base type must have a public default ctor - if (!baseTypeInfo.DeclaredConstructors.Any(c => c.IsPublic && c.GetParameters().Length == 0)) - { - throw new ArgumentException(String.Format("The base type '{0}' must have a public parameterless constructor.", baseType.FullName), "TProxy"); - } - - // Create a type that derives from 'baseType' provided by caller - ProxyBuilder pb = s_proxyAssembly.CreateProxy("generatedProxy", baseType); - - foreach (Type t in interfaceType.GetTypeInfo().ImplementedInterfaces) - pb.AddInterfaceImpl(t); - - pb.AddInterfaceImpl(interfaceType); - - Type generatedProxyType = pb.CreateType(); - return generatedProxyType; - } - - // All generated proxy methods call this static helper method to dispatch. - // Its job is to unpack the arguments and the 'this' instance and to dispatch directly - // to the (abstract) DispatchProxy.Invoke() method. - private static void Invoke(object[] args) - { - PackedArgs packed = new PackedArgs(args); - MethodBase method = s_proxyAssembly.ResolveMethodToken(packed.DeclaringType, packed.MethodToken); - if (method.IsGenericMethodDefinition) - method = ((MethodInfo)method).MakeGenericMethod(packed.GenericTypes); - - // Call (protected method) DispatchProxy.Invoke() - try - { - Debug.Assert(s_dispatchProxyInvokeMethod != null); - object returnValue = s_dispatchProxyInvokeMethod.Invoke(packed.DispatchProxy, - new object[] { method, packed.Args }); - packed.ReturnValue = returnValue; - } - catch (TargetInvocationException tie) - { - ExceptionDispatchInfo.Capture(tie.InnerException).Throw(); - } - } - - private class PackedArgs - { - internal const int DispatchProxyPosition = 0; - internal const int DeclaringTypePosition = 1; - internal const int MethodTokenPosition = 2; - internal const int ArgsPosition = 3; - internal const int GenericTypesPosition = 4; - internal const int ReturnValuePosition = 5; - - internal static readonly Type[] PackedTypes = new Type[] { typeof(object), typeof(Type), typeof(int), typeof(object[]), typeof(Type[]), typeof(object) }; - - private object[] _args; - internal PackedArgs() : this(new object[PackedTypes.Length]) { } - internal PackedArgs(object[] args) { _args = args; } - - internal DispatchProxy DispatchProxy { get { return (DispatchProxy)_args[DispatchProxyPosition]; } } - internal Type DeclaringType { get { return (Type)_args[DeclaringTypePosition]; } } - internal int MethodToken { get { return (int)_args[MethodTokenPosition]; } } - internal object[] Args { get { return (object[])_args[ArgsPosition]; } } - internal Type[] GenericTypes { get { return (Type[])_args[GenericTypesPosition]; } } - internal object ReturnValue { /*get { return args[ReturnValuePosition]; }*/ set { _args[ReturnValuePosition] = value; } } - } - - private class ProxyAssembly - { - private AssemblyBuilder _ab; - private ModuleBuilder _mb; - private int _typeId = 0; - - // Maintain a MethodBase-->int, int-->MethodBase mapping to permit generated code - // to pass methods by token - private Dictionary _methodToToken = new Dictionary(); - private List _methodsByToken = new List(); - private HashSet _ignoresAccessAssemblyNames = new HashSet(); - private ConstructorInfo _ignoresAccessChecksToAttributeConstructor; - - public ProxyAssembly() - { - _ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ProxyBuilder"), AssemblyBuilderAccess.Run); - _mb = _ab.DefineDynamicModule("testmod"); - } - - // Gets or creates the ConstructorInfo for the IgnoresAccessChecksAttribute. - // This attribute is both defined and referenced in the dynamic assembly to - // allow access to internal types in other assemblies. - internal ConstructorInfo IgnoresAccessChecksAttributeConstructor - { - get - { - if (_ignoresAccessChecksToAttributeConstructor == null) - { - TypeInfo attributeTypeInfo = GenerateTypeInfoOfIgnoresAccessChecksToAttribute(); - _ignoresAccessChecksToAttributeConstructor = attributeTypeInfo.DeclaredConstructors.Single(); - } - - return _ignoresAccessChecksToAttributeConstructor; - } - } - public ProxyBuilder CreateProxy(string name, Type proxyBaseType) - { - int nextId = Interlocked.Increment(ref _typeId); - TypeBuilder tb = _mb.DefineType(name + "_" + nextId, TypeAttributes.Public, proxyBaseType); - return new ProxyBuilder(this, tb, proxyBaseType); - } - - // Generate the declaration for the IgnoresAccessChecksToAttribute type. - // This attribute will be both defined and used in the dynamic assembly. - // Each usage identifies the name of the assembly containing non-public - // types the dynamic assembly needs to access. Normally those types - // would be inaccessible, but this attribute allows them to be visible. - // It works like a reverse InternalsVisibleToAttribute. - // This method returns the TypeInfo of the generated attribute. - private TypeInfo GenerateTypeInfoOfIgnoresAccessChecksToAttribute() - { - TypeBuilder attributeTypeBuilder = - _mb.DefineType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute", - TypeAttributes.Public | TypeAttributes.Class, - typeof(Attribute)); - - // Create backing field as: - // private string assemblyName; - FieldBuilder assemblyNameField = - attributeTypeBuilder.DefineField("assemblyName", typeof(String), FieldAttributes.Private); - - // Create ctor as: - // public IgnoresAccessChecksToAttribute(string) - ConstructorBuilder constructorBuilder = attributeTypeBuilder.DefineConstructor(MethodAttributes.Public, - CallingConventions.HasThis, - new Type[] { assemblyNameField.FieldType }); - - ILGenerator il = constructorBuilder.GetILGenerator(); - - // Create ctor body as: - // this.assemblyName = {ctor parameter 0} - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldarg, 1); - il.Emit(OpCodes.Stfld, assemblyNameField); - - // return - il.Emit(OpCodes.Ret); - - // Define property as: - // public string AssemblyName {get { return this.assemblyName; } } - PropertyBuilder getterPropertyBuilder = attributeTypeBuilder.DefineProperty( - "AssemblyName", - PropertyAttributes.None, - CallingConventions.HasThis, - returnType: typeof(String), - parameterTypes: null); - - MethodBuilder getterMethodBuilder = attributeTypeBuilder.DefineMethod( - "get_AssemblyName", - MethodAttributes.Public, - CallingConventions.HasThis, - returnType: typeof(String), - parameterTypes: null); - - // Generate body: - // return this.assemblyName; - il = getterMethodBuilder.GetILGenerator(); - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldfld, assemblyNameField); - il.Emit(OpCodes.Ret); - - // Generate the AttributeUsage attribute for this attribute type: - // [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] - TypeInfo attributeUsageTypeInfo = typeof(AttributeUsageAttribute).GetTypeInfo(); - - // Find the ctor that takes only AttributeTargets - ConstructorInfo attributeUsageConstructorInfo = - attributeUsageTypeInfo.DeclaredConstructors - .Single(c => c.GetParameters().Count() == 1 && - c.GetParameters()[0].ParameterType == typeof(AttributeTargets)); - - // Find the property to set AllowMultiple - PropertyInfo allowMultipleProperty = - attributeUsageTypeInfo.DeclaredProperties - .Single(f => String.Equals(f.Name, "AllowMultiple")); - - // Create a builder to construct the instance via the ctor and property - CustomAttributeBuilder customAttributeBuilder = - new CustomAttributeBuilder(attributeUsageConstructorInfo, - new object[] { AttributeTargets.Assembly }, - new PropertyInfo[] { allowMultipleProperty }, - new object[] { true }); - - // Attach this attribute instance to the newly defined attribute type - attributeTypeBuilder.SetCustomAttribute(customAttributeBuilder); - - // Make the TypeInfo real so the constructor can be used. - return attributeTypeBuilder.CreateTypeInfo(); - } - - // Generates an instance of the IgnoresAccessChecksToAttribute to - // identify the given assembly as one which contains internal types - // the dynamic assembly will need to reference. - internal void GenerateInstanceOfIgnoresAccessChecksToAttribute(string assemblyName) - { - // Add this assembly level attribute: - // [assembly: System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute(assemblyName)] - ConstructorInfo attributeConstructor = IgnoresAccessChecksAttributeConstructor; - CustomAttributeBuilder customAttributeBuilder = - new CustomAttributeBuilder(attributeConstructor, new object[] { assemblyName }); - _ab.SetCustomAttribute(customAttributeBuilder); - } - - // Ensures the type we will reference from the dynamic assembly - // is visible. Non-public types need to emit an attribute that - // allows access from the dynamic assembly. - internal void EnsureTypeIsVisible(Type type) - { - TypeInfo typeInfo = type.GetTypeInfo(); - if (!typeInfo.IsVisible) - { - string assemblyName = typeInfo.Assembly.GetName().Name; - if (!_ignoresAccessAssemblyNames.Contains(assemblyName)) - { - GenerateInstanceOfIgnoresAccessChecksToAttribute(assemblyName); - _ignoresAccessAssemblyNames.Add(assemblyName); - } - } - } - - internal void GetTokenForMethod(MethodBase method, out Type type, out int token) - { - type = method.DeclaringType; - token = 0; - if (!_methodToToken.TryGetValue(method, out token)) - { - _methodsByToken.Add(method); - token = _methodsByToken.Count - 1; - _methodToToken[method] = token; - } - } - - internal MethodBase ResolveMethodToken(Type type, int token) - { - Debug.Assert(token >= 0 && token < _methodsByToken.Count); - return _methodsByToken[token]; - } - } - - private class ProxyBuilder - { - private static readonly MethodInfo s_delegateInvoke = typeof(Action).GetTypeInfo().GetDeclaredMethod("Invoke"); - - private ProxyAssembly _assembly; - private TypeBuilder _tb; - private Type _proxyBaseType; - private List _fields; - - internal ProxyBuilder(ProxyAssembly assembly, TypeBuilder tb, Type proxyBaseType) - { - _assembly = assembly; - _tb = tb; - _proxyBaseType = proxyBaseType; - - _fields = new List(); - _fields.Add(tb.DefineField("invoke", typeof(Action), FieldAttributes.Private)); - } - - private void Complete() - { - Type[] args = new Type[_fields.Count]; - for (int i = 0; i < args.Length; i++) - { - args[i] = _fields[i].FieldType; - } - - ConstructorBuilder cb = _tb.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, args); - ILGenerator il = cb.GetILGenerator(); - - // chained ctor call - ConstructorInfo baseCtor = _proxyBaseType.GetTypeInfo().DeclaredConstructors.SingleOrDefault(c => c.IsPublic && c.GetParameters().Length == 0); - Debug.Assert(baseCtor != null); - - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Call, baseCtor); - - // store all the fields - for (int i = 0; i < args.Length; i++) - { - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldarg, i + 1); - il.Emit(OpCodes.Stfld, _fields[i]); - } - - il.Emit(OpCodes.Ret); - } - - internal Type CreateType() - { - this.Complete(); - return _tb.CreateTypeInfo().AsType(); - } - - internal void AddInterfaceImpl(Type iface) - { - // If necessary, generate an attribute to permit visiblity - // to internal types. - _assembly.EnsureTypeIsVisible(iface); - - _tb.AddInterfaceImplementation(iface); - foreach (MethodInfo mi in iface.GetRuntimeMethods()) - { - AddMethodImpl(mi); - } - } - - private void AddMethodImpl(MethodInfo mi) - { - ParameterInfo[] parameters = mi.GetParameters(); - Type[] paramTypes = ParamTypes(parameters, false); - - MethodBuilder mdb = _tb.DefineMethod(mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, mi.ReturnType, paramTypes); - if (mi.ContainsGenericParameters) - { - Type[] ts = mi.GetGenericArguments(); - string[] ss = new string[ts.Length]; - for (int i = 0; i < ts.Length; i++) - { - ss[i] = ts[i].Name; - } - GenericTypeParameterBuilder[] genericParameters = mdb.DefineGenericParameters(ss); - for (int i = 0; i < genericParameters.Length; i++) - { - genericParameters[i].SetGenericParameterAttributes(ts[i].GetTypeInfo().GenericParameterAttributes); - } - } - ILGenerator il = mdb.GetILGenerator(); - - ParametersArray args = new ParametersArray(il, paramTypes); - - // object[] args = new object[paramCount]; - il.Emit(OpCodes.Nop); - GenericArray argsArr = new GenericArray(il, ParamTypes(parameters, true).Length); - - for (int i = 0; i < parameters.Length; i++) - { - // args[i] = argi; - if (!parameters[i].IsOut) - { - argsArr.BeginSet(i); - args.Get(i); - argsArr.EndSet(parameters[i].ParameterType); - } - } - - // object[] packed = new object[PackedArgs.PackedTypes.Length]; - GenericArray packedArr = new GenericArray(il, PackedArgs.PackedTypes.Length); - - // packed[PackedArgs.DispatchProxyPosition] = this; - packedArr.BeginSet(PackedArgs.DispatchProxyPosition); - il.Emit(OpCodes.Ldarg_0); - packedArr.EndSet(typeof(DispatchProxy)); - - // packed[PackedArgs.DeclaringTypePosition] = typeof(iface); - MethodInfo Type_GetTypeFromHandle = typeof(Type).GetRuntimeMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }); - _assembly.GetTokenForMethod(mi, out Type declaringType, out int methodToken); - packedArr.BeginSet(PackedArgs.DeclaringTypePosition); - il.Emit(OpCodes.Ldtoken, declaringType); - il.Emit(OpCodes.Call, Type_GetTypeFromHandle); - packedArr.EndSet(typeof(object)); - - // packed[PackedArgs.MethodTokenPosition] = iface method token; - packedArr.BeginSet(PackedArgs.MethodTokenPosition); - il.Emit(OpCodes.Ldc_I4, methodToken); - packedArr.EndSet(typeof(Int32)); - - // packed[PackedArgs.ArgsPosition] = args; - packedArr.BeginSet(PackedArgs.ArgsPosition); - argsArr.Load(); - packedArr.EndSet(typeof(object[])); - - // packed[PackedArgs.GenericTypesPosition] = mi.GetGenericArguments(); - if (mi.ContainsGenericParameters) - { - packedArr.BeginSet(PackedArgs.GenericTypesPosition); - Type[] genericTypes = mi.GetGenericArguments(); - GenericArray typeArr = new GenericArray(il, genericTypes.Length); - for (int i = 0; i < genericTypes.Length; ++i) - { - typeArr.BeginSet(i); - il.Emit(OpCodes.Ldtoken, genericTypes[i]); - il.Emit(OpCodes.Call, Type_GetTypeFromHandle); - typeArr.EndSet(typeof(Type)); - } - typeArr.Load(); - packedArr.EndSet(typeof(Type[])); - } - - // Call static DispatchProxyHelper.Invoke(object[]) - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldfld, _fields[InvokeActionFieldAndCtorParameterIndex]); // delegate - packedArr.Load(); - il.Emit(OpCodes.Call, s_delegateInvoke); - - for (int i = 0; i < parameters.Length; i++) - { - if (parameters[i].ParameterType.IsByRef) - { - args.BeginSet(i); - argsArr.Get(i); - args.EndSet(i, typeof(object)); - } - } - - if (mi.ReturnType != typeof(void)) - { - packedArr.Get(PackedArgs.ReturnValuePosition); - Convert(il, typeof(object), mi.ReturnType, false); - } - - il.Emit(OpCodes.Ret); - - _tb.DefineMethodOverride(mdb, mi); - } - - private static Type[] ParamTypes(ParameterInfo[] parms, bool noByRef) - { - Type[] types = new Type[parms.Length]; - for (int i = 0; i < parms.Length; i++) - { - types[i] = parms[i].ParameterType; - if (noByRef && types[i].IsByRef) - types[i] = types[i].GetElementType(); - } - return types; - } - - // TypeCode does not exist in ProjectK or ProjectN. - // This lookup method was copied from PortableLibraryThunks\Internal\PortableLibraryThunks\System\TypeThunks.cs - // but returns the integer value equivalent to its TypeCode enum. - private static int GetTypeCode(Type type) - { - if (type == null) - return 0; // TypeCode.Empty; - - if (type == typeof(Boolean)) - return 3; // TypeCode.Boolean; - - if (type == typeof(Char)) - return 4; // TypeCode.Char; - - if (type == typeof(SByte)) - return 5; // TypeCode.SByte; - - if (type == typeof(Byte)) - return 6; // TypeCode.Byte; - - if (type == typeof(Int16)) - return 7; // TypeCode.Int16; - - if (type == typeof(UInt16)) - return 8; // TypeCode.UInt16; - - if (type == typeof(Int32)) - return 9; // TypeCode.Int32; - - if (type == typeof(UInt32)) - return 10; // TypeCode.UInt32; - - if (type == typeof(Int64)) - return 11; // TypeCode.Int64; - - if (type == typeof(UInt64)) - return 12; // TypeCode.UInt64; - - if (type == typeof(Single)) - return 13; // TypeCode.Single; - - if (type == typeof(Double)) - return 14; // TypeCode.Double; - - if (type == typeof(Decimal)) - return 15; // TypeCode.Decimal; - - if (type == typeof(DateTime)) - return 16; // TypeCode.DateTime; - - if (type == typeof(String)) - return 18; // TypeCode.String; - - if (type.GetTypeInfo().IsEnum) - return GetTypeCode(Enum.GetUnderlyingType(type)); - - return 1; // TypeCode.Object; - } - - private static OpCode[] s_convOpCodes = new OpCode[] { - OpCodes.Nop,//Empty = 0, - OpCodes.Nop,//Object = 1, - OpCodes.Nop,//DBNull = 2, - OpCodes.Conv_I1,//Boolean = 3, - OpCodes.Conv_I2,//Char = 4, - OpCodes.Conv_I1,//SByte = 5, - OpCodes.Conv_U1,//Byte = 6, - OpCodes.Conv_I2,//Int16 = 7, - OpCodes.Conv_U2,//UInt16 = 8, - OpCodes.Conv_I4,//Int32 = 9, - OpCodes.Conv_U4,//UInt32 = 10, - OpCodes.Conv_I8,//Int64 = 11, - OpCodes.Conv_U8,//UInt64 = 12, - OpCodes.Conv_R4,//Single = 13, - OpCodes.Conv_R8,//Double = 14, - OpCodes.Nop,//Decimal = 15, - OpCodes.Nop,//DateTime = 16, - OpCodes.Nop,//17 - OpCodes.Nop,//String = 18, - }; - - private static OpCode[] s_ldindOpCodes = new OpCode[] { - OpCodes.Nop,//Empty = 0, - OpCodes.Nop,//Object = 1, - OpCodes.Nop,//DBNull = 2, - OpCodes.Ldind_I1,//Boolean = 3, - OpCodes.Ldind_I2,//Char = 4, - OpCodes.Ldind_I1,//SByte = 5, - OpCodes.Ldind_U1,//Byte = 6, - OpCodes.Ldind_I2,//Int16 = 7, - OpCodes.Ldind_U2,//UInt16 = 8, - OpCodes.Ldind_I4,//Int32 = 9, - OpCodes.Ldind_U4,//UInt32 = 10, - OpCodes.Ldind_I8,//Int64 = 11, - OpCodes.Ldind_I8,//UInt64 = 12, - OpCodes.Ldind_R4,//Single = 13, - OpCodes.Ldind_R8,//Double = 14, - OpCodes.Nop,//Decimal = 15, - OpCodes.Nop,//DateTime = 16, - OpCodes.Nop,//17 - OpCodes.Ldind_Ref,//String = 18, - }; - - private static OpCode[] s_stindOpCodes = new OpCode[] { - OpCodes.Nop,//Empty = 0, - OpCodes.Nop,//Object = 1, - OpCodes.Nop,//DBNull = 2, - OpCodes.Stind_I1,//Boolean = 3, - OpCodes.Stind_I2,//Char = 4, - OpCodes.Stind_I1,//SByte = 5, - OpCodes.Stind_I1,//Byte = 6, - OpCodes.Stind_I2,//Int16 = 7, - OpCodes.Stind_I2,//UInt16 = 8, - OpCodes.Stind_I4,//Int32 = 9, - OpCodes.Stind_I4,//UInt32 = 10, - OpCodes.Stind_I8,//Int64 = 11, - OpCodes.Stind_I8,//UInt64 = 12, - OpCodes.Stind_R4,//Single = 13, - OpCodes.Stind_R8,//Double = 14, - OpCodes.Nop,//Decimal = 15, - OpCodes.Nop,//DateTime = 16, - OpCodes.Nop,//17 - OpCodes.Stind_Ref,//String = 18, - }; - - private static void Convert(ILGenerator il, Type source, Type target, bool isAddress) - { - Debug.Assert(!target.IsByRef); - if (target == source) - return; - - TypeInfo sourceTypeInfo = source.GetTypeInfo(); - TypeInfo targetTypeInfo = target.GetTypeInfo(); - - if (source.IsByRef) - { - Debug.Assert(!isAddress); - Type argType = source.GetElementType(); - Ldind(il, argType); - Convert(il, argType, target, isAddress); - return; - } - if (targetTypeInfo.IsValueType) - { - if (sourceTypeInfo.IsValueType) - { - OpCode opCode = s_convOpCodes[GetTypeCode(target)]; - Debug.Assert(!opCode.Equals(OpCodes.Nop)); - il.Emit(opCode); - } - else - { - Debug.Assert(sourceTypeInfo.IsAssignableFrom(targetTypeInfo)); - il.Emit(OpCodes.Unbox, target); - if (!isAddress) - Ldind(il, target); - } - } - else if (targetTypeInfo.IsAssignableFrom(sourceTypeInfo)) - { - if (sourceTypeInfo.IsValueType) - { - if (isAddress) - Ldind(il, source); - il.Emit(OpCodes.Box, source); - } - } - else - { - Debug.Assert(sourceTypeInfo.IsAssignableFrom(targetTypeInfo) || targetTypeInfo.IsInterface || sourceTypeInfo.IsInterface); - if (target.IsGenericParameter) - { - // T GetProperty() where T : class; - Debug.Assert(targetTypeInfo.GenericParameterAttributes == GenericParameterAttributes.ReferenceTypeConstraint); - il.Emit(OpCodes.Unbox_Any, target); - } - else - { - il.Emit(OpCodes.Castclass, target); - } - } - } - - private static void Ldind(ILGenerator il, Type type) - { - OpCode opCode = s_ldindOpCodes[GetTypeCode(type)]; - if (!opCode.Equals(OpCodes.Nop)) - { - il.Emit(opCode); - } - else - { - il.Emit(OpCodes.Ldobj, type); - } - } - - private static void Stind(ILGenerator il, Type type) - { - OpCode opCode = s_stindOpCodes[GetTypeCode(type)]; - if (!opCode.Equals(OpCodes.Nop)) - { - il.Emit(opCode); - } - else - { - il.Emit(OpCodes.Stobj, type); - } - } - - private class ParametersArray - { - private ILGenerator _il; - private Type[] _paramTypes; - internal ParametersArray(ILGenerator il, Type[] paramTypes) - { - _il = il; - _paramTypes = paramTypes; - } - - internal void Get(int i) - { - _il.Emit(OpCodes.Ldarg, i + 1); - } - - internal void BeginSet(int i) - { - _il.Emit(OpCodes.Ldarg, i + 1); - } - - internal void EndSet(int i, Type stackType) - { - Debug.Assert(_paramTypes[i].IsByRef); - Type argType = _paramTypes[i].GetElementType(); - Convert(_il, stackType, argType, false); - Stind(_il, argType); - } - } - - private class GenericArray - { - private ILGenerator _il; - private LocalBuilder _lb; - internal GenericArray(ILGenerator il, int len) - { - _il = il; - _lb = il.DeclareLocal(typeof(T[])); - - il.Emit(OpCodes.Ldc_I4, len); - il.Emit(OpCodes.Newarr, typeof(T)); - il.Emit(OpCodes.Stloc, _lb); - } - - internal void Load() - { - _il.Emit(OpCodes.Ldloc, _lb); - } - - internal void Get(int i) - { - _il.Emit(OpCodes.Ldloc, _lb); - _il.Emit(OpCodes.Ldc_I4, i); - _il.Emit(OpCodes.Ldelem_Ref); - } - - internal void BeginSet(int i) - { - _il.Emit(OpCodes.Ldloc, _lb); - _il.Emit(OpCodes.Ldc_I4, i); - } - - internal void EndSet(Type stackType) - { - Convert(_il, stackType, typeof(T), false); - _il.Emit(OpCodes.Stelem_Ref); - } - } - } - } -} \ No newline at end of file diff --git a/Gigya.Microdot.ServiceProxy/CoreFX/_Readme.txt b/Gigya.Microdot.ServiceProxy/CoreFX/_Readme.txt deleted file mode 100644 index 71459314..00000000 --- a/Gigya.Microdot.ServiceProxy/CoreFX/_Readme.txt +++ /dev/null @@ -1,3 +0,0 @@ -Classes in this folder are borrowed from CoreFX (.NET Core's Libraries) git repository: -https://github.com/dotnet/corefx/tree/master/src/ -When migrating this codebase to .NET Core, these classes can be removed since they will be included with the CoreFX. \ No newline at end of file diff --git a/Gigya.Microdot.ServiceProxy/DelegatingDispatchProxy.cs b/Gigya.Microdot.ServiceProxy/DelegatingDispatchProxy.cs index ae86418d..19d4e8c2 100644 --- a/Gigya.Microdot.ServiceProxy/DelegatingDispatchProxy.cs +++ b/Gigya.Microdot.ServiceProxy/DelegatingDispatchProxy.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using Gigya.Microdot.System_Reflection.DispatchProxy; using System; using System.Reflection; diff --git a/Gigya.Microdot.ServiceProxy/Gigya.Microdot.ServiceProxy.csproj b/Gigya.Microdot.ServiceProxy/Gigya.Microdot.ServiceProxy.csproj index 6cb574e0..687adbb7 100644 --- a/Gigya.Microdot.ServiceProxy/Gigya.Microdot.ServiceProxy.csproj +++ b/Gigya.Microdot.ServiceProxy/Gigya.Microdot.ServiceProxy.csproj @@ -1,15 +1,22 @@  - - netstandard2.0 - Gigya.Microdot.ServiceProxy - $(SolutionDir)main.ruleset - - - - - - - - + + Gigya.Microdot.ServiceProxy + + ServiceProxy is used to call remote Microdot services. It is a + runtime-generated transparent proxy which implements the remote service's + public interface, translating all calls performed on it to HTTP calls. + Part of the Microdot framework. + + gigya microdot microservice microservices serviceproxy http rpc + + + + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.ServiceProxy/HttpsAuthenticator.cs b/Gigya.Microdot.ServiceProxy/HttpsAuthenticator.cs index 47bd0bb2..e010ccde 100644 --- a/Gigya.Microdot.ServiceProxy/HttpsAuthenticator.cs +++ b/Gigya.Microdot.ServiceProxy/HttpsAuthenticator.cs @@ -1,11 +1,11 @@ -using System; +using Gigya.Microdot.Interfaces.Logging; +using Gigya.Microdot.SharedLogic.HttpService; +using Gigya.Microdot.SharedLogic.Security; +using System; using System.Net.Http; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; -using Gigya.Microdot.Interfaces.Logging; -using Gigya.Microdot.SharedLogic.HttpService; -using Gigya.Microdot.SharedLogic.Security; namespace Gigya.Microdot.ServiceProxy { diff --git a/Gigya.Microdot.ServiceProxy/IServiceProxyProvider.cs b/Gigya.Microdot.ServiceProxy/IServiceProxyProvider.cs index 4dbe277c..1f963c53 100644 --- a/Gigya.Microdot.ServiceProxy/IServiceProxyProvider.cs +++ b/Gigya.Microdot.ServiceProxy/IServiceProxyProvider.cs @@ -20,12 +20,12 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.SharedLogic.HttpService; using Newtonsoft.Json; +using System; +using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.ServiceProxy { diff --git a/Gigya.Microdot.ServiceProxy/Properties/AssemblyInfo.cs b/Gigya.Microdot.ServiceProxy/Properties/AssemblyInfo.cs index 5aa528c4..6abd153a 100644 --- a/Gigya.Microdot.ServiceProxy/Properties/AssemblyInfo.cs +++ b/Gigya.Microdot.ServiceProxy/Properties/AssemblyInfo.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: InternalsVisibleTo("Gigya.Common.OrleansInfra.TestingTools")] diff --git a/Gigya.Microdot.ServiceProxy/Rewrite/IMemoizer.cs b/Gigya.Microdot.ServiceProxy/Rewrite/IMemoizer.cs index 932ab449..4098fe9b 100644 --- a/Gigya.Microdot.ServiceProxy/Rewrite/IMemoizer.cs +++ b/Gigya.Microdot.ServiceProxy/Rewrite/IMemoizer.cs @@ -20,11 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Attributes; using System; using System.Reflection; using System.Threading.Tasks; -using Gigya.Common.Contracts.Attributes; -using Gigya.Microdot.ServiceDiscovery.Config; namespace Gigya.Microdot.ServiceProxy.Rewrite { diff --git a/Gigya.Microdot.ServiceProxy/Rewrite/IProxyable.cs b/Gigya.Microdot.ServiceProxy/Rewrite/IProxyable.cs index c39aa3bd..6d99c0a7 100644 --- a/Gigya.Microdot.ServiceProxy/Rewrite/IProxyable.cs +++ b/Gigya.Microdot.ServiceProxy/Rewrite/IProxyable.cs @@ -19,8 +19,7 @@ // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #endregion - -using Gigya.Microdot.System_Reflection.DispatchProxy; + using System.Reflection; namespace Gigya.Microdot.ServiceProxy.Rewrite diff --git a/Gigya.Microdot.ServiceProxy/Rewrite/IServiceProxyProvider.cs b/Gigya.Microdot.ServiceProxy/Rewrite/IServiceProxyProvider.cs index ce349f6d..faa3ced6 100644 --- a/Gigya.Microdot.ServiceProxy/Rewrite/IServiceProxyProvider.cs +++ b/Gigya.Microdot.ServiceProxy/Rewrite/IServiceProxyProvider.cs @@ -20,21 +20,19 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Threading.Tasks; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.LanguageExtensions; -using Gigya.Microdot.ServiceDiscovery.HostManagement; using Gigya.Microdot.ServiceDiscovery.Rewrite; using Gigya.Microdot.SharedLogic.HttpService; -using Gigya.Microdot.SharedLogic.Utils; using Newtonsoft.Json; +using System; +using System.Threading.Tasks; namespace Gigya.Microdot.ServiceProxy.Rewrite -{ - /// - /// This is a beta version. Please do not use it until it's ready - /// +{ + /// + /// This is a beta version. Please do not use it until it's ready + /// public interface IServiceProxyProvider : IProxyable { Task Invoke(HttpServiceRequest request, Type resultReturnType, JsonSerializerSettings jsonSettings = null); diff --git a/Gigya.Microdot.ServiceProxy/Rewrite/ServiceProxyProvider.cs b/Gigya.Microdot.ServiceProxy/Rewrite/ServiceProxyProvider.cs index 65dc3441..4cc2e43a 100644 --- a/Gigya.Microdot.ServiceProxy/Rewrite/ServiceProxyProvider.cs +++ b/Gigya.Microdot.ServiceProxy/Rewrite/ServiceProxyProvider.cs @@ -1,3 +1,9 @@ +using Gigya.Common.Contracts.HttpService; +using Gigya.Microdot.SharedLogic; +using Gigya.Microdot.SharedLogic.Events; +using Gigya.Microdot.SharedLogic.HttpService; +using Gigya.Microdot.SharedLogic.Security; +using Newtonsoft.Json; using System; using System.Collections.Concurrent; using System.Linq; @@ -5,22 +11,13 @@ using System.Reflection; using System.Text; using System.Threading.Tasks; -using Gigya.Common.Contracts.HttpService; -using Gigya.Microdot.Configuration; -using Gigya.Microdot.SharedLogic; -using Gigya.Microdot.SharedLogic.Configurations; -using Gigya.Microdot.SharedLogic.Events; -using Gigya.Microdot.SharedLogic.HttpService; -using Gigya.Microdot.SharedLogic.Rewrite; -using Gigya.Microdot.SharedLogic.Security; -using Newtonsoft.Json; namespace Gigya.Microdot.ServiceProxy.Rewrite { - /// - /// This is a beta version. Please do not use it until it's ready - /// - public class ServiceProxyProvider : IServiceProxyProvider + /// + /// This is a beta version. Please do not use it until it's ready + /// + public class ServiceProxyProvider : IServiceProxyProvider { public static readonly JsonSerializerSettings JsonSettings = new JsonSerializerSettings { diff --git a/Gigya.Microdot.ServiceProxy/ServiceProxyProvider.cs b/Gigya.Microdot.ServiceProxy/ServiceProxyProvider.cs index bc43500a..2a6a036b 100644 --- a/Gigya.Microdot.ServiceProxy/ServiceProxyProvider.cs +++ b/Gigya.Microdot.ServiceProxy/ServiceProxyProvider.cs @@ -20,17 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Runtime.ExceptionServices; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; using Gigya.Common.Application.HttpService.Client; using Gigya.Common.Contracts.Exceptions; using Gigya.Common.Contracts.HttpService; @@ -39,18 +28,26 @@ using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.ServiceDiscovery.Rewrite; using Gigya.Microdot.SharedLogic; -using Gigya.Microdot.SharedLogic.Configurations; using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.Exceptions; using Gigya.Microdot.SharedLogic.HttpService; using Gigya.Microdot.SharedLogic.Rewrite; using Gigya.Microdot.SharedLogic.Security; -using Gigya.Microdot.SharedLogic.Utils; using Metrics; using Newtonsoft.Json; -using Timer = Metrics.Timer; - +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Runtime.ExceptionServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; using static Gigya.Microdot.LanguageExtensions.MiscExtensions; +using Timer = Metrics.Timer; namespace Gigya.Microdot.ServiceProxy { @@ -88,9 +85,9 @@ public class ServiceProxyProvider : IDisposable, IServiceProxyProvider /// network. /// public Action PrepareRequest { get; set; } - [Obsolete] + [Obsolete("Will be removed in feature versions")] public ISourceBlock EndPointsChanged => null; - [Obsolete] + [Obsolete("Will be removed in feature versions")] public ISourceBlock ReachabilityChanged => null; private TimeSpan? Timeout { get; set; } @@ -132,8 +129,6 @@ public class ServiceProxyProvider : IDisposable, IServiceProxyProvider private CurrentApplicationInfo AppInfo { get; } - private ObjectPool _stopwatchPool = new ObjectPool(() => new Stopwatch(), 4096); - public ServiceProxyProvider(string serviceName, IEventPublisher eventPublisher, ILog log, Func serviceDiscoveryFactory, @@ -278,8 +273,18 @@ await ValidateReachability(hostname, basePort, fallbackOnProtocolError: false, c } catch (HttpRequestException ex) { - Log.Info(_ => _($"HTTPS for service {ServiceName} is not available.")); - Log.Debug(_ => _($"HTTPS for service {ServiceName} is not available.", ex)); + + if ( ex.Message != null + && (this.GetDiscoveryConfig().CertificateErrorMessageSubstrings??Enumerable.Empty()) + .Any(ex.Message.Contains) + ) + { + Log.Error(_ => _($"HTTPS for service {ServiceName} is not available due to certificate error.", ex)); + } + else + { + Log.Info(_ => _($"HTTPS for service {ServiceName} is not available.", ex)); + } } } @@ -290,7 +295,7 @@ private Task ValidateReachability(Node node, CancellationToken cancellationToken if (port == null) throw new Exception("No port is configured"); - Func clientFactory = tryHttps => GetHttpClient(config, GetDiscoveryConfig(), tryHttps, node.Hostname, port.Value); + (HttpClient client, bool isHttps) clientFactory(bool tryHttps) => GetHttpClient(config, GetDiscoveryConfig(), tryHttps, node.Hostname, port.Value); return ValidateReachability(node.Hostname, port.Value, fallbackOnProtocolError: true, clientFactory: clientFactory, cancellationToken: cancellationToken); } @@ -482,8 +487,9 @@ private async Task InvokeCore(HttpServiceRequest request, Type resultRet finally { clientCallEvent.ResponseEndTimestamp = Stopwatch.GetTimestamp(); - +#if !NET5_0_OR_GREATER PublishServiceConnectionMetrics(uri); +#endif } if (response.Headers.TryGetValues(GigyaHttpHeaders.ExecutionTime, out IEnumerable values)) { @@ -496,10 +502,15 @@ private async Task InvokeCore(HttpServiceRequest request, Type resultRet } catch (HttpRequestException ex) { + //In case we get any https request exception and we were trying HTTPs we must fallback to HTTP //otherwise we will be stuck trying HTTPs because we didn't change the Http client and will probably //get different error than Tls errors - if (allowNonHttps && isHttps) + if ( allowNonHttps + && isHttps + && ex.Message != null + && (discoveryConfig.CertificateErrorMessageSubstrings??Enumerable.Empty()).Any(ex.Message.Contains) + ) { tryHttps = false; continue; @@ -620,12 +631,6 @@ private async Task InvokeCore(HttpServiceRequest request, Type resultRet } else { - if (allowNonHttps && isHttps) - { - tryHttps = false; - continue; - } - var exception = response.StatusCode == HttpStatusCode.ServiceUnavailable ? new Exception($"The remote service is unavailable (503) and is not recognized as a Gigya host at uri: {uri}") : new Exception($"The remote service returned a response but is not recognized as a Gigya host at uri: {uri}"); diff --git a/Gigya.Microdot.ServiceProxy/ServiceProxyProviderGeneric.cs b/Gigya.Microdot.ServiceProxy/ServiceProxyProviderGeneric.cs index b38fd68d..9611dd4a 100644 --- a/Gigya.Microdot.ServiceProxy/ServiceProxyProviderGeneric.cs +++ b/Gigya.Microdot.ServiceProxy/ServiceProxyProviderGeneric.cs @@ -20,14 +20,13 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Linq; -using System.Reflection; using Gigya.Common.Contracts.Exceptions; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.HttpService; -using Gigya.Microdot.System_Reflection.DispatchProxy; +using System; +using System.Linq; +using System.Reflection; namespace Gigya.Microdot.ServiceProxy { diff --git a/Gigya.Microdot.ServiceProxy/paket.references b/Gigya.Microdot.ServiceProxy/paket.references deleted file mode 100644 index d8685d3b..00000000 --- a/Gigya.Microdot.ServiceProxy/paket.references +++ /dev/null @@ -1,10 +0,0 @@ -Gigya.ServiceContract -Newtonsoft.Json -Nito.AsyncEx -System.Collections.Immutable -System.Threading.Tasks.Dataflow -System.ValueTuple -System.ComponentModel.Annotations -System.Net.Http -System.Runtime.Caching -System.Reflection.Emit diff --git a/Gigya.Microdot.ServiceProxy/paket.template b/Gigya.Microdot.ServiceProxy/paket.template deleted file mode 100644 index 2bae6443..00000000 --- a/Gigya.Microdot.ServiceProxy/paket.template +++ /dev/null @@ -1,13 +0,0 @@ -type - project -description - ServiceProxy is used to call remote Microdot services. It is a - runtime-generated transparent proxy which implements the remote service's - public interface, translating all calls performed on it to HTTP calls. - Part of the Microdot framework. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices serviceproxy http rpc \ No newline at end of file diff --git a/Gigya.Microdot.SharedLogic/ApplicationDirectoryProvider.cs b/Gigya.Microdot.SharedLogic/ApplicationDirectoryProvider.cs index f4e4bab6..600e947f 100644 --- a/Gigya.Microdot.SharedLogic/ApplicationDirectoryProvider.cs +++ b/Gigya.Microdot.SharedLogic/ApplicationDirectoryProvider.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces; using System.IO; using System.Reflection; -using Gigya.Microdot.Interfaces; namespace Gigya.Microdot.SharedLogic { diff --git a/Gigya.Microdot.SharedLogic/AssemblyProvider.cs b/Gigya.Microdot.SharedLogic/AssemblyProvider.cs index 7095470f..339813ef 100644 --- a/Gigya.Microdot.SharedLogic/AssemblyProvider.cs +++ b/Gigya.Microdot.SharedLogic/AssemblyProvider.cs @@ -20,13 +20,13 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces; +using Gigya.Microdot.Interfaces.Logging; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; -using Gigya.Microdot.Interfaces; -using Gigya.Microdot.Interfaces.Logging; namespace Gigya.Microdot.SharedLogic { diff --git a/Gigya.Microdot.SharedLogic/Configurations/LoadShedding.cs b/Gigya.Microdot.SharedLogic/Configurations/LoadShedding.cs index f8349435..e1216cd3 100644 --- a/Gigya.Microdot.SharedLogic/Configurations/LoadShedding.cs +++ b/Gigya.Microdot.SharedLogic/Configurations/LoadShedding.cs @@ -1,5 +1,5 @@ -using System; -using Gigya.Microdot.Interfaces.Configuration; +using Gigya.Microdot.Interfaces.Configuration; +using System; namespace Gigya.Microdot.SharedLogic.Configurations { diff --git a/Gigya.Microdot.SharedLogic/Configurations/Serialization/MicrodotSerializationConstraintsService.cs b/Gigya.Microdot.SharedLogic/Configurations/Serialization/MicrodotSerializationConstraintsService.cs index 560a5777..d5ba863d 100644 --- a/Gigya.Microdot.SharedLogic/Configurations/Serialization/MicrodotSerializationConstraintsService.cs +++ b/Gigya.Microdot.SharedLogic/Configurations/Serialization/MicrodotSerializationConstraintsService.cs @@ -1,9 +1,6 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using Newtonsoft.Json; namespace Gigya.Microdot.SharedLogic.Configurations.Serialization { @@ -22,8 +19,9 @@ public AssemblyAndTypeName(string assemblyName, string typeName) public interface IMicrodotSerializationConstraints { void ThrowIfExcluded(string typeName); +#nullable enable AssemblyAndTypeName TryGetAssemblyNameAndTypeReplacement(string? assemblyName, string typeName); - +#nullable disable AssemblyAndTypeName TryGetAssemblyAndTypeNameReplacementFromType(Type serializedType, string assemblyName, string typeName); } @@ -78,8 +76,10 @@ public void ThrowIfExcluded(string typeName) throw new UnauthorizedAccessException($"JSON Serialization Binder forbids BindToType type '{typeName}'"); } } - + +#nullable enable public AssemblyAndTypeName TryGetAssemblyNameAndTypeReplacement(string? assemblyName, string typeName) +#nullable disable { var config = GetSerializationConfigAndRefreshCaches(); diff --git a/Gigya.Microdot.SharedLogic/Configurations/Serialization/MicrodotSerializationSecurityConfig.cs b/Gigya.Microdot.SharedLogic/Configurations/Serialization/MicrodotSerializationSecurityConfig.cs index b9c178a3..956a0011 100644 --- a/Gigya.Microdot.SharedLogic/Configurations/Serialization/MicrodotSerializationSecurityConfig.cs +++ b/Gigya.Microdot.SharedLogic/Configurations/Serialization/MicrodotSerializationSecurityConfig.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; +using Gigya.Microdot.Interfaces.Configuration; +using Newtonsoft.Json; +using System.Collections.Generic; using System.Runtime.Serialization; using System.Text.RegularExpressions; -using Gigya.Microdot.Interfaces.Configuration; -using Newtonsoft.Json; namespace Gigya.Microdot.SharedLogic.Configurations.Serialization { diff --git a/Gigya.Microdot.SharedLogic/Events/ClientCallEvent.cs b/Gigya.Microdot.SharedLogic/Events/ClientCallEvent.cs index a2d55543..1a4d1823 100644 --- a/Gigya.Microdot.SharedLogic/Events/ClientCallEvent.cs +++ b/Gigya.Microdot.SharedLogic/Events/ClientCallEvent.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Diagnostics; using Gigya.Microdot.Interfaces.Events; +using System.Diagnostics; namespace Gigya.Microdot.SharedLogic.Events { diff --git a/Gigya.Microdot.SharedLogic/Events/ContextTags.cs b/Gigya.Microdot.SharedLogic/Events/ContextTags.cs index 3db2d627..5a38745e 100644 --- a/Gigya.Microdot.SharedLogic/Events/ContextTags.cs +++ b/Gigya.Microdot.SharedLogic/Events/ContextTags.cs @@ -2,7 +2,6 @@ using Gigya.Microdot.SharedLogic.Utils; using System; using System.Collections.Generic; -using System.Linq; namespace Gigya.Microdot.SharedLogic.Events { diff --git a/Gigya.Microdot.SharedLogic/Events/Event.cs b/Gigya.Microdot.SharedLogic/Events/Event.cs index 6b20a381..2ed149fc 100644 --- a/Gigya.Microdot.SharedLogic/Events/Event.cs +++ b/Gigya.Microdot.SharedLogic/Events/Event.cs @@ -20,16 +20,16 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic.Logging; using Gigya.Microdot.SharedLogic.Utils; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; namespace Gigya.Microdot.SharedLogic.Events { @@ -92,9 +92,12 @@ public class Event : IEvent [EventField(EventConsts.infrVersion, OmitFromAudit = true)] public string InfraVersion { get; set;} // Publisher populated from CurrentApplicationInfo; + [EventField(EventConsts.containerName, OmitFromAudit = true)] + public string ContainerName { get; set; } = CurrentApplicationInfo.ContainerName; + ///// The hostname of the server making the report [EventField(EventConsts.runtimeHost)] - public string HostName { get; set; } = CurrentApplicationInfo.HostName; + public string HostName { get; set; } = CurrentApplicationInfo.HostName; /// The value of the %REGION% environment variable. . [EventField(EventConsts.runtimeREGION, OmitFromAudit = true)] diff --git a/Gigya.Microdot.SharedLogic/Events/EventConsts.cs b/Gigya.Microdot.SharedLogic/Events/EventConsts.cs index d9657ef0..2b2ba425 100644 --- a/Gigya.Microdot.SharedLogic/Events/EventConsts.cs +++ b/Gigya.Microdot.SharedLogic/Events/EventConsts.cs @@ -45,6 +45,7 @@ public static class EventConsts public const string srvSystemInstance = "srv.systemInstance"; public const string srvVersion = "srv.version"; public const string infrVersion = "srv.infraVersion"; + public const string containerName = "srv.containerName"; public const string message = "message"; public const string details = "details"; diff --git a/Gigya.Microdot.SharedLogic/Events/EventFactory.cs b/Gigya.Microdot.SharedLogic/Events/EventFactory.cs index 4c4f5e4a..4e794d49 100644 --- a/Gigya.Microdot.SharedLogic/Events/EventFactory.cs +++ b/Gigya.Microdot.SharedLogic/Events/EventFactory.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.SystemWrappers; +using System; namespace Gigya.Microdot.SharedLogic.Events { diff --git a/Gigya.Microdot.SharedLogic/Events/EventFieldFormatter.cs b/Gigya.Microdot.SharedLogic/Events/EventFieldFormatter.cs index 0afa173e..3ae3dc44 100644 --- a/Gigya.Microdot.SharedLogic/Events/EventFieldFormatter.cs +++ b/Gigya.Microdot.SharedLogic/Events/EventFieldFormatter.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Newtonsoft.Json; using System; using System.Globalization; -using Newtonsoft.Json; namespace Gigya.Microdot.SharedLogic.Events { diff --git a/Gigya.Microdot.SharedLogic/Events/EventSerializer.cs b/Gigya.Microdot.SharedLogic/Events/EventSerializer.cs index 95fea612..2ab6fe1d 100644 --- a/Gigya.Microdot.SharedLogic/Events/EventSerializer.cs +++ b/Gigya.Microdot.SharedLogic/Events/EventSerializer.cs @@ -1,14 +1,13 @@ -using System; +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.Interfaces.Events; +using Gigya.Microdot.Interfaces.Logging; +using Gigya.Microdot.Interfaces.SystemWrappers; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; - -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.Interfaces.Events; -using Gigya.Microdot.Interfaces.Logging; -using Gigya.Microdot.Interfaces.SystemWrappers; namespace Gigya.Microdot.SharedLogic.Events { diff --git a/Gigya.Microdot.SharedLogic/Events/MembersToLogExtractor.cs b/Gigya.Microdot.SharedLogic/Events/MembersToLogExtractor.cs index 0ad93282..fe049ac3 100644 --- a/Gigya.Microdot.SharedLogic/Events/MembersToLogExtractor.cs +++ b/Gigya.Microdot.SharedLogic/Events/MembersToLogExtractor.cs @@ -21,15 +21,15 @@ #endregion +using Gigya.Microdot.Interfaces.Logging; +using Gigya.ServiceContract.Attributes; +using Newtonsoft.Json.Linq; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; -using Gigya.Microdot.Interfaces.Logging; -using Gigya.ServiceContract.Attributes; -using Newtonsoft.Json.Linq; namespace Gigya.Microdot.SharedLogic.Events { diff --git a/Gigya.Microdot.SharedLogic/Events/TracingContext.cs b/Gigya.Microdot.SharedLogic/Events/TracingContext.cs index 18ea3dff..0beb16d2 100644 --- a/Gigya.Microdot.SharedLogic/Events/TracingContext.cs +++ b/Gigya.Microdot.SharedLogic/Events/TracingContext.cs @@ -20,11 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic.HttpService; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; -using Gigya.Microdot.SharedLogic.HttpService; namespace Gigya.Microdot.SharedLogic.Events { diff --git a/Gigya.Microdot.SharedLogic/Exceptions/ConfigurationException.cs b/Gigya.Microdot.SharedLogic/Exceptions/ConfigurationException.cs index c4d26aa2..852bd3be 100644 --- a/Gigya.Microdot.SharedLogic/Exceptions/ConfigurationException.cs +++ b/Gigya.Microdot.SharedLogic/Exceptions/ConfigurationException.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; using System; using System.Runtime.Serialization; -using Gigya.Common.Contracts.Exceptions; namespace Gigya.Microdot.SharedLogic.Exceptions { diff --git a/Gigya.Microdot.SharedLogic/Exceptions/ExceptionHierarchySerializationBinder.cs b/Gigya.Microdot.SharedLogic/Exceptions/ExceptionHierarchySerializationBinder.cs index 42d82726..194c9a03 100644 --- a/Gigya.Microdot.SharedLogic/Exceptions/ExceptionHierarchySerializationBinder.cs +++ b/Gigya.Microdot.SharedLogic/Exceptions/ExceptionHierarchySerializationBinder.cs @@ -1,13 +1,9 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using Gigya.Microdot.SharedLogic.Configurations; -using Gigya.Microdot.SharedLogic.Configurations.Serialization; -using Gigya.Microdot.SharedLogic.Security; +using Gigya.Microdot.SharedLogic.Security; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; +using System; +using System.Collections.Generic; +using System.Linq; namespace Gigya.Microdot.SharedLogic.Exceptions { diff --git a/Gigya.Microdot.SharedLogic/Exceptions/JsonExceptionSerializationSettings.cs b/Gigya.Microdot.SharedLogic/Exceptions/JsonExceptionSerializationSettings.cs index 80a17711..41241522 100644 --- a/Gigya.Microdot.SharedLogic/Exceptions/JsonExceptionSerializationSettings.cs +++ b/Gigya.Microdot.SharedLogic/Exceptions/JsonExceptionSerializationSettings.cs @@ -1,7 +1,4 @@ -using System; -using Gigya.Microdot.SharedLogic.Configurations; -using Gigya.Microdot.SharedLogic.Security; -using Newtonsoft.Json; +using Newtonsoft.Json; namespace Gigya.Microdot.SharedLogic.Exceptions { diff --git a/Gigya.Microdot.SharedLogic/Exceptions/JsonExceptionSerializer.cs b/Gigya.Microdot.SharedLogic/Exceptions/JsonExceptionSerializer.cs index 08a081a7..e850b6aa 100644 --- a/Gigya.Microdot.SharedLogic/Exceptions/JsonExceptionSerializer.cs +++ b/Gigya.Microdot.SharedLogic/Exceptions/JsonExceptionSerializer.cs @@ -20,18 +20,17 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using System; namespace Gigya.Microdot.SharedLogic.Exceptions { - /// - /// Serializes and deserializes exceptions into JSON, with inheritance hierarchy tolerance. - /// - public class JsonExceptionSerializer + /// + /// Serializes and deserializes exceptions into JSON, with inheritance hierarchy tolerance. + /// + public class JsonExceptionSerializer { private readonly IJsonExceptionSerializationSettings _exceptionSerializationSettings; private IStackTraceEnhancer StackTraceEnhancer { get; } diff --git a/Gigya.Microdot.SharedLogic/Exceptions/StackTraceEnhancer.cs b/Gigya.Microdot.SharedLogic/Exceptions/StackTraceEnhancer.cs index 9679d86e..c6edb1e7 100644 --- a/Gigya.Microdot.SharedLogic/Exceptions/StackTraceEnhancer.cs +++ b/Gigya.Microdot.SharedLogic/Exceptions/StackTraceEnhancer.cs @@ -1,14 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.ServiceContract.Exceptions; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; namespace Gigya.Microdot.SharedLogic.Exceptions { @@ -75,7 +74,12 @@ public string Clean(string stackTrace) var replacements = config.RegexReplacements.Values.ToArray(); var frames = stackTrace .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) - .Where(f => f.StartsWith(" at System.Runtime") == false && f.StartsWith("Exception rethrown at ") == false && f.StartsWith("Server stack trace:") == false && f != "--- End of stack trace from previous location where exception was thrown ---") + .Where(f => + f.StartsWith(" at System.Runtime") == false && + f.StartsWith("Exception rethrown at ") == false && + f.StartsWith("Server stack trace:") == false && + f != "--- End of stack trace from previous location where exception was thrown ---" && + f != "--- End of stack trace from previous location ---") .Select(f => ApplyRegexs(f, replacements)); return string.Join("\r\n", frames); diff --git a/Gigya.Microdot.SharedLogic/Exceptions/StripHttpRequestExceptionConverter.cs b/Gigya.Microdot.SharedLogic/Exceptions/StripHttpRequestExceptionConverter.cs index 9c151090..1ea943a7 100644 --- a/Gigya.Microdot.SharedLogic/Exceptions/StripHttpRequestExceptionConverter.cs +++ b/Gigya.Microdot.SharedLogic/Exceptions/StripHttpRequestExceptionConverter.cs @@ -1,9 +1,9 @@ -using System; -using System.Net.Http; -using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.SharedLogic.Utils; using Newtonsoft.Json; using Newtonsoft.Json.Linq; +using System; +using System.Net.Http; namespace Gigya.Microdot.SharedLogic.Exceptions { diff --git a/Gigya.Microdot.SharedLogic/Gigya.Microdot.SharedLogic.csproj b/Gigya.Microdot.SharedLogic/Gigya.Microdot.SharedLogic.csproj index 75f7f877..4d4e6dcc 100644 --- a/Gigya.Microdot.SharedLogic/Gigya.Microdot.SharedLogic.csproj +++ b/Gigya.Microdot.SharedLogic/Gigya.Microdot.SharedLogic.csproj @@ -1,14 +1,18 @@  - - netstandard2.0 - Gigya.Microdot.SharedLogic - 8.0 - $(SolutionDir)main.ruleset - - - - - - + + Gigya.Microdot.SharedLogic + Various components and utilities shared between different parts of the Microdot framework. + + + + + + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.SharedLogic/HttpService/ClientCertificateVerificationModes.cs b/Gigya.Microdot.SharedLogic/HttpService/ClientCertificateVerificationModes.cs index 281c2b98..19323ab1 100644 --- a/Gigya.Microdot.SharedLogic/HttpService/ClientCertificateVerificationModes.cs +++ b/Gigya.Microdot.SharedLogic/HttpService/ClientCertificateVerificationModes.cs @@ -1,7 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Newtonsoft.Json; +using Newtonsoft.Json; +using System; namespace Gigya.Microdot.SharedLogic.HttpService { diff --git a/Gigya.Microdot.SharedLogic/HttpService/HttpServiceRequest.cs b/Gigya.Microdot.SharedLogic/HttpService/HttpServiceRequest.cs index ec1d6e01..58f60199 100644 --- a/Gigya.Microdot.SharedLogic/HttpService/HttpServiceRequest.cs +++ b/Gigya.Microdot.SharedLogic/HttpService/HttpServiceRequest.cs @@ -20,6 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic.Events; +using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; @@ -27,8 +29,6 @@ using System.Linq; using System.Reflection; using System.Text.RegularExpressions; -using Gigya.Microdot.SharedLogic.Events; -using Newtonsoft.Json; namespace Gigya.Microdot.SharedLogic.HttpService { diff --git a/Gigya.Microdot.SharedLogic/HttpService/RequestOverrides.cs b/Gigya.Microdot.SharedLogic/HttpService/RequestOverrides.cs index 83663f11..be2188fa 100644 --- a/Gigya.Microdot.SharedLogic/HttpService/RequestOverrides.cs +++ b/Gigya.Microdot.SharedLogic/HttpService/RequestOverrides.cs @@ -20,11 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic.Events; +using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using Newtonsoft.Json; -using Gigya.Microdot.SharedLogic.Events; namespace Gigya.Microdot.SharedLogic.HttpService { diff --git a/Gigya.Microdot.SharedLogic/HttpService/ServiceSchemaPostProcessor.cs b/Gigya.Microdot.SharedLogic/HttpService/ServiceSchemaPostProcessor.cs new file mode 100644 index 00000000..4b03efee --- /dev/null +++ b/Gigya.Microdot.SharedLogic/HttpService/ServiceSchemaPostProcessor.cs @@ -0,0 +1,116 @@ +using Gigya.Common.Contracts.HttpService; +using Gigya.Microdot.SharedLogic.Configurations.Serialization; +using System; +using System.Linq; + +namespace Gigya.Microdot.SharedLogic.HttpService +{ + public interface IServiceSchemaPostProcessor + { + void PostProcessServiceSchema(ServiceSchema serviceSchema); + } + + public class ServiceSchemaPostProcessor : IServiceSchemaPostProcessor + { + private readonly IMicrodotSerializationConstraints _serializationConstraints; + + public ServiceSchemaPostProcessor(IMicrodotSerializationConstraints serializationConstraints) + { + _serializationConstraints = serializationConstraints; + } + + public void PostProcessServiceSchema(ServiceSchema serviceSchema) + { + foreach (var curInterface in serviceSchema.Interfaces) + { + PostProcessInterface(curInterface); + } + } + + private void PostProcessInterface(InterfaceSchema curInterface) + { + if (curInterface.Attributes != null) + { + PostProcessAttributes(curInterface.Attributes); + } + + foreach (var curMethod in curInterface.Methods) + { + if (curMethod.Attributes != null) + { + PostProcessAttributes(curMethod.Attributes); + } + + if (curMethod.Parameters != null) + { + foreach (var curMethodParameter in curMethod.Parameters) + { + var alternagiveQuaAlternativeFullyQualifiedName = + GetAlternagiveQuaAlternativeFullyQualifiedName(curMethodParameter.Type); + curMethodParameter.TypeName = alternagiveQuaAlternativeFullyQualifiedName ?? + curMethodParameter.TypeName; + + if (curMethodParameter.Fields != null) + { + PostProcessFields(curMethodParameter.Fields); + } + } + } + + if (curMethod.Response != null) + { + if (curMethod.Response.Attributes != null) + { + PostProcessAttributes(curMethod.Response.Attributes); + } + + if (curMethod.Response.Fields != null) + { + PostProcessFields(curMethod.Response.Fields); + } + } + } + } + + private void PostProcessFields(FieldSchema[] fields) + { + foreach (var curMethodField in fields) + { + var curMethodFieldAlternativeFullyQualifiedName = + GetAlternagiveQuaAlternativeFullyQualifiedName(curMethodField.Type); + + curMethodField.TypeName = + curMethodFieldAlternativeFullyQualifiedName ?? curMethodField.TypeName; + + if (curMethodField.Attributes != null) + { + PostProcessAttributes(curMethodField.Attributes); + } + } + } + + private void PostProcessAttributes(AttributeSchema[] attributes) + { + foreach (var curAttribute in attributes.Where(x => x.Attribute != null)) + { + var alternagiveQuaAlternativeFullyQualifiedName = + GetAlternagiveQuaAlternativeFullyQualifiedName(curAttribute.Attribute.GetType()); + curAttribute.TypeName = alternagiveQuaAlternativeFullyQualifiedName ?? curAttribute.TypeName; + } + } + + private string GetAlternagiveQuaAlternativeFullyQualifiedName(Type serializedType) + { + var typeConverstionResult = _serializationConstraints.TryGetAssemblyAndTypeNameReplacementFromType( + serializedType, serializedType.Assembly.FullName, serializedType.FullName); + + if (typeConverstionResult.AssemblyName != serializedType.Assembly.FullName || + typeConverstionResult.TypeName != serializedType.FullName) + { + return $"{typeConverstionResult.TypeName}, {typeConverstionResult.AssemblyName}"; + } + + return null; + } + } +} \ No newline at end of file diff --git a/Gigya.Microdot.SharedLogic/Logging/LogBase.cs b/Gigya.Microdot.SharedLogic/Logging/LogBase.cs index 2f9eab2f..462727ee 100644 --- a/Gigya.Microdot.SharedLogic/Logging/LogBase.cs +++ b/Gigya.Microdot.SharedLogic/Logging/LogBase.cs @@ -20,13 +20,13 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; -using Gigya.Microdot.Interfaces.Logging; namespace Gigya.Microdot.SharedLogic.Logging { diff --git a/Gigya.Microdot.SharedLogic/Logging/TagsExtractor.cs b/Gigya.Microdot.SharedLogic/Logging/TagsExtractor.cs index bd8db218..32ef8350 100644 --- a/Gigya.Microdot.SharedLogic/Logging/TagsExtractor.cs +++ b/Gigya.Microdot.SharedLogic/Logging/TagsExtractor.cs @@ -20,19 +20,19 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.SharedLogic.Events; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.SharedLogic.Events; namespace Gigya.Microdot.SharedLogic.Logging { - public static class TagsExtractor + public static class TagsExtractor { private const string prefix = "tags."; diff --git a/Gigya.Microdot.SharedLogic/Measurement/DataSourceOperationStopwatches.cs b/Gigya.Microdot.SharedLogic/Measurement/DataSourceOperationStopwatches.cs index 3957dfa0..42a10cef 100644 --- a/Gigya.Microdot.SharedLogic/Measurement/DataSourceOperationStopwatches.cs +++ b/Gigya.Microdot.SharedLogic/Measurement/DataSourceOperationStopwatches.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.SharedLogic.Utils; using System; using System.Linq; -using Gigya.Microdot.SharedLogic.Utils; namespace Gigya.Microdot.SharedLogic.Measurement { diff --git a/Gigya.Microdot.SharedLogic/Measurement/DataSourceStopwatches.cs b/Gigya.Microdot.SharedLogic/Measurement/DataSourceStopwatches.cs index 0c4b9670..d35cbe85 100644 --- a/Gigya.Microdot.SharedLogic/Measurement/DataSourceStopwatches.cs +++ b/Gigya.Microdot.SharedLogic/Measurement/DataSourceStopwatches.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using Gigya.Microdot.SharedLogic.Utils; +using System; namespace Gigya.Microdot.SharedLogic.Measurement { diff --git a/Gigya.Microdot.SharedLogic/Measurement/Workload/Counter.cs b/Gigya.Microdot.SharedLogic/Measurement/Workload/Counter.cs new file mode 100644 index 00000000..2406858a --- /dev/null +++ b/Gigya.Microdot.SharedLogic/Measurement/Workload/Counter.cs @@ -0,0 +1,20 @@ +namespace Gigya.Microdot.SharedLogic.Measurement.Workload +{ + public class Counter + { + public string EventName { get; set; } + public string PerformanceCounterName { get; set; } + public double? Value { get; set; } + + public Counter() + { + + } + + public Counter(string eventName, string performanceCounterName) + { + EventName = eventName; + PerformanceCounterName = performanceCounterName; + } + } +} diff --git a/Gigya.Microdot.SharedLogic/Measurement/Workload/CpuTotalAssignedCoresCounter.cs b/Gigya.Microdot.SharedLogic/Measurement/Workload/CpuTotalAssignedCoresCounter.cs index 8b88c8f9..c8d3854c 100644 --- a/Gigya.Microdot.SharedLogic/Measurement/Workload/CpuTotalAssignedCoresCounter.cs +++ b/Gigya.Microdot.SharedLogic/Measurement/Workload/CpuTotalAssignedCoresCounter.cs @@ -1,7 +1,9 @@ -using System; +#pragma warning disable CA1416 // Validate platform compatibility +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Runtime.InteropServices; namespace Gigya.Microdot.SharedLogic.Measurement.Workload { @@ -28,9 +30,15 @@ public CpuTotalAssignedCoresCounter() /// public CpuTotalAssignedCoresCounter(Process p) { + _counters = new List(2 /* reasonable for a service with an affinity */); - foreach (var index in p.ProcessorAffinityList()) - _counters.Add(new PerformanceCounter("Processor", "% Processor Time", $"{index}")); + + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + foreach (var index in p.ProcessorAffinityList()) + _counters.Add(new PerformanceCounter("Processor", "% Processor Time", $"{index}")); + } } /// @@ -40,7 +48,8 @@ public CpuTotalAssignedCoresCounter(Process p) { try { - return Math.Round(_counters.Sum(c => c.NextValue()) / _counters.Count, 2); + + return Math.Round(_counters.Sum(c => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? c.NextValue() : double.NaN) / _counters.Count, 2); } catch { @@ -49,7 +58,7 @@ public CpuTotalAssignedCoresCounter(Process p) } /// - /// Dispose the obtainded counters. + /// Dispose the obtained counters. /// public void Dispose() { @@ -58,3 +67,4 @@ public void Dispose() } } } +#pragma warning restore CA1416 // Validate platform compatibility \ No newline at end of file diff --git a/Gigya.Microdot.SharedLogic/Measurement/Workload/IWorkloadMetrics.cs b/Gigya.Microdot.SharedLogic/Measurement/Workload/IWorkloadMetrics.cs index 2c18695b..efae1294 100644 --- a/Gigya.Microdot.SharedLogic/Measurement/Workload/IWorkloadMetrics.cs +++ b/Gigya.Microdot.SharedLogic/Measurement/Workload/IWorkloadMetrics.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Gigya.Microdot.SharedLogic.Measurement.Workload { diff --git a/Gigya.Microdot.SharedLogic/Measurement/Workload/LowSensitivityHealthCheck.cs b/Gigya.Microdot.SharedLogic/Measurement/Workload/LowSensitivityHealthCheck.cs index 41ee8055..5607ab5c 100644 --- a/Gigya.Microdot.SharedLogic/Measurement/Workload/LowSensitivityHealthCheck.cs +++ b/Gigya.Microdot.SharedLogic/Measurement/Workload/LowSensitivityHealthCheck.cs @@ -1,6 +1,6 @@ -using System; -using Gigya.Microdot.Interfaces.SystemWrappers; +using Gigya.Microdot.Interfaces.SystemWrappers; using Metrics; +using System; namespace Gigya.Microdot.SharedLogic.Measurement.Workload { diff --git a/Gigya.Microdot.SharedLogic/Measurement/Workload/PerformanceCounterByProcess.cs b/Gigya.Microdot.SharedLogic/Measurement/Workload/PerformanceCounterByProcess.cs index 97a4e84f..ce1e358e 100644 --- a/Gigya.Microdot.SharedLogic/Measurement/Workload/PerformanceCounterByProcess.cs +++ b/Gigya.Microdot.SharedLogic/Measurement/Workload/PerformanceCounterByProcess.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics; using System.Linq; +using System.Runtime.InteropServices; namespace Gigya.Microdot.SharedLogic.Measurement.Workload { @@ -32,7 +33,7 @@ public PerformanceCounterByProcess(string categoryName, string counterName) try { - return _counter?.NextValue(); + return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?_counter?.NextValue() : null; } catch { @@ -41,7 +42,7 @@ public PerformanceCounterByProcess(string categoryName, string counterName) _counter = GetCounterByCurrentProcess(); try { - return _counter?.NextValue(); + return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? _counter?.NextValue() : null; } catch { @@ -52,21 +53,32 @@ public PerformanceCounterByProcess(string categoryName, string counterName) private PerformanceCounter GetCounterByCurrentProcess() { - var instanceName = GetInstanceNameByProcessId(Process.GetCurrentProcess().Id) ?? Process.GetCurrentProcess().ProcessName; - return new PerformanceCounter(_categoryName, _counterName, instanceName); + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + var instanceName = GetInstanceNameByProcessId(Process.GetCurrentProcess().Id) ?? + Process.GetCurrentProcess().ProcessName; + return new PerformanceCounter(_categoryName, _counterName, instanceName); + } + + return null; } private static string GetInstanceNameByProcessId(int pid) { - var processName = Process.GetCurrentProcess().ProcessName; - foreach (string instanceName in new PerformanceCounterCategory("Process").GetInstanceNames().Where(i => i.StartsWith(processName))) + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - using (var pidCounter = new PerformanceCounter("Process", "ID Process", instanceName, true)) + var processName = Process.GetCurrentProcess().ProcessName; + foreach (string instanceName in new PerformanceCounterCategory("Process").GetInstanceNames() + .Where(i => i.StartsWith(processName))) { - if ((int)pidCounter.NextValue() == pid) - return instanceName; + using (var pidCounter = new PerformanceCounter("Process", "ID Process", instanceName, true)) + { + if ((int)pidCounter.NextValue() == pid) + return instanceName; + } } } + return null; } diff --git a/Gigya.Microdot.SharedLogic/Measurement/Workload/PerformanceEventListener.cs b/Gigya.Microdot.SharedLogic/Measurement/Workload/PerformanceEventListener.cs new file mode 100644 index 00000000..5d1dadd7 --- /dev/null +++ b/Gigya.Microdot.SharedLogic/Measurement/Workload/PerformanceEventListener.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.Tracing; +using System.Linq; + +namespace Gigya.Microdot.SharedLogic.Measurement.Workload +{ + public class PerformanceEventListener : EventListener + { + private static readonly string[] EventSources = { + "System.Runtime", + "System.Net.NameResolution", + "System.Net.Http", + "System.Net.Sockets", + "System.Net.Security", + "Gigya.EventCounters" + }; + + private const string EventCounters = "EventCounters"; + + private readonly Func _getConfig; + private readonly Dictionary _counters; + private readonly Dictionary _perfCounters; + + public PerformanceEventListener(Func getConfig) + { + _getConfig = getConfig; + _counters = new Dictionary(); + _perfCounters = new Dictionary(); + } + + public bool Subscribe(string performanceCounterName) + { + string counterName = NormalizeCounterName(performanceCounterName); + string eventCounter; + + var translationDictionary = _getConfig().PerformanceCountersToEventCounters; + if (translationDictionary == null || !translationDictionary.ContainsKey(counterName)) + eventCounter = counterName; + else + eventCounter = translationDictionary[counterName]; + if (_counters.ContainsKey(eventCounter)) + return true; + + Counter counter = new Counter(eventCounter, performanceCounterName); + _counters.Add(eventCounter, counter); + _perfCounters.Add(performanceCounterName, counter); + + return true; + } + + public double? ReadPerfCounter(string performanceCounterName) + { + if (_perfCounters.ContainsKey(performanceCounterName)) + return _perfCounters[performanceCounterName].Value; + + return null; + } + + protected override void OnEventSourceCreated(EventSource eventSource) + { + if (EventSources.Contains(eventSource.Name)) + { + Dictionary refreshInterval = new Dictionary { { "EventCounterIntervalSec", "1" } }; + EnableEvents(eventSource, EventLevel.LogAlways, EventKeywords.All, refreshInterval); + } + } + + protected override void OnEventWritten(EventWrittenEventArgs eventData) + { + if (eventData.EventName is EventCounters) + { + for (int i = 0; i < eventData.Payload?.Count; i++) + { + if (eventData.Payload[i] is IDictionary eventPayload) + { + var (Name, Value) = GetMetric(eventPayload); + if (_counters.ContainsKey(Name)) + _counters[Name].Value = Value; + } + } + } + } + + private static (string Name, double Value) GetMetric(IDictionary eventPayload) + { + string name = string.Empty; + double value = 0; + foreach (KeyValuePair payload in eventPayload) + { + switch (payload.Key) + { + case "Name": + name = payload.Value.ToString(); + break; + case "Mean": + case "Increment": + value = Convert.ToDouble(payload.Value); + break; + } + } + return (name, value); + } + + private static string NormalizeCounterName(string name) + { + return name.Replace("#", "").Replace("%", "").Trim().Replace(" ", "_").Replace("/", "_").ToLower(); + } + } +} \ No newline at end of file diff --git a/Gigya.Microdot.SharedLogic/Measurement/Workload/WorkloadMetrics.cs b/Gigya.Microdot.SharedLogic/Measurement/Workload/WorkloadMetrics.cs index ec6064ad..be9529e1 100644 --- a/Gigya.Microdot.SharedLogic/Measurement/Workload/WorkloadMetrics.cs +++ b/Gigya.Microdot.SharedLogic/Measurement/Workload/WorkloadMetrics.cs @@ -1,9 +1,11 @@ -using System; -using System.Linq; -using Gigya.Microdot.Interfaces.Logging; +using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic.Monitor; using Metrics; +using Metrics.EventCounters.CPU; +using System; +using System.Diagnostics; +using System.Linq; using Timer = System.Threading.Timer; namespace Gigya.Microdot.SharedLogic.Measurement.Workload @@ -13,49 +15,100 @@ public sealed class WorkloadMetrics : IWorkloadMetrics private readonly AggregatingHealthStatus _healthStatus; private readonly Func _getConfig; private readonly IDateTime _dateTime; - - readonly PerformanceCounterByProcess _virtualBytes = new PerformanceCounterByProcess("Process", "Virtual Bytes"); - readonly PerformanceCounterByProcess _privateBytes = new PerformanceCounterByProcess("Process", "Private Bytes"); - readonly PerformanceCounterByProcess _workingSet = new PerformanceCounterByProcess("Process", "Working Set"); - readonly PerformanceCounterByProcess _threadCount = new PerformanceCounterByProcess("Process", "Thread Count"); - readonly PerformanceCounterByProcess _dotNetThreadCount = new PerformanceCounterByProcess(".Net CLR LocksAndThreads", "# of current logical Threads"); - readonly PerformanceCounterByProcess _gen2Collections = new PerformanceCounterByProcess(".NET CLR Memory", "# Gen 2 Collections"); - readonly PerformanceCounterByProcess _timeInGc = new PerformanceCounterByProcess(".NET CLR Memory", "% Time in GC"); - readonly CpuUsageCounterByProcess _processorTimePercent; - readonly CpuTotalAssignedCoresCounter _processorTotalPercent = new CpuTotalAssignedCoresCounter(); + private readonly PerformanceEventListener _eventListener; private LowSensitivityHealthCheck _cpuUsageHealthCheck; private LowSensitivityHealthCheck _threadsCountHealthCheck; private LowSensitivityHealthCheck _orleansQueueHealthCheck; + private readonly ICpuUsageCalculator _cpuUsageCalculator; private readonly MetricsContext _context = Metric.Context("Workload"); private Timer _triggerHealthChecksEvery5Seconds; private bool _disposed; - + //private const int MegabyteToByte = 1024 * 1024; private ILog Log { get; } - public WorkloadMetrics(Func getAggregatingHealthStatus, Func getConfig, IDateTime dateTime, ILog log) + + public WorkloadMetrics(Func getAggregatingHealthStatus, Func getConfig, IDateTime dateTime, ILog log, PerformanceEventListener eventListener) { Log = log; _getConfig = getConfig; _dateTime = dateTime; + _eventListener = eventListener; + _cpuUsageCalculator = CpuHelper.GetOSCpuUsageCalculator(); _healthStatus = getAggregatingHealthStatus("Workload"); - _processorTimePercent = new CpuUsageCounterByProcess(); } - + public void Init() { - _context.Context("CPU").Gauge("Processor Affinity", () => _processorTimePercent.AssignedCoresCount, Unit.Items); - _context.Context("CPU").Gauge("CPU usage", () => ReadPerfCounter(_processorTimePercent), Unit.Percent); - _context.Context("CPU").Gauge("CPU total", () => _processorTotalPercent.GetValue() ?? 0, Unit.Percent); - _context.Context("CPU").Gauge("Thread count", () => { double threads = ReadPerfCounter(_threadCount); return threads < 0 || threads > 1000000 ? 0 : threads; }, Unit.Items); - _context.Context("CPU").Gauge("DotNet logical thread count", () => { double threads = ReadPerfCounter(_dotNetThreadCount); return threads < 0 || threads > 1000000 ? 0 : threads; }, Unit.Items); - _context.Context("Memory").Gauge("Working set", () => ReadPerfCounter(_workingSet), Unit.Bytes); - _context.Context("Memory").Gauge("Private", () => ReadPerfCounter(_virtualBytes), Unit.Bytes); - _context.Context("Memory").Gauge("Virtual", () => ReadPerfCounter(_privateBytes), Unit.Bytes); - _context.Context("GC").Gauge("Gen-2 collections", () => ReadPerfCounter(_gen2Collections), Unit.Events); - _context.Context("GC").Gauge("Time in GC", () => ReadPerfCounter(_timeInGc), Unit.Percent); + _eventListener.Subscribe("% Processor Time"); + _eventListener.Subscribe("# of current logical Threads"); + _eventListener.Subscribe("threadpool-queue-length"); + _eventListener.Subscribe("threadpool-completed-items-count"); + _eventListener.Subscribe("working-set"); + _eventListener.Subscribe("# Bytes in all Heaps"); + _eventListener.Subscribe("Allocated Bytes/second"); + _eventListener.Subscribe("poh-size"); + _eventListener.Subscribe("loh-size"); + _eventListener.Subscribe("# Gen 0 Collections"); + _eventListener.Subscribe("# Gen 1 Collections"); + _eventListener.Subscribe("# Gen 2 Collections"); + _eventListener.Subscribe("Gen 0 heap size"); + _eventListener.Subscribe("Gen 1 heap size"); + _eventListener.Subscribe("Gen 2 heap size"); + _eventListener.Subscribe("Time in GC"); + _eventListener.Subscribe("gc-fragmentation"); + _eventListener.Subscribe("# of Exceps Thrown / Sec"); + _eventListener.Subscribe("active-timer-count"); + + _context.Context("CPU").Gauge("Machine Cpu Usage", () => _cpuUsageCalculator.Calculate().MachineCpuUsage, Unit.Percent); + _context.Context("CPU").Gauge("Processor Affinity", () => Process.GetCurrentProcess().ProcessorAffinityList().Count(), Unit.Items); + _context.Context("CPU").Gauge("CPU usage", () => ReadPerfCounter("% Processor Time"), Unit.Percent); + _context.Context("ThreadPool").Gauge("Thread Count", () => { double threads = ReadPerfCounter("# of current logical Threads"); return threads < 0 || threads > 1000000 ? 0 : threads; }, Unit.Items); + _context.Context("ThreadPool").Gauge("Queue Length", () => { double threads = ReadPerfCounter("threadpool-queue-length"); return threads < 0 || threads > 1000000 ? 0 : threads; }, Unit.Items); + _context.Context("ThreadPool").Gauge("Completed Item Count", () => { double threads = ReadPerfCounter("threadpool-completed-items-count"); return threads < 0 || threads > 1000000 ? 0 : threads; }, Unit.Items); + _context.Context("Memory").Gauge("Working set", () => ReadPerfCounter("working-set"), Unit.MegaBytes); + _context.Context("Memory").Gauge("MegaBytes in all Heaps", () => ReadPerfCounter("# Bytes in all Heaps"), Unit.MegaBytes); + _context.Context("Memory").Gauge("Allocated Bytes/second", () => ReadPerfCounter("Allocated Bytes/second"), Unit.Bytes); + _context.Context("Memory").Gauge("POH Size", () => ReadPerfCounter("poh-size"), Unit.Bytes); + _context.Context("Memory").Gauge("LOH Size", () => ReadPerfCounter("loh-size"), Unit.Bytes); + _context.Context("GC").Gauge("Gen-0 collections", () => ReadPerfCounter("# Gen 0 Collections"), Unit.Items); + _context.Context("GC").Gauge("Gen-1 collections", () => ReadPerfCounter("# Gen 1 Collections"), Unit.Items); + _context.Context("GC").Gauge("Gen-2 collections", () => ReadPerfCounter("# Gen 2 Collections"), Unit.Items); + _context.Context("GC").Gauge("Gen 0 heap size", () => ReadPerfCounter("Gen 0 heap size"), Unit.Bytes); + _context.Context("GC").Gauge("Gen 1 heap size", () => ReadPerfCounter("Gen 1 heap size"), Unit.Bytes); + _context.Context("GC").Gauge("Gen 2 heap size", () => ReadPerfCounter("Gen 2 heap size"), Unit.Bytes); + _context.Context("GC").Gauge("Time in GC", () => ReadPerfCounter("Time in GC"), Unit.Percent); + _context.Context("GC").Gauge("GC Fragmentation", () => ReadPerfCounter("gc-fragmentation"), Unit.Percent); + _context.Context("General").Gauge("Exceps Thrown / Sec", () => ReadPerfCounter("# of Exceps Thrown / Sec"), Unit.Items); + _context.Context("General").Gauge("Active Timers", () => ReadPerfCounter("active-timer-count"), Unit.Items); + +#if NET5_0_OR_GREATER + _eventListener.Subscribe("requests-started"); + _eventListener.Subscribe("requests-started-rate"); + _eventListener.Subscribe("requests-failed"); + _eventListener.Subscribe("requests-failed-rate"); + _eventListener.Subscribe("current-requests"); + _eventListener.Subscribe("http11-connections-current-total"); + _eventListener.Subscribe("http20-connections-current-total"); + _eventListener.Subscribe("http11-requests-queue-duration"); + _eventListener.Subscribe("http20-requests-queue-duration"); + _eventListener.Subscribe("outgoing-connections-established"); + _eventListener.Subscribe("incoming-connections-established"); + _eventListener.Subscribe("bytes-received"); + _eventListener.Subscribe("bytes-sent"); + + _context.Context("Http").Gauge("Requests Started", () => ReadPerfCounter("requests-started"), Unit.Requests); + _context.Context("Http").Gauge("Requests Started Rate", () => ReadPerfCounter("requests-started-rate"), Unit.Requests); + _context.Context("Http").Gauge("Requests Failed", () => ReadPerfCounter("requests-failed"), Unit.Requests); + _context.Context("Http").Gauge("Requests Failed Rate", () => ReadPerfCounter("requests-failed-rate"), Unit.Requests); + _context.Context("Http").Gauge("Current Requests", () => ReadPerfCounter("current-requests"), Unit.Requests); + _context.Context("Http").Gauge("Http11 Connections Current Total", () => ReadPerfCounter("http11-connections-current-total"), Unit.Custom("Connections")); + _context.Context("Http").Gauge("Http20 Connections Current Total", () => ReadPerfCounter("http20-connections-current-total"), Unit.Custom("Connections")); + _context.Context("Sockets").Gauge("Bytes Received", () => ReadPerfCounter("bytes-received"), Unit.Bytes); + _context.Context("Sockets").Gauge("Bytes Sent", () => ReadPerfCounter("bytes-sent"), Unit.Bytes); +#endif _cpuUsageHealthCheck = new LowSensitivityHealthCheck(CpuUsageHealth, () => _getConfig().MinUnhealthyDuration, _dateTime); _threadsCountHealthCheck = new LowSensitivityHealthCheck(ThreadsCountHealth, () => _getConfig().MinUnhealthyDuration, _dateTime); @@ -68,6 +121,16 @@ public void Init() _triggerHealthChecksEvery5Seconds = new Timer(TriggerHealthCheck, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)); } + private double ReadPerfCounter(string performanceCounterName) + { + if (_getConfig().ReadPerformanceCounters) + { + return _eventListener.ReadPerfCounter(performanceCounterName) ?? 0; + } + + return 0; + } + private void TriggerHealthCheck(object state) { try @@ -81,29 +144,17 @@ private void TriggerHealthCheck(object state) } } - - private double ReadPerfCounter(PerformanceCounterByProcess perfCounter) - { - if (_getConfig().ReadPerformanceCounters) - { - return perfCounter.GetValue() ?? 0; - } - else - return 0; - } - private HealthCheckResult CpuUsageHealth() { if (!_getConfig().ReadPerformanceCounters) return HealthCheckResult.Healthy("CPU Usage: Reading perf counter disabled by configuration"); - var cpuUsage = ReadPerfCounter(_processorTimePercent); + var cpuUsage = ReadPerfCounter("% Processor Time"); var maxCpuUsage = _getConfig().MaxHealthyCpuUsage; if (cpuUsage > maxCpuUsage) return HealthCheckResult.Unhealthy($"CPU Usage: {cpuUsage}% (unhealthy above {maxCpuUsage}%)"); - else - return HealthCheckResult.Healthy($"CPU Usage: {cpuUsage}% (unhealthy above {maxCpuUsage}%)"); + return HealthCheckResult.Healthy($"CPU Usage: {cpuUsage}% (unhealthy above {maxCpuUsage}%)"); } @@ -112,13 +163,12 @@ private HealthCheckResult ThreadsCountHealth() if (!_getConfig().ReadPerformanceCounters) return HealthCheckResult.Healthy("Threads: Reading perf counter disabled by configuration"); - var threads = ReadPerfCounter(_threadCount); + var threads = ReadPerfCounter("# of current logical Threads"); var maxThreads = _getConfig().MaxHealthyThreadsCount; if (threads > maxThreads) return HealthCheckResult.Unhealthy($"Threads: {threads} (unhealthy above {maxThreads})"); - else - return HealthCheckResult.Healthy($"Threads: {threads} (unhealthy above {maxThreads})"); + return HealthCheckResult.Healthy($"Threads: {threads} (unhealthy above {maxThreads})"); } @@ -143,17 +193,10 @@ public void Dispose() _disposed = true; _context?.Dispose(); + _cpuUsageCalculator?.Dispose(); _triggerHealthChecksEvery5Seconds?.Dispose(); - - _processorTimePercent.Dispose(); - _processorTotalPercent.Dispose(); - _virtualBytes.Dispose(); - _privateBytes.Dispose(); - _workingSet.Dispose(); - _threadCount.Dispose(); - _dotNetThreadCount.Dispose(); - _gen2Collections.Dispose(); - _timeInGc.Dispose(); } + } } + diff --git a/Gigya.Microdot.SharedLogic/Measurement/Workload/WorkloadMetricsConfig.cs b/Gigya.Microdot.SharedLogic/Measurement/Workload/WorkloadMetricsConfig.cs index 5229ebdf..0908643f 100644 --- a/Gigya.Microdot.SharedLogic/Measurement/Workload/WorkloadMetricsConfig.cs +++ b/Gigya.Microdot.SharedLogic/Measurement/Workload/WorkloadMetricsConfig.cs @@ -1,9 +1,6 @@ -using System; +using Gigya.Microdot.Interfaces.Configuration; +using System; using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Gigya.Microdot.Interfaces.Configuration; namespace Gigya.Microdot.SharedLogic.Measurement.Workload { @@ -34,5 +31,11 @@ public class WorkloadMetricsConfig : IConfigObject /// Service will report itself as unhealthy only if some unhelthy metric is unhealthy for at least the specified duration /// public TimeSpan MinUnhealthyDuration { get; set; } = TimeSpan.FromMinutes(3); + + public Dictionary PerformanceCountersToEventCounters { get; set; } = new Dictionary + { + { "processor_time", "cpu-usage"}, + { "of_current_logical_threads", "threadpool-thread-count"} + }; } } diff --git a/Gigya.Microdot.SharedLogic/Measurement/Workload/WorkloadMetricsWindows.cs b/Gigya.Microdot.SharedLogic/Measurement/Workload/WorkloadMetricsWindows.cs new file mode 100644 index 00000000..ae5fb9d6 --- /dev/null +++ b/Gigya.Microdot.SharedLogic/Measurement/Workload/WorkloadMetricsWindows.cs @@ -0,0 +1,159 @@ +using Gigya.Microdot.Interfaces.Logging; +using Gigya.Microdot.Interfaces.SystemWrappers; +using Gigya.Microdot.SharedLogic.Monitor; +using Metrics; +using System; +using System.Linq; +using Timer = System.Threading.Timer; + +namespace Gigya.Microdot.SharedLogic.Measurement.Workload +{ + public sealed class WorkloadMetricsWindows : IWorkloadMetrics + { + private readonly AggregatingHealthStatus _healthStatus; + private readonly Func _getConfig; + private readonly IDateTime _dateTime; + + readonly PerformanceCounterByProcess _virtualBytes = new PerformanceCounterByProcess("Process", "Virtual Bytes"); + readonly PerformanceCounterByProcess _privateBytes = new PerformanceCounterByProcess("Process", "Private Bytes"); + readonly PerformanceCounterByProcess _workingSet = new PerformanceCounterByProcess("Process", "Working Set"); + readonly PerformanceCounterByProcess _threadCount = new PerformanceCounterByProcess("Process", "Thread Count"); + readonly PerformanceCounterByProcess _dotNetThreadCount = new PerformanceCounterByProcess(".Net CLR LocksAndThreads", "# of current logical Threads"); + readonly PerformanceCounterByProcess _gen2Collections = new PerformanceCounterByProcess(".NET CLR Memory", "# Gen 2 Collections"); + readonly PerformanceCounterByProcess _timeInGc = new PerformanceCounterByProcess(".NET CLR Memory", "% Time in GC"); + readonly CpuUsageCounterByProcess _processorTimePercent; + readonly CpuTotalAssignedCoresCounter _processorTotalPercent = new CpuTotalAssignedCoresCounter(); + + private LowSensitivityHealthCheck _cpuUsageHealthCheck; + private LowSensitivityHealthCheck _threadsCountHealthCheck; + private LowSensitivityHealthCheck _orleansQueueHealthCheck; + + private readonly MetricsContext _context = Metric.Context("Workload"); + private Timer _triggerHealthChecksEvery5Seconds; + private bool _disposed; + + private ILog Log { get; } + + public WorkloadMetricsWindows(Func getAggregatingHealthStatus, Func getConfig, IDateTime dateTime, ILog log) + { + Log = log; + _getConfig = getConfig; + _dateTime = dateTime; + _healthStatus = getAggregatingHealthStatus("Workload"); + _processorTimePercent = new CpuUsageCounterByProcess(); + } + + + public void Init() + { + _context.Context("CPU").Gauge("Processor Affinity", () => _processorTimePercent.AssignedCoresCount, Unit.Items); + _context.Context("CPU").Gauge("CPU usage", () => ReadPerfCounter(_processorTimePercent), Unit.Percent); + _context.Context("CPU").Gauge("Machine Cpu Usage", () => _processorTotalPercent.GetValue() ?? 0, Unit.Percent); + _context.Context("ThreadPool").Gauge("Thread Count", () => { double threads = ReadPerfCounter(_threadCount); return threads < 0 || threads > 1000000 ? 0 : threads; }, Unit.Items); + _context.Context("ThreadPool").Gauge("DotNet logical thread count", () => { double threads = ReadPerfCounter(_dotNetThreadCount); return threads < 0 || threads > 1000000 ? 0 : threads; }, Unit.Items); + _context.Context("Memory").Gauge("Working set", () => ReadPerfCounter(_workingSet), Unit.Bytes); + _context.Context("Memory").Gauge("Private", () => ReadPerfCounter(_virtualBytes), Unit.Bytes); + _context.Context("Memory").Gauge("Virtual", () => ReadPerfCounter(_privateBytes), Unit.Bytes); + _context.Context("GC").Gauge("Gen-2 collections", () => ReadPerfCounter(_gen2Collections), Unit.Events); + _context.Context("GC").Gauge("Time in GC", () => ReadPerfCounter(_timeInGc), Unit.Percent); + + _cpuUsageHealthCheck = new LowSensitivityHealthCheck(CpuUsageHealth, () => _getConfig().MinUnhealthyDuration, _dateTime); + _threadsCountHealthCheck = new LowSensitivityHealthCheck(ThreadsCountHealth, () => _getConfig().MinUnhealthyDuration, _dateTime); + _orleansQueueHealthCheck = new LowSensitivityHealthCheck(OrleansRequestQueueHealth, () => _getConfig().MinUnhealthyDuration, _dateTime); + + _healthStatus.RegisterCheck("CPU Usage", _cpuUsageHealthCheck.GetHealthStatus); + _healthStatus.RegisterCheck("Threads Count", _threadsCountHealthCheck.GetHealthStatus); + _healthStatus.RegisterCheck("Orleans Queue", _orleansQueueHealthCheck.GetHealthStatus); + + _triggerHealthChecksEvery5Seconds = new Timer(TriggerHealthCheck, null, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(5)); + } + + private void TriggerHealthCheck(object state) + { + try + { + _cpuUsageHealthCheck.GetHealthStatus(); + _threadsCountHealthCheck.GetHealthStatus(); + } + catch (Exception ex) + { + Log.Warn(x => x("Error triggering workload health status", exception: ex)); + } + } + + + private double ReadPerfCounter(PerformanceCounterByProcess perfCounter) + { + if (_getConfig().ReadPerformanceCounters) + { + return perfCounter.GetValue() ?? 0; + } + else + return 0; + } + + private HealthCheckResult CpuUsageHealth() + { + if (!_getConfig().ReadPerformanceCounters) + return HealthCheckResult.Healthy("CPU Usage: Reading perf counter disabled by configuration"); + + var cpuUsage = ReadPerfCounter(_processorTimePercent); + var maxCpuUsage = _getConfig().MaxHealthyCpuUsage; + + if (cpuUsage > maxCpuUsage) + return HealthCheckResult.Unhealthy($"CPU Usage: {cpuUsage}% (unhealthy above {maxCpuUsage}%)"); + else + return HealthCheckResult.Healthy($"CPU Usage: {cpuUsage}% (unhealthy above {maxCpuUsage}%)"); + } + + + private HealthCheckResult ThreadsCountHealth() + { + if (!_getConfig().ReadPerformanceCounters) + return HealthCheckResult.Healthy("Threads: Reading perf counter disabled by configuration"); + + var threads = ReadPerfCounter(_threadCount); + var maxThreads = _getConfig().MaxHealthyThreadsCount; + + if (threads > maxThreads) + return HealthCheckResult.Unhealthy($"Threads: {threads} (unhealthy above {maxThreads})"); + else + return HealthCheckResult.Healthy($"Threads: {threads} (unhealthy above {maxThreads})"); + } + + + private HealthCheckResult OrleansRequestQueueHealth() + { + var queueLength = Metric.Context("Silo").DataProvider.CurrentMetricsData.Gauges + .FirstOrDefault(x => x.Name == "Request queue length")?.Value; + if (queueLength == null) + return HealthCheckResult.Healthy("Orleans queue length: unknown"); + + var maxLength = _getConfig().MaxHealthyOrleansQueueLength; + if (queueLength > maxLength) + return HealthCheckResult.Unhealthy($"Orleans queue length: {queueLength} (unhealthy above {maxLength})"); + + return HealthCheckResult.Healthy($"Orleans queue length: {queueLength} (unhealthy above {maxLength})"); + } + + public void Dispose() + { + if (_disposed) + return; + + _disposed = true; + _context?.Dispose(); + _triggerHealthChecksEvery5Seconds?.Dispose(); + + _processorTimePercent?.Dispose(); + _processorTotalPercent?.Dispose(); + _virtualBytes?.Dispose(); + _privateBytes?.Dispose(); + _workingSet?.Dispose(); + _threadCount?.Dispose(); + _dotNetThreadCount?.Dispose(); + _gen2Collections?.Dispose(); + _timeInGc?.Dispose(); + } + } +} diff --git a/Gigya.Microdot.SharedLogic/Monitor/AggregatingHealthStatus.cs b/Gigya.Microdot.SharedLogic/Monitor/AggregatingHealthStatus.cs index 8538627e..bfaea7b4 100644 --- a/Gigya.Microdot.SharedLogic/Monitor/AggregatingHealthStatus.cs +++ b/Gigya.Microdot.SharedLogic/Monitor/AggregatingHealthStatus.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Metrics; using System; using System.Collections.Generic; using System.Linq; -using Metrics; namespace Gigya.Microdot.SharedLogic.Monitor { diff --git a/Gigya.Microdot.SharedLogic/Monitor/ComponentHealthMonitor.cs b/Gigya.Microdot.SharedLogic/Monitor/ComponentHealthMonitor.cs index 938307ef..72c12d7d 100644 --- a/Gigya.Microdot.SharedLogic/Monitor/ComponentHealthMonitor.cs +++ b/Gigya.Microdot.SharedLogic/Monitor/ComponentHealthMonitor.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Metrics; using System; using System.Collections.Generic; -using Metrics; namespace Gigya.Microdot.SharedLogic.Monitor { diff --git a/Gigya.Microdot.SharedLogic/Monitor/HealthMonitor.cs b/Gigya.Microdot.SharedLogic/Monitor/HealthMonitor.cs index f208146a..f3404757 100644 --- a/Gigya.Microdot.SharedLogic/Monitor/HealthMonitor.cs +++ b/Gigya.Microdot.SharedLogic/Monitor/HealthMonitor.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Metrics; using System; using System.Collections.Concurrent; using System.Collections.Generic; -using Metrics; namespace Gigya.Microdot.SharedLogic.Monitor { diff --git a/Gigya.Microdot.SharedLogic/Monitor/IHealthMonitor.cs b/Gigya.Microdot.SharedLogic/Monitor/IHealthMonitor.cs index f427c56d..356d7985 100644 --- a/Gigya.Microdot.SharedLogic/Monitor/IHealthMonitor.cs +++ b/Gigya.Microdot.SharedLogic/Monitor/IHealthMonitor.cs @@ -20,9 +20,9 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Metrics; using System; using System.Collections.Generic; -using Metrics; namespace Gigya.Microdot.SharedLogic.Monitor { diff --git a/Gigya.Microdot.SharedLogic/Monitor/PassiveAggregatingHealthCheck.cs b/Gigya.Microdot.SharedLogic/Monitor/PassiveAggregatingHealthCheck.cs index e456c56a..ebcbb191 100644 --- a/Gigya.Microdot.SharedLogic/Monitor/PassiveAggregatingHealthCheck.cs +++ b/Gigya.Microdot.SharedLogic/Monitor/PassiveAggregatingHealthCheck.cs @@ -1,14 +1,14 @@ -using System; +using Gigya.Microdot.Interfaces.SystemWrappers; +using Metrics; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; -using Gigya.Microdot.Interfaces.SystemWrappers; -using Metrics; namespace Gigya.Microdot.SharedLogic.Monitor -{ +{ /// If you ever find you want this class as a pure health status not connected to Metrics.Net, /// feel free to split it (i.e. create a new class that only links between Metrics.Net and this health check). public class PassiveAggregatingHealthCheck : IPassiveAggregatingHealthCheck diff --git a/Gigya.Microdot.SharedLogic/Properties/AssemblyInfo.cs b/Gigya.Microdot.SharedLogic/Properties/AssemblyInfo.cs index f37148d6..abaddbf1 100644 --- a/Gigya.Microdot.SharedLogic/Properties/AssemblyInfo.cs +++ b/Gigya.Microdot.SharedLogic/Properties/AssemblyInfo.cs @@ -21,7 +21,6 @@ #endregion using Gigya.Microdot.SharedLogic; -using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/Gigya.Microdot.SharedLogic/Security/WindowsStoreCertificateLocator.cs b/Gigya.Microdot.SharedLogic/Security/CertificateLocator.cs similarity index 58% rename from Gigya.Microdot.SharedLogic/Security/WindowsStoreCertificateLocator.cs rename to Gigya.Microdot.SharedLogic/Security/CertificateLocator.cs index 13510c1e..6c5378d3 100644 --- a/Gigya.Microdot.SharedLogic/Security/WindowsStoreCertificateLocator.cs +++ b/Gigya.Microdot.SharedLogic/Security/CertificateLocator.cs @@ -20,37 +20,39 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.Configuration; +using Gigya.Microdot.SharedLogic.Exceptions; +using Gigya.Microdot.SharedLogic.HttpService; +using Gigya.Microdot.SharedLogic.Utils; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; +using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; -using Gigya.Microdot.Interfaces.Configuration; -using Gigya.Microdot.SharedLogic.Exceptions; -using Gigya.Microdot.SharedLogic.HttpService; -using Gigya.Microdot.SharedLogic.Utils; namespace Gigya.Microdot.SharedLogic.Security -{ - +{ + public class CertificateConfig { [Required] public string CertificatePath { get; set; } } - [ConfigurationRoot("Https",RootStrategy.ReplaceClassNameWithPath)] + [ConfigurationRoot("Https", RootStrategy.ReplaceClassNameWithPath)] public class HttpsConfiguration : IConfigObject { - public Dictionary Certificates { get; set; } + public Dictionary Certificates { get; set; } + public string LinuxCertsBasePath { get; set; } = "/etc/pki/tls/certs/"; } - public class WindowsStoreCertificateLocator : ICertificateLocator + public class CertificateLocatorWindows : ICertificateLocator { private Func HttpsConfigurationFactory { get; } private CurrentApplicationInfo AppInfo { get; } - public WindowsStoreCertificateLocator(Func httpsConfigurationFactory, CurrentApplicationInfo appInfo) + public CertificateLocatorWindows(Func httpsConfigurationFactory, CurrentApplicationInfo appInfo) { HttpsConfigurationFactory = httpsConfigurationFactory; AppInfo = appInfo; @@ -61,20 +63,18 @@ public X509Certificate2 GetCertificate(string certName) var config = HttpsConfigurationFactory(); if (!config.Certificates.TryGetValue(certName, out CertificateConfig certificateConfig)) { - throw new ConfigurationException($"No certificate configuration is found for {certName}" ); + throw new ConfigurationException($"No certificate configuration is found for {certName}"); } string certPath = certificateConfig.CertificatePath; string errorPrefix = $"Config entry '{certName}.CertificatePath' specifies '{certPath}'"; + var parts = certPath.Split('\\'); var storeLocation = StoreLocation.CurrentUser; var storeName = StoreName.My; GAssert.IsTrue(parts.Length == 3 && Enum.TryParse(parts[0], true, out storeLocation) && Enum.TryParse(parts[1], true, out storeName), - string.Format("{0}; invalid format; expecting <{1}>\\<{2}>\\", - errorPrefix, - string.Join("|", Enum.GetNames(typeof(StoreLocation))),string.Join("|", Enum.GetNames(typeof(StoreName))) - )); + $"{errorPrefix}; invalid format; expecting <{string.Join("|", Enum.GetNames(typeof(StoreLocation)))}>\\<{string.Join("|", Enum.GetNames(typeof(StoreName)))}>\\"); var store = new X509Store(storeName, storeLocation); store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); @@ -82,11 +82,46 @@ public X509Certificate2 GetCertificate(string certName) var foundCert = certs.Cast().FirstOrDefault(cer => cer.GetNameInfo(X509NameType.SimpleName, false) == parts[2]); - errorPrefix += " and process runs under user '" + AppInfo.OsUser + "'"; - GAssert.IsTrue(foundCert != null, errorPrefix + ", but certificate was not found."); - GAssert.IsTrue(foundCert.HasPrivateKey, errorPrefix + ", but certificate does not contain a private key."); + errorPrefix += $" and process runs under user '{AppInfo.OsUser}'"; + GAssert.IsTrue(foundCert != null, $"{errorPrefix}, but certificate was not found."); + GAssert.IsTrue(foundCert.HasPrivateKey, $"{errorPrefix}, but certificate does not contain a private key."); return foundCert; } + } + public class CertificateLocatorLinux : ICertificateLocator + { + private Func HttpsConfigurationFactory { get; } + private CurrentApplicationInfo AppInfo { get; } + + public CertificateLocatorLinux(Func httpsConfigurationFactory, CurrentApplicationInfo appInfo) + { + HttpsConfigurationFactory = httpsConfigurationFactory; + AppInfo = appInfo; + } + + public X509Certificate2 GetCertificate(string certName) + { + var config = HttpsConfigurationFactory(); + if (!config.Certificates.TryGetValue(certName, out CertificateConfig certificateConfig)) + { + throw new ConfigurationException($"No certificate configuration is found for {certName}"); + } + + string certPath = certificateConfig.CertificatePath; + string errorPrefix = $"Config entry '{certName}.CertificatePath' specifies '{certPath}'"; + + certPath = $"{Path.Combine(config.LinuxCertsBasePath, certificateConfig.CertificatePath)}"; + + if (!File.Exists(certPath)) + throw new ConfigurationException($"{errorPrefix}. File not found: {certPath}"); + + var foundCert = new X509Certificate2(certPath); + + errorPrefix += $" and process runs under user '{AppInfo.OsUser}'"; + GAssert.IsTrue(foundCert != null, $"{errorPrefix}, but certificate was not found."); + GAssert.IsTrue(foundCert.HasPrivateKey, $"{errorPrefix}, but certificate does not contain a private key."); + return foundCert; + } } } \ No newline at end of file diff --git a/Gigya.Microdot.SharedLogic/Security/GigyaTypePolicySerializationBinder.cs b/Gigya.Microdot.SharedLogic/Security/GigyaTypePolicySerializationBinder.cs index 0ec0a22c..06a2832d 100644 --- a/Gigya.Microdot.SharedLogic/Security/GigyaTypePolicySerializationBinder.cs +++ b/Gigya.Microdot.SharedLogic/Security/GigyaTypePolicySerializationBinder.cs @@ -1,12 +1,8 @@ -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Globalization; -using System.Linq; -using System.Text.RegularExpressions; -using Gigya.Microdot.SharedLogic.Configurations; +#nullable enable + using Gigya.Microdot.SharedLogic.Configurations.Serialization; using Newtonsoft.Json.Serialization; +using System; namespace Gigya.Microdot.SharedLogic.Security { diff --git a/Gigya.Microdot.SharedLogic/ServiceArguments.cs b/Gigya.Microdot.SharedLogic/ServiceArguments.cs index 88be3f21..cded577e 100644 --- a/Gigya.Microdot.SharedLogic/ServiceArguments.cs +++ b/Gigya.Microdot.SharedLogic/ServiceArguments.cs @@ -166,9 +166,6 @@ private void ApplyDefaults() case ServiceStartupMode.CommandLineNonInteractive: ConsoleOutputMode = ConsoleOutputMode.Standard; break; - case ServiceStartupMode.WindowsService: - ConsoleOutputMode = ConsoleOutputMode.Disabled; - break; default: throw new ArgumentOutOfRangeException(); } @@ -183,9 +180,6 @@ private void ApplyDefaults() case ServiceStartupMode.VerifyConfigurations: SiloClusterMode = SiloClusterMode.PrimaryNode; break; - case ServiceStartupMode.WindowsService: - SiloClusterMode = SiloClusterMode.ZooKeeper; - break; default: throw new ArgumentOutOfRangeException(); } @@ -241,7 +235,7 @@ public static string GetHelpDocumentation() => @" -h, --help or /?: This help screen --ServiceStartupMode: Specifies under which mode to start the service (command - line, Windows service, etc). Possible values: + line, etc). Possible values: CommandLineInteractive: Specifies that the service will run in command-line mode, expecting input from the user. This is the default value when @@ -251,9 +245,6 @@ public static string GetHelpDocumentation() => @" line mode, not requiring any input from the user. This is the default value when compiled with 'Debug' when Console.IsInputRedirected == true. - WindowsService: Specifies that the service will run as a Windows service. - This is the default value when compiled with 'Release'. - VerifyConfigurations: Specifies that the service will run to verify configuration objects only (while performing only minimal required initialization). Available IConfigObject implementations (config @@ -271,7 +262,7 @@ The validation errors will be reported in console. CommandLineNonInteractive. Disabled: Specifies that log messages should not be written to the console - at all. This is the default when running as WindowsService. + at all. --SiloClusterMode: Specifies how a silo started in this service should behave in a cluster. Not relevant for non-Orleans services. Possible values: @@ -287,7 +278,7 @@ CommandLineNonInteractive or VerifyConfigurations. ZooKeeper: Specifies that this node belongs to a real cluster, which has its membership table managed by ZooKeeper and the reminder table stored on - an external database. Default when running as WindowsService. + an external database. --BasePortOverride: Specifies what base port should be used for the silo. Not relevant for non-Orleans services. This value takes precedence over any base @@ -345,13 +336,7 @@ public enum ServiceStartupMode /// default value when compiled with 'Debug' when Console.IsInputRedirected == true. /// CommandLineNonInteractive, - - /// - /// Specifies that the service will run as a Windows service. This is the default value when compiled with - /// 'Release'. - /// - WindowsService, - + /// /// Specifies that the service will run to verify configuration objects only (while performing only minimal required initialization). /// Available IConfigObject implementations (config objects) in service assemblies will be instantiated to pass validations. @@ -387,15 +372,14 @@ public enum ConsoleOutputMode Standard, /// - /// Specifies that log messages should not be written to the console at all. This is the default when running - /// as . + /// Specifies that log messages should not be written to the console at all. /// Disabled } /// - /// Specifies how a silo hosten in a service should find other nodes. + /// Specifies how a silo hosted in a service should find other nodes. /// public enum SiloClusterMode { @@ -422,7 +406,6 @@ public enum SiloClusterMode /// /// Specifies that this node belongs to a real cluster, which has it's membership table managed by ZooKeeper and /// the reminder table stored on an external database. This is the default when running as - /// . /// ZooKeeper } diff --git a/Gigya.Microdot.SharedLogic/SystemWrappers/DateTimeImpl.cs b/Gigya.Microdot.SharedLogic/SystemWrappers/DateTimeImpl.cs index e71cf5a3..ef13e29a 100644 --- a/Gigya.Microdot.SharedLogic/SystemWrappers/DateTimeImpl.cs +++ b/Gigya.Microdot.SharedLogic/SystemWrappers/DateTimeImpl.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.SystemWrappers; using System; using System.Threading; using System.Threading.Tasks; -using Gigya.Microdot.Interfaces.SystemWrappers; namespace Gigya.Microdot.SharedLogic.SystemWrappers { diff --git a/Gigya.Microdot.SharedLogic/SystemWrappers/FileSystem.cs b/Gigya.Microdot.SharedLogic/SystemWrappers/FileSystem.cs index 7f40c388..9a61fb0e 100644 --- a/Gigya.Microdot.SharedLogic/SystemWrappers/FileSystem.cs +++ b/Gigya.Microdot.SharedLogic/SystemWrappers/FileSystem.cs @@ -20,11 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Microdot.Interfaces.SystemWrappers; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; -using Gigya.Microdot.Interfaces.SystemWrappers; namespace Gigya.Microdot.SharedLogic.SystemWrappers { diff --git a/Gigya.Microdot.SharedLogic/Utils/Assert.cs b/Gigya.Microdot.SharedLogic/Utils/Assert.cs index 2eefa6b6..3d7cd93e 100644 --- a/Gigya.Microdot.SharedLogic/Utils/Assert.cs +++ b/Gigya.Microdot.SharedLogic/Utils/Assert.cs @@ -20,12 +20,13 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; using System; using System.Runtime.CompilerServices; using System.Runtime.Serialization; -using Gigya.Common.Contracts.Exceptions; -namespace Gigya.Microdot.SharedLogic.Utils { +namespace Gigya.Microdot.SharedLogic.Utils +{ /// A Gigya equivalent for Microsoft.VisualStudio.TestTools.UnitTesting.Assert, to prevent including that /// dependency, and to throw our own exception type. Assertion errors should be communicated to developers somehow in diff --git a/Gigya.Microdot.SharedLogic/Utils/Extensions.cs b/Gigya.Microdot.SharedLogic/Utils/Extensions.cs index 3e35e7e2..d57edf79 100644 --- a/Gigya.Microdot.SharedLogic/Utils/Extensions.cs +++ b/Gigya.Microdot.SharedLogic/Utils/Extensions.cs @@ -20,13 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.SharedLogic.Events; using System; using System.Collections.Generic; using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.SharedLogic.Events; namespace Gigya.Microdot.SharedLogic.Utils { diff --git a/Gigya.Microdot.SharedLogic/Utils/System.Diagnostics.cs b/Gigya.Microdot.SharedLogic/Utils/System.Diagnostics.cs index 67107a11..723b17ea 100644 --- a/Gigya.Microdot.SharedLogic/Utils/System.Diagnostics.cs +++ b/Gigya.Microdot.SharedLogic/Utils/System.Diagnostics.cs @@ -1,5 +1,8 @@ using System.Collections.Generic; - +using System.Runtime.InteropServices; +#if NET6_0_OR_GREATER +using System.Runtime.Versioning; +#endif // ReSharper disable CheckNamespace namespace System.Diagnostics { @@ -9,12 +12,21 @@ public static class ProcessExtensions /// /// Enumerates the indexes of cores assgined to the current process by CPU affinity. /// +#if NET6_0_OR_GREATER + [SupportedOSPlatformGuard("windows")] + [SupportedOSPlatformGuard("linux")] +#endif public static IEnumerable ProcessorAffinityList(this Process p) { - var mask = (ulong)p.ProcessorAffinity.ToInt64(); - for (var i = 0; i < 64; i++) - if ((mask & 1ul << i) > 0) - yield return i; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + var mask = (ulong)p.ProcessorAffinity.ToInt64(); + for (var i = 0; i < 64; i++) + if ((mask & 1ul << i) > 0) + yield return i; + } + else + throw new NotSupportedException($"Platform '{RuntimeInformation.OSDescription}' not supported"); } } diff --git a/Gigya.Microdot.SharedLogic/paket.references b/Gigya.Microdot.SharedLogic/paket.references deleted file mode 100644 index c1b081e6..00000000 --- a/Gigya.Microdot.SharedLogic/paket.references +++ /dev/null @@ -1,8 +0,0 @@ -Gigya.ServiceContract -Newtonsoft.Json -System.ComponentModel.Annotations -System.Diagnostics.PerformanceCounter -System.Net.Http -System.Threading.Tasks.Dataflow -System.ValueTuple -Microsoft.CSharp diff --git a/Gigya.Microdot.SharedLogic/paket.template b/Gigya.Microdot.SharedLogic/paket.template deleted file mode 100644 index fc250aeb..00000000 --- a/Gigya.Microdot.SharedLogic/paket.template +++ /dev/null @@ -1,10 +0,0 @@ -type - project -description - Various components and utilities shared between different parts of the Microdot framework. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices \ No newline at end of file diff --git a/Gigya.Microdot.Testing.Shared/App.config b/Gigya.Microdot.Testing.Shared/App.config deleted file mode 100644 index 69ebeb2f..00000000 --- a/Gigya.Microdot.Testing.Shared/App.config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/Gigya.Microdot.Testing.Shared/Gigya.Microdot.Testing.Shared.csproj b/Gigya.Microdot.Testing.Shared/Gigya.Microdot.Testing.Shared.csproj index 4a792fd2..ac072fef 100644 --- a/Gigya.Microdot.Testing.Shared/Gigya.Microdot.Testing.Shared.csproj +++ b/Gigya.Microdot.Testing.Shared/Gigya.Microdot.Testing.Shared.csproj @@ -1,23 +1,17 @@  - - netstandard2.0 - true - true - Gigya.Microdot.Testing.Shared - $(SolutionDir)main.ruleset - - - - - - - - - - - - - - + + Gigya.Microdot.Testing.Shared + + Tools to help write tests for Microdot services. + The project contains logic for both Orleans and Non-Orleans host testers. + + gigya microdot microservice microservices fakes mocks mocking unit-testing + + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.Testing.Shared/Service/DisposablePort.cs b/Gigya.Microdot.Testing.Shared/Service/DisposablePort.cs index de8c8961..6cccc758 100644 --- a/Gigya.Microdot.Testing.Shared/Service/DisposablePort.cs +++ b/Gigya.Microdot.Testing.Shared/Service/DisposablePort.cs @@ -1,19 +1,19 @@ -using System; +using Gigya.Microdot.SharedLogic; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.NetworkInformation; using System.Threading; -using Gigya.Microdot.SharedLogic; namespace Gigya.Microdot.Testing.Shared.Service { public class DisposablePort : IDisposable { public readonly int Port; - private readonly List _semaphores = new List(4); - private static ConcurrentDictionary portMaintainer = new ConcurrentDictionary(); + private readonly List _mutexes = new List(4); + private static ConcurrentDictionary portMaintainerMutex = new ConcurrentDictionary(); internal DisposablePort(int port) { @@ -22,11 +22,11 @@ internal DisposablePort(int port) public void Dispose() { - foreach (var x in _semaphores) + foreach (var x in _mutexes) { try { - portMaintainer.TryRemove(x, out _); + portMaintainerMutex.TryRemove(x, out _); x.Dispose(); } catch (Exception ex) @@ -72,7 +72,7 @@ public static DisposablePort GetPort(int retries, int rangeFrom, int rangeTo, in var randomPort = random.Next(rangeFrom, rangeTo); - // Check the every port in the sequence isn't occupoed + // Check the every port in the sequence isn't occupied bool freeRange = true; for (int port = randomPort; port < randomPort + sequence; port++) { @@ -94,7 +94,8 @@ public static DisposablePort GetPort(int retries, int rangeFrom, int rangeTo, in for (int port = randomPort; port < randomPort + sequence; port++) { var name = $"ServiceTester-{port}"; - if (Semaphore.TryOpenExisting(name, out var _)) + + if (Mutex.TryOpenExisting(name, out _)) { someOneElseWantThisPort = true; } @@ -102,9 +103,9 @@ public static DisposablePort GetPort(int retries, int rangeFrom, int rangeTo, in { try { - var item = new Semaphore(1, 1, name); - result._semaphores.Add(item); - portMaintainer.TryAdd(item, DateTime.UtcNow); + var item = new Mutex(true, name); + result._mutexes.Add(item); + portMaintainerMutex.TryAdd(item, DateTime.UtcNow); if (port == randomPort) { IsHttpSysLocked(port); @@ -127,7 +128,7 @@ public static DisposablePort GetPort(int retries, int rangeFrom, int rangeTo, in Console.WriteLine($"Service Tester found a free port: {randomPort}. " + $"After retries: {retry}. " + $"Initially occupied ports: {occupiedPorts.Count}. " + - $"Port maintainer contains: {portMaintainer.Count}. " + + $"Port maintainer contains: {portMaintainerMutex.Count}. " + $"New semaphore exceptions: {totalNewSemExceptions}. " + $"Total elapsed, ms: {sw.ElapsedMilliseconds}"); return result; @@ -138,7 +139,7 @@ public static DisposablePort GetPort(int retries, int rangeFrom, int rangeTo, in throw new Exception($"Can't find free port in range: [{rangeFrom}-{rangeTo}]." + $"Retries: {retries}. " + $"Currently occupied ports: {Occupied().Count}. " + - $"Port maintainer contains: {portMaintainer.Count}. " + + $"Port maintainer contains: {portMaintainerMutex.Count}. " + $"New semaphore exceptions: {totalNewSemExceptions}. " + $"Total elapsed, ms: {sw.ElapsedMilliseconds}." + $"Process id: {Process.GetCurrentProcess().Id}"); diff --git a/Gigya.Microdot.Testing.Shared/Service/NonOrleansServiceTester.cs b/Gigya.Microdot.Testing.Shared/Service/NonOrleansServiceTester.cs index e81fb3bf..11f0c063 100644 --- a/Gigya.Microdot.Testing.Shared/Service/NonOrleansServiceTester.cs +++ b/Gigya.Microdot.Testing.Shared/Service/NonOrleansServiceTester.cs @@ -22,10 +22,7 @@ #endregion Copyright -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Hosting.Service; -using Gigya.Microdot.Ninject.Host; using Gigya.Microdot.SharedLogic; using System; using System.Threading.Tasks; diff --git a/Gigya.Microdot.Testing.Shared/Service/ServiceTesterBase.cs b/Gigya.Microdot.Testing.Shared/Service/ServiceTesterBase.cs index 00295837..b8bb0ecc 100644 --- a/Gigya.Microdot.Testing.Shared/Service/ServiceTesterBase.cs +++ b/Gigya.Microdot.Testing.Shared/Service/ServiceTesterBase.cs @@ -23,17 +23,14 @@ #endregion Copyright using Gigya.Microdot.Fakes.Discovery; +using Gigya.Microdot.Ninject; using Gigya.Microdot.ServiceDiscovery.Rewrite; using Gigya.Microdot.ServiceProxy; using Gigya.Microdot.ServiceProxy.Caching; +using Gigya.Microdot.UnitTests.Caching.Host; using Ninject; using Ninject.Parameters; using System; -using Gigya.Microdot.Ninject; -using Gigya.Microdot.UnitTests.Caching.Host; -using Gigya.Microdot.Interfaces.Configuration; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; namespace Gigya.Microdot.Testing.Shared.Service { diff --git a/Gigya.Microdot.Testing.Shared/paket.references b/Gigya.Microdot.Testing.Shared/paket.references deleted file mode 100644 index 7c9388f8..00000000 --- a/Gigya.Microdot.Testing.Shared/paket.references +++ /dev/null @@ -1,5 +0,0 @@ -Gigya.ServiceContract -Ninject -System.Threading.Tasks.Dataflow -Microsoft.CSharp -System.Net.Http \ No newline at end of file diff --git a/Gigya.Microdot.Testing.Shared/paket.template b/Gigya.Microdot.Testing.Shared/paket.template deleted file mode 100644 index b262eb20..00000000 --- a/Gigya.Microdot.Testing.Shared/paket.template +++ /dev/null @@ -1,11 +0,0 @@ -type - project -description - Tools to help write tests for Microdot services. - The project contains logic for both Orleans and Non-Orleans host testers. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices fakes mocks mocking unit-testing \ No newline at end of file diff --git a/Gigya.Microdot.Testing/Gigya.Microdot.Testing.csproj b/Gigya.Microdot.Testing/Gigya.Microdot.Testing.csproj index b5d50716..ed60016e 100644 --- a/Gigya.Microdot.Testing/Gigya.Microdot.Testing.csproj +++ b/Gigya.Microdot.Testing/Gigya.Microdot.Testing.csproj @@ -1,24 +1,16 @@  - - netstandard2.0 - true - true - Gigya.Microdot.Testing - $(SolutionDir)main.ruleset - - - - - - - - - - - - - - - + + Gigya.Microdot.Testing + + Tools to help write tests for Microdot services. + The project contains logic for Orleans host testers. + + gigya microdot microservice microservices fakes mocks mocking unit-testing + + + + + + \ No newline at end of file diff --git a/Gigya.Microdot.Testing/Service/ServiceTester.cs b/Gigya.Microdot.Testing/Service/ServiceTester.cs index 483ef795..34971453 100644 --- a/Gigya.Microdot.Testing/Service/ServiceTester.cs +++ b/Gigya.Microdot.Testing/Service/ServiceTester.cs @@ -23,11 +23,8 @@ #endregion Copyright using Gigya.Common.Contracts.HttpService; -using Gigya.Microdot.Common.Tests; using Gigya.Microdot.Fakes; -using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Hosting.Service; -using Gigya.Microdot.Ninject.Host; using Gigya.Microdot.Orleans.Hosting; using Gigya.Microdot.Orleans.Ninject.Host; using Gigya.Microdot.SharedLogic; @@ -73,14 +70,14 @@ public ServiceTester(ServiceArguments serviceArguments = null, Type customSerial private void Initialize() { - Host = new TServiceHost() + Host = new TServiceHost { FailServiceStartOnConfigError = false }; BasePort = ServiceArguments.BasePortOverride ?? GetBasePortFromHttpServiceAttribute(); - this.SiloStopped = Task.Run(() => this.Host.Run((ServiceArguments)this.ServiceArguments)); + SiloStopped = Task.Run(() => Host.Run(ServiceArguments)); //Silo is ready or failed to start Task.WaitAny(SiloStopped, Host.WaitForServiceStartedAsync()); @@ -101,7 +98,7 @@ private void Initialize() throw new Exception("Silo Failed to start"); } - protected int GetBasePortFromHttpServiceAttribute() + private int GetBasePortFromHttpServiceAttribute() { var commonConfig = new BaseCommonConfig(); var mapper = new OrleansServiceInterfaceMapper(new AssemblyProvider(new ApplicationDirectoryProvider(commonConfig), commonConfig, new ConsoleLog())); diff --git a/Gigya.Microdot.Testing/paket.references b/Gigya.Microdot.Testing/paket.references deleted file mode 100644 index dd8cf923..00000000 --- a/Gigya.Microdot.Testing/paket.references +++ /dev/null @@ -1,6 +0,0 @@ -Gigya.ServiceContract -Ninject -Microsoft.Orleans.Client -Microsoft.CSharp -System.Net.Http - diff --git a/Gigya.Microdot.Testing/paket.template b/Gigya.Microdot.Testing/paket.template deleted file mode 100644 index 29a14918..00000000 --- a/Gigya.Microdot.Testing/paket.template +++ /dev/null @@ -1,11 +0,0 @@ -type - project -description - Tools to help write tests for Microdot services. - The project contains logic for Orleans host testers. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices fakes mocks mocking unit-testing \ No newline at end of file diff --git a/Gigya.ServiceContract/.paket/Paket.Restore.targets b/Gigya.ServiceContract/.paket/Paket.Restore.targets deleted file mode 100644 index 8cb5986c..00000000 --- a/Gigya.ServiceContract/.paket/Paket.Restore.targets +++ /dev/null @@ -1,488 +0,0 @@ - - - - - - - $(MSBuildAllProjects);$(MSBuildThisFileFullPath) - - $(MSBuildVersion) - 15.0.0 - false - true - - true - $(MSBuildThisFileDirectory) - $(MSBuildThisFileDirectory)..\ - $(PaketRootPath)paket-files\paket.restore.cached - $(PaketRootPath)paket.lock - classic - proj - assembly - native - /Library/Frameworks/Mono.framework/Commands/mono - mono - - - $(PaketRootPath)paket.bootstrapper.exe - $(PaketToolsPath)paket.bootstrapper.exe - $([System.IO.Path]::GetDirectoryName("$(PaketBootStrapperExePath)"))\ - - "$(PaketBootStrapperExePath)" - $(MonoPath) --runtime=v4.0.30319 "$(PaketBootStrapperExePath)" - - - True - - - False - - $(BaseIntermediateOutputPath.TrimEnd('\').TrimEnd('\/')) - - - - - - - - - $(PaketRootPath)paket - $(PaketToolsPath)paket - - - - - - $(PaketRootPath)paket.exe - $(PaketToolsPath)paket.exe - - - - - - <_DotnetToolsJson Condition="Exists('$(PaketRootPath)/.config/dotnet-tools.json')">$([System.IO.File]::ReadAllText("$(PaketRootPath)/.config/dotnet-tools.json")) - <_ConfigContainsPaket Condition=" '$(_DotnetToolsJson)' != ''">$(_DotnetToolsJson.Contains('"paket"')) - <_ConfigContainsPaket Condition=" '$(_ConfigContainsPaket)' == ''">false - - - - - - - - - - - <_PaketCommand>dotnet paket - - - - - - $(PaketToolsPath)paket - $(PaketBootStrapperExeDir)paket - - - paket - - - - - <_PaketExeExtension>$([System.IO.Path]::GetExtension("$(PaketExePath)")) - <_PaketCommand Condition=" '$(_PaketCommand)' == '' AND '$(_PaketExeExtension)' == '.dll' ">dotnet "$(PaketExePath)" - <_PaketCommand Condition=" '$(_PaketCommand)' == '' AND '$(OS)' != 'Windows_NT' AND '$(_PaketExeExtension)' == '.exe' ">$(MonoPath) --runtime=v4.0.30319 "$(PaketExePath)" - <_PaketCommand Condition=" '$(_PaketCommand)' == '' ">"$(PaketExePath)" - - - - - - - - - - - - - - - - - - - - - true - $(NoWarn);NU1603;NU1604;NU1605;NU1608 - false - true - - - - - - - - - $([System.IO.File]::ReadAllText('$(PaketRestoreCacheFile)')) - - - - - - - $([System.Text.RegularExpressions.Regex]::Split(`%(Identity)`, `": "`)[0].Replace(`"`, ``).Replace(` `, ``)) - $([System.Text.RegularExpressions.Regex]::Split(`%(Identity)`, `": "`)[1].Replace(`"`, ``).Replace(` `, ``)) - - - - - %(PaketRestoreCachedKeyValue.Value) - %(PaketRestoreCachedKeyValue.Value) - - - - - true - false - true - - - - - true - - - - - - - - - - - - - - - - - - - $(PaketIntermediateOutputPath)\$(MSBuildProjectFile).paket.references.cached - - $(MSBuildProjectFullPath).paket.references - - $(MSBuildProjectDirectory)\$(MSBuildProjectName).paket.references - - $(MSBuildProjectDirectory)\paket.references - - false - true - true - references-file-or-cache-not-found - - - - - $([System.IO.File]::ReadAllText('$(PaketReferencesCachedFilePath)')) - $([System.IO.File]::ReadAllText('$(PaketOriginalReferencesFilePath)')) - references-file - false - - - - - false - - - - - true - target-framework '$(TargetFramework)' or '$(TargetFrameworks)' files @(PaketResolvedFilePaths) - - - - - - - - - - - false - true - - - - - - - - - - - $([System.String]::Copy('%(PaketReferencesFileLines.Identity)').Split(',').Length) - $([System.String]::Copy('%(PaketReferencesFileLines.Identity)').Split(',')[0]) - $([System.String]::Copy('%(PaketReferencesFileLines.Identity)').Split(',')[1]) - $([System.String]::Copy('%(PaketReferencesFileLines.Identity)').Split(',')[4]) - $([System.String]::Copy('%(PaketReferencesFileLines.Identity)').Split(',')[5]) - - - %(PaketReferencesFileLinesInfo.PackageVersion) - All - runtime - runtime - true - true - - - - - $(PaketIntermediateOutputPath)/$(MSBuildProjectFile).paket.clitools - - - - - - - - - $([System.String]::Copy('%(PaketCliToolFileLines.Identity)').Split(',')[0]) - $([System.String]::Copy('%(PaketCliToolFileLines.Identity)').Split(',')[1]) - - - %(PaketCliToolFileLinesInfo.PackageVersion) - - - - - - - - - - false - - - - - - <_NuspecFilesNewLocation Include="$(PaketIntermediateOutputPath)\$(Configuration)\*.nuspec"/> - - - - - - $(MSBuildProjectDirectory)/$(MSBuildProjectFile) - true - false - true - false - true - false - true - false - true - $(PaketIntermediateOutputPath)\$(Configuration) - $(PaketIntermediateOutputPath) - - - - <_NuspecFiles Include="$(AdjustedNuspecOutputPath)\*.$(PackageVersion.Split(`+`)[0]).nuspec"/> - - - - - - - - - - - - - - - - - - - - - diff --git a/Gigya.ServiceContract/.paket/paket.bootstrapper.exe b/Gigya.ServiceContract/.paket/paket.bootstrapper.exe deleted file mode 100644 index b98e000b..00000000 Binary files a/Gigya.ServiceContract/.paket/paket.bootstrapper.exe and /dev/null differ diff --git a/Gigya.ServiceContract/.paket/paket.exe b/Gigya.ServiceContract/.paket/paket.exe deleted file mode 100644 index 3e92760f..00000000 Binary files a/Gigya.ServiceContract/.paket/paket.exe and /dev/null differ diff --git a/Gigya.ServiceContract/.paket/paket.targets b/Gigya.ServiceContract/.paket/paket.targets deleted file mode 100644 index 0fd370f9..00000000 --- a/Gigya.ServiceContract/.paket/paket.targets +++ /dev/null @@ -1,41 +0,0 @@ - - - - - true - - true - $(MSBuildThisFileDirectory) - $(MSBuildThisFileDirectory)..\ - /Library/Frameworks/Mono.framework/Commands/mono - mono - - - - $(PaketToolsPath)paket.exe - $(PaketToolsPath)paket.bootstrapper.exe - "$(PaketExePath)" - $(MonoPath) --runtime=v4.0.30319 "$(PaketExePath)" - "$(PaketBootStrapperExePath)" $(PaketBootStrapperCommandArgs) - $(MonoPath) --runtime=v4.0.30319 $(PaketBootStrapperExePath) $(PaketBootStrapperCommandArgs) - - $(MSBuildProjectDirectory)\paket.references - $(MSBuildStartupDirectory)\paket.references - $(MSBuildProjectFullPath).paket.references - $(PaketCommand) restore --references-files "$(PaketReferences)" - $(PaketBootStrapperCommand) - - RestorePackages; $(BuildDependsOn); - - - - - - - - - - - - - diff --git a/Gigya.ServiceContract/.paket/restore.bat b/Gigya.ServiceContract/.paket/restore.bat deleted file mode 100644 index deb7a57f..00000000 --- a/Gigya.ServiceContract/.paket/restore.bat +++ /dev/null @@ -1,7 +0,0 @@ -@echo off -cd /d %~dp0 -paket.bootstrapper.exe -paket.exe restore -echo. -echo. -pause \ No newline at end of file diff --git a/Gigya.ServiceContract/.paket/update.bat b/Gigya.ServiceContract/.paket/update.bat deleted file mode 100644 index 3c4773b2..00000000 --- a/Gigya.ServiceContract/.paket/update.bat +++ /dev/null @@ -1,7 +0,0 @@ -@echo off -cd /d %~dp0 -paket.bootstrapper.exe -paket.exe update -echo. -echo. -pause \ No newline at end of file diff --git a/Gigya.ServiceContract/Attributes/CachedAttribute.cs b/Gigya.ServiceContract/Attributes/CachedAttribute.cs deleted file mode 100644 index 99487c2f..00000000 --- a/Gigya.ServiceContract/Attributes/CachedAttribute.cs +++ /dev/null @@ -1,350 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; - -namespace Gigya.Common.Contracts.Attributes -{ - // - // Specifies that the method should be cached using the CachingProxy.Set the relevant properties to control caching settings.Note - // that clients may override these preferences with their own.Also note that clients using older versions of Microdot may ignore some - // of these settings. - // - [AttributeUsage(AttributeTargets.Method)] - public class CachedAttribute : Attribute, IMethodCachingSettings - { - public CachedAttribute() - { - if (RefreshTime > ExpirationTime) - throw new ArgumentException("RefreshTime cannot be longer than ExpirationTime"); - - if ((ResponseKindsToCache & ResponseKindsToIgnore) > 0) - throw new ArgumentException("You cannot define a specific response kind both in ResponseKindsToCache and ResponseKindsToIgnore"); - } - - /// Defines which kinds of responses clients should cache (non-null, null, exceptions, etc). Default: non-null and null - /// responses. Note that if the client called the method and received a response that needs to be cached (e.g. non-null), then later - /// refreshes the response and receives a response that shouldn't be cached (e.g. null), it will remove the previous response from - /// the cache, unless that kind of response is set to be ignored (see ). Also note that if you - /// choose to cache exceptions, there's currently no way to revoke them (you can't add revoke keys to exceptions). - public ResponseKinds ResponseKindsToCache { get; set; } - - - /// When a client has a cached response but tries to obtain a fresh value (since it was revoked or is considered old), it - /// will ignore bad responses (e.g. exceptions) and return the last-good value instead. This enum defines which kinds of responses - /// to ignore. Note that you may not define the same kind both here and in . - /// Default: all exceptions. - public ResponseKinds ResponseKindsToIgnore { get; set; } - - - /// You can either manually revoke responses from client caches (by returning Revocable<> responses and using - /// an ICacheRevoker to revoke them), or define a time-to-live for cached responses so that clients will periodically fetch - /// up-to-date responses. Using manual revokes is preferred since revoke messages typically arrive to clients immediately so they - /// don't keep using stale responses once something was changed, i.e. they'll be "strongly consistent" instead of "eventually - /// consistent". Using time-to-live will cause clients to use stale responses up to , and - /// they will generate a constant stream of requests (as long as they use particular pieces of data) to fetch up-to-date values, - /// even if the responses haven't changed. - public RefreshMode RefreshMode { get; set; } - - - /// - /// Default: 1 minute. Once a response was cached, and assuming refreshing is enabled as per , - /// clients will periodically ATTEMPT to fetch a fresh response. If they fail to do so (e.g. in case of a timeout error, and in case - /// that's not allowed by ), then they'll keep using the last-good cached response, up to - /// , but they will keep retrying to fetch fresh values in the mean time. The higher this value, - /// the lower the load on your service, and the less up-to-date responses clients will cache. Consider what issues could be caused - /// by clients using stale responses (they might make wrong decisions based on these responses, or write that stale data somewhere). - /// - public TimeSpan? RefreshTime { get; set; } - - public double RefreshTimeInMinutes - { - get => RefreshTime?.TotalMinutes ?? -1; - set => RefreshTime = value == -1 ? null : (TimeSpan?)TimeSpan.FromMinutes(value); - } - - - /// - /// Default: 360 minutes (6 hours). How long should clients cache responses for. When that time passed, responses are evicted from - /// the cache, unless they were refreshed earlier (see ), or unless - /// specifies the expiration time is auto-extended when a cached response is used. Responses might be evicted earlier if they were - /// explicitly revoked or due to RAM pressure on client machines. Note that in case your service is unavailable, incoming requests - /// will fail and your service clients won't be able to fall back to cached responses after that time, possibly causing them to fail - /// as well. When picking a value, think how long it might take you to restore your service in case of a production disaster (e.g. 6 - /// hours). But also consider what issues could be caused by clients using very old stale responses (they might make wrong decisions - /// based on these responses, or write that stale data somewhere). - /// - public TimeSpan? ExpirationTime { get; set; } - - public double ExpirationTimeInMinutes - { - get => ExpirationTime?.TotalMinutes ?? -1; - set => ExpirationTime = value == -1 ? null : (TimeSpan?)TimeSpan.FromMinutes(value); - } - - - /// - /// Default: 1 second. When a client calls this method and receives a failure response (e.g. in case of a timeout error, and in case - /// it should be ignored as per ), it will not cache the response, and will keep using the last- - /// good response in the mean time, if any. However, it will wait a shorter delay than till it - /// attempts to refresh the data, since the response is now considered old and shouldn't be used for much longer. This delay is used - /// so clients don't "attack" your service when it's already potentially having availability issues. To disable, set to 0. - /// - public TimeSpan? FailedRefreshDelay { get; set; } - - public double FailedRefreshDelayInSeconds - { - get => FailedRefreshDelay?.TotalSeconds ?? -1; - set => FailedRefreshDelay = value == -1 ? null : (TimeSpan?)TimeSpan.FromSeconds(value); - } - - - /// - /// Default: Enabled. When a client calls this method multiple times concurrently with the same parameters, the caching layer will - /// "group" the requests and issue a single request to this method, to reduce the load on this service. It is assumed that this - /// method returns the exact same answer given the exact same parameters. This flag controls whether to use request grouping or not. - /// - public RequestGroupingBehavior RequestGroupingBehavior { get; set; } - - - /// - /// Determines what clients do when accessing a cached response that is considered old, i.e. its refresh time passed. - /// - public RefreshBehavior RefreshBehavior { get; set; } - - - /// - /// Dictates what clients do when a cached response is explicitly revoked by the server. - /// - public RevokedResponseBehavior RevokedResponseBehavior { get; set; } - - - /// - /// Defines how cached response expiration time is auto-extended. - /// - public ExpirationBehavior ExpirationBehavior { get; set; } - - - /// - /// Default: Enabled. When clients bypass their cache for specific requests using TracingContext.SuppressCaching(), this flag controls - /// whether the response will be cached. I.e. clients ignore the cache while READING, but not necessarily when WRITING. - /// - public CacheResponsesWhenSupressedBehavior CacheResponsesWhenSupressedBehavior { get; set; } - - /// - /// Default: Disabled. Defines whether to remove the previously cached response in case a response that we dont want to cache nor to ignore is received - /// - public NotIgnoredResponseBehavior NotIgnoredResponseBehavior { get; set; } - - // Not in use - bool? IMethodCachingSettings.Enabled { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } - } - - public interface IMethodCachingSettings - { - bool? Enabled { get; set; } - ResponseKinds ResponseKindsToCache { get; set; } - ResponseKinds ResponseKindsToIgnore { get; set; } - RefreshMode RefreshMode { get; set; } - TimeSpan? RefreshTime { get; set; } - TimeSpan? ExpirationTime { get; set; } - TimeSpan? FailedRefreshDelay { get; set; } - RequestGroupingBehavior RequestGroupingBehavior { get; set; } - RefreshBehavior RefreshBehavior { get; set; } - RevokedResponseBehavior RevokedResponseBehavior { get; set; } - ExpirationBehavior ExpirationBehavior { get; set; } - CacheResponsesWhenSupressedBehavior CacheResponsesWhenSupressedBehavior { get; set; } - NotIgnoredResponseBehavior NotIgnoredResponseBehavior { get; set; } - } - - - /// The various kinds of responses that can be obtained from a service (non-null, null, exceptions). - [Flags] - public enum ResponseKinds - { - /// Normal, non-null response. This does not include non-null Revocable<> with a null inner Value. - NonNullResponse = 1 << 0, - - /// Null response. This includes non-null Revocable<> with a null inner Value. - NullResponse = 1 << 1, - - /// (e.g. 404 not found). - RequestException = 1 << 2, - - /// (e.g. 500 internal server error). - EnvironmentException = 1 << 3, - - /// or . - TimeoutException = 1 << 4, - - /// Exceptions other than Request, Environment, Timeout and TaskCanceled. - OtherExceptions = 1 << 5, - } - - - /// Controls if and how refreshes should be used. - public enum RefreshMode - { - /// Use this option in case this method does not return Revocable<> responses or you don't use an - /// ICacheRevoker to revoke cached responses. Clients will periodically fetch up-to-date responses. - UseRefreshes = 1, - - /// Use this option in case this method returns Revocable<> responses and you use an ICacheRevoker to revoke cached - /// responses. Refreshes will NOT be used (since you're revoking responses manually) except in case a client detects that it is - /// unable to obtain cache revoke messages, in which case it will fall back to using soft expiration until it reconnects to the - /// revoke messages stream. Note that during that time your service will experience higher incoming traffic. - UseRefreshesWhenDisconnectedFromCacheRevokesBus = 2, - - /// DANGEROUS. Use this option to prevent clients from refreshing responses, up to the time they expire (see - /// ). - DoNotUseRefreshes = 3, - } - - - /// - /// Whether or not to group outgoing requests to the same method with the same parameters. - /// - public enum RequestGroupingBehavior - { - Enabled = 1, - Disabled = 2, - } - - - /// - /// Determines what clients do when accessing a cached response that is considered old, i.e. its refresh time passed. - /// - public enum RefreshBehavior - { - /// - /// When a client encounters a cached response that is older than , it will attempt to call - /// this method and fetch a fresh value. If it fails to do so (i.e. the response does not match ), - /// it will keep using the old value. This lets the client to continue providing service while this service is down. It is assumed - /// that it is preferable to use stale responses over not providing service. The client will retry fetching a new value the next - /// time it needs that response with a minimum delay of between retries, unless it had no - /// previously-cache response, in which case it might issue a request as soon as it received a reply for the previous one. This is - /// the default for Microdot v4+ clients. - /// - TryFetchNewValueOrUseOld = 1, - - - /// - /// DANGEROUS! When a client encounters a cached response that is older than , it will - /// use it even though it's old (possibly several hours old), and will issue a request to obtain a fresh value so the NEXT time it - /// needs it, it'll be (more) up-to-date (though if it needs it much later, it'll be old anyway). This behavior prioritizes low - /// latency over fresh data. This is the default for Microdot v1, v2 and v3 clients. - /// - UseOldAndFetchNewValueInBackground = 2, - } - - - /// - /// Dictates what clients do when a cached response is explicitly revoked by the server. - /// - public enum RevokedResponseBehavior - { - /// - /// When a client receives a revoke message, it looks for all cached responses tagged with that message key and marks them - /// as "stale". The NEXT time the client happens to need such a cached response (if it didn't expire by then), it will ignore - /// the cached response and call this method to obtain fresh data. If the new response does not match - /// , it will use the stale cached response. This lets the client to continue providing - /// service while this service is down. It is assumed that it is preferable to use stale responses over not providing service. - /// This is the default for Microdot v3+ clients. - /// - TryFetchNewValueNextTimeOrUseOld = 1, - - /// - /// DANGEROUS! When a client receives a revoke message, it looks for all cached responses tagged with that message key and marks them - /// as "stale". With this option, the NEXT time the client happens to need such a cached response (if it didn't expire by then), it - /// will immediately return the stale response and initiate a background call to the target service to obtain an up-to-date response, - /// for the next-next time it needs it. Use this option if your clients need the lowest latency possible, even at the cost of using - /// stale data (that can be several hours out-of-date). This is the default for Microdot v1,v2 and v3 clients. - /// - TryFetchNewValueInBackgroundNextTime = 2, - - /// - /// DANGEROUS! With this option, when a client receives a cache revoke message, it will look for all cached responses from that - /// method tagged with that message key and immediately issue a request to this method to obtain an up-to-date value for each of - /// them. Use this option if your clients need the lowest latency possible, even at the cost of issuing redundant calls to your - /// method for data they haven't been using for a while. Use this in case your clients cache and actively use a large portion of - /// all possible responses from that method. - /// - //TryFetchNewValueImmediately = 3, - - /// - /// DANGEROUS! With this option, when a client receives a cache revoke message, it will immediately stop using all cached responses - /// tagged with that message key. In case your service becomes unavailable the client will not have last-good cached responses - /// to fall back to, which may cause it to fail, in turn. Use this option in case your clients must absolutely not use stale - /// responses, even at the cost of not providing service. - /// - FetchNewValueNextTime = 4, - - /// - /// DANGEROUS! With this option, when a client receives a cache revoke message, it will ignore the message and keep using stale - /// responses. You can achieve a similar effect by not returning Revocable<> responses, or responses with an empty list of - /// revoke keys. If that's inconvenient, you can use this option as a work-around. - /// - KeepUsingRevokedResponse = 5, - } - - - /// - /// Defines how cached response expiration time is auto-extended. - /// - public enum ExpirationBehavior - { - /// - /// This option defines that every time a response is read from the cache, its expiration is pushed forward. This is suitable when - /// you use manual cache revokes and responses aren't auto-refreshed (since you set to - /// ), hence their expiration isn't updated, and you don't want them to expire while - /// they're still in use. - /// - ExtendExpirationWhenReadFromCache = 1, - - /// - /// This option defines that cached responses will be expired on time, regardless if they were used or not. This is suitable when - /// you set to ; refresh operations, that occur when clients make - /// use of cached responses, automatically extend the expiration time. - /// - DoNotExtendExpirationWhenReadFromCache = 2, - } - - - /// - /// When clients bypass their cache for specific requests using TracingContext.SuppressCaching(), this option controls - /// whether the response will be cached. I.e. clients ignore the cache while READING, but not necessarily when WRITING. - /// - public enum CacheResponsesWhenSupressedBehavior - { - Enabled = 1, - Disabled = 2, - } - - /// - /// Defines whether to remove the previously cached response in case a response that we dont want to cache nor to ignore is received - /// - public enum NotIgnoredResponseBehavior - { - RemoveCachedResponse = 1, - KeepCachedResponse = 2, - } -} diff --git a/Gigya.ServiceContract/Attributes/EventAttrubute.cs b/Gigya.ServiceContract/Attributes/EventAttrubute.cs deleted file mode 100644 index b2cd58dc..00000000 --- a/Gigya.ServiceContract/Attributes/EventAttrubute.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; - -namespace Gigya.ServiceContract.Attributes -{ - /// Mark the parameter as containing sensitive data. - /// When sensitive data is automaticity logged (e.g. event publisher) it will be encrypted. - /// - [AttributeUsage(AttributeTargets.Parameter| AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field)] - - public class SensitiveAttribute : Attribute - { - /// Mark the parameter as containing Secretive data. - ///it will never log automaticity (e.g. event publisher). - /// - public bool Secretive { get; set; } - } - - /// Mark the parameter as containing nonsensitive data. - /// When nonsensitive data is automaticity logged (e.g. event publisher) it wont be encrypted. - /// - [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field)] - public class NonSensitiveAttribute : Attribute{} - - -} diff --git a/Gigya.ServiceContract/Attributes/HttpServiceAttribute.cs b/Gigya.ServiceContract/Attributes/HttpServiceAttribute.cs deleted file mode 100644 index e2a7d842..00000000 --- a/Gigya.ServiceContract/Attributes/HttpServiceAttribute.cs +++ /dev/null @@ -1,46 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; - -namespace Gigya.Common.Contracts.HttpService -{ - [AttributeUsage(AttributeTargets.Interface)] - public class HttpServiceAttribute : Attribute - { - /// - /// This is the port number that the service will listen to for incoming HTTP requests. Other ports (used for - /// Orleans, Metrics.Net, etc) are opened at sequential numbers from this base offset. - /// - public int BasePort { get; set; } - - public bool UseHttps { get; set; } - - public HttpServiceAttribute(int basePort) - { - BasePort = basePort; - } - - [Obsolete("This propery is no longer in use, and will be removed on Microdot version 2.0. Service name is now extracted from its interface's namespace.")] - public string Name { get; set; } - } -} diff --git a/Gigya.ServiceContract/Attributes/LogFieldsAttribute.cs b/Gigya.ServiceContract/Attributes/LogFieldsAttribute.cs deleted file mode 100644 index bdf8f0b0..00000000 --- a/Gigya.ServiceContract/Attributes/LogFieldsAttribute.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System; - -namespace Gigya.ServiceContract.Attributes -{ - /// Mark the parameter as containing log field data - /// by providing this attribute the class will be dissects into properties. - /// - [AttributeUsage(AttributeTargets.Parameter)] - public class LogFieldsAttribute : Attribute { } -} \ No newline at end of file diff --git a/Gigya.ServiceContract/Attributes/PublicEndpointAttribute.cs b/Gigya.ServiceContract/Attributes/PublicEndpointAttribute.cs deleted file mode 100644 index 55de1724..00000000 --- a/Gigya.ServiceContract/Attributes/PublicEndpointAttribute.cs +++ /dev/null @@ -1,108 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; - -namespace Gigya.Common.Contracts.HttpService -{ - - /// - /// Specifies that this method is exposed to the external world, and can be called via Gator. - /// - [AttributeUsage(AttributeTargets.Method)] - public class PublicEndpointAttribute : Attribute - { - /// - /// Full endpoint name (e.g. "accounts.getPolicies"). If is specified, should specify the a logical name in the same format, which will be used for logging and rate limit. - /// - public string EndpointName { get; set; } - - /// - /// True if only HTTPS requests are allowed to call this endpoint, false if both HTTP and HTTPS requests are allowed. - /// - public bool RequireHTTPS { get; set; } = true; - - /// - /// Defines how to map the response from this method to the response returned by Gator. If not specified, this - /// method's response will be returned as-is to the outside world, along with Gigya's standard response fields - /// (statusCode, errorCode, statusReason, callId, etc.), unless your response already includes them, or some of - /// them. If you do specify a name, all of your response will be put under that json property name, and the - /// standard response fields will be next to it. - /// - public string PropertyNameForResponseBody { get; set; } = null; - - /// - /// Specifies the routing regex that determines which matching URLs will be routed to this method. - /// Regex is matched against the path only, not the domain or query string. - /// When specifying a value for this property, calls won't be routed to this method according to the command name. - /// In this case, the command name is only used for logging and rate limit. - /// - public string UrlPathRegex { get; set; } = null; - - /// - /// True if calls to this method should bypass authentication checks, otherwise false. - /// - public bool SkipPermissionChecks { get; set; } = false; - - /// - /// True if calls to this method should bypass datacenter checks, otherwise false. - /// - public bool SkipDatacenterChecks { get; set; } = false; - - /// - /// True if this method accepts a single parameter where the request parameters should be mapped to each of its properties, - /// false if request parameters should be directly mapped to the method's parameters. - /// - public bool UsingRequestObject { get; set; } = false; - - /// Full endpoint name (e.g. "accounts.getPolicies"). If is specified, should specify the a logical name in the same format, which will be used for logging and rate limit. - /// - /// Whether Gator should reject requests from the outside world that were passed over http and not https, and - /// not forward them to the service. - /// - /// - /// Defines how to map the response from this method to the response returned by Gator. If not specified, this - /// method's response will be returned as-is to the outside world, along with Gigya's standard response fields - /// (statusCode, errorCode, statusReason, callId, etc.), unless your response already includes them, or some of - /// them. If you do specify a name, all of your response will be put under that json property name, and the - /// standard response fields will be next to it. - /// - [Obsolete("Please use the other constructor overload that accepts only an 'endpoint' parameter, and specify all other paramters with the attributes optional named parameter syntax (MyProp = 5)")] - public PublicEndpointAttribute(string endpointName, bool requireHTTPS = true, string propertyNameForResponseBody = null) - { - EndpointName = endpointName; - RequireHTTPS = requireHTTPS; - PropertyNameForResponseBody = propertyNameForResponseBody; - } - - /// Full endpoint name (e.g. "accounts.getPolicies"). If is specified, should specify the a logical name in the same format, which will be used for logging and rate limit. - public PublicEndpointAttribute(string endpointName) - { - EndpointName = endpointName; - } - - internal PublicEndpointAttribute() - { - - } - } -} diff --git a/Gigya.ServiceContract/Exceptions/Breadcrumb.cs b/Gigya.ServiceContract/Exceptions/Breadcrumb.cs deleted file mode 100644 index feca6823..00000000 --- a/Gigya.ServiceContract/Exceptions/Breadcrumb.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; - -namespace Gigya.ServiceContract.Exceptions -{ - [Serializable] - public class Breadcrumb - { - public string ServiceName { get; set; } - public string ServiceVersion { get; set; } - public string HostName { get; set; } - public string DataCenter { get; set; } - public string DeploymentEnvironment { get; set; } - - public override string ToString() - { - return $"{ServiceName} v{ServiceVersion} on {HostName} in {DataCenter}-{DeploymentEnvironment}"; - } - } -} diff --git a/Gigya.ServiceContract/Exceptions/EnvironmentException.cs b/Gigya.ServiceContract/Exceptions/EnvironmentException.cs deleted file mode 100644 index 33c1e148..00000000 --- a/Gigya.ServiceContract/Exceptions/EnvironmentException.cs +++ /dev/null @@ -1,55 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Runtime.Serialization; - -namespace Gigya.Common.Contracts.Exceptions -{ - /// - /// This exception denotes a problem with the environment, such as a database that's down, an external service - /// we rely on that's inaccessible, a missing or invalid configuration file, or even going out of memory. Exceptions of - /// this type are sometimes recoverable, e.g. by retrying the DB operation. They're the same kind of errors that cause - /// web servers to return HTTP 5xx errors. Exceptions of this type are routed by default to IT/Operations -- it's up to - /// them to fix the problem in production environment. s, on the other hand, are - /// routed to developers. - /// - [Serializable] - public class EnvironmentException : SerializableException - { - /// - /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - /// - /// The error message that explains the reason for the exception. - /// Optional. The exception that is the cause of the current exception. - /// Optional. A collection of type that contains additional data about the exception, which must be encrypted when stored. - /// Optional. A collection of type that contains additional data about the exception, which needn't be encrypted when stored. - public EnvironmentException(string message, Exception innerException = null, Tags encrypted = null, Tags unencrypted = null) : base(message, innerException, encrypted, unencrypted) { } - - /// Initializes a new instance of the class with serialized data. - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). - protected EnvironmentException(SerializationInfo info, StreamingContext context) : base(info, context) { } - } -} diff --git a/Gigya.ServiceContract/Exceptions/InvalidParameterValueException.cs b/Gigya.ServiceContract/Exceptions/InvalidParameterValueException.cs deleted file mode 100644 index 727f3848..00000000 --- a/Gigya.ServiceContract/Exceptions/InvalidParameterValueException.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Runtime.Serialization; -using Gigya.Common.Contracts.Exceptions; -using Newtonsoft.Json; - -namespace Gigya.ServiceContract.Exceptions -{ - /// - /// This excpetion is thrown if a parameter contains an invalid value - /// - [Serializable] - public class InvalidParameterValueException: RequestException - { - ///ErrorCode of Invalid_parameter_value - public override int? ErrorCode => 400006; - - /// - /// Name of the parameter which has an invalid value - /// - [JsonProperty] - public string parameterName { get; set; } - - /// - /// For parameters that contain data structures, the path inside the data structure pointing to the field/property that - /// caused the deserialization or validation error. - /// - public string[] ErrorPath { get; set; } - - /// - /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - /// - /// Name of the parameter which has an invalid value - /// For parameters that contain data structures, the path inside the data structure pointing to the field/property that - /// caused the deserialization or validation error. - /// The error message that explains the reason for the exception. - /// Optional. A collection of type that contains additional data about the exception, which must be encrypted when stored. - /// Optional. A collection of type that contains additional data about the exception, which needn't be encrypted when stored. - /// Optional. The exception that is the cause of the current exception. - public InvalidParameterValueException(string paramName, string[] errorPath, string message, Exception innerException = null, Tags encrypted = null, Tags unencrypted = null) : base(message, innerException, encrypted, unencrypted) - { - parameterName = paramName; - ErrorPath = errorPath; - } - - /// Initializes a new instance of the class with serialized data. - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). - public InvalidParameterValueException(SerializationInfo info, StreamingContext context) : base(info, context) - { - } - } -} diff --git a/Gigya.ServiceContract/Exceptions/ProgrammaticException.cs b/Gigya.ServiceContract/Exceptions/ProgrammaticException.cs deleted file mode 100644 index 4cee7d0c..00000000 --- a/Gigya.ServiceContract/Exceptions/ProgrammaticException.cs +++ /dev/null @@ -1,100 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Runtime.Serialization; - -namespace Gigya.Common.Contracts.Exceptions -{ - /// - /// This exception denotes a programmatic error, i.e. a bug we detected in our code at run time. For example, - /// you can throw this when your method was called with a null pointer, or if someone attempts to use a static class - /// you wrote before initializing it. Throw this when you detect you're in an invalid state (e.g. using assertions). - /// Exceptions of this type are logged and (hopefully) routed to developers. s, on - /// the other hand, are routed to IT/Operations. - /// - [Serializable] - public class ProgrammaticException : SerializableException - { - /// - /// Initializes a new instance of the class with a specified error message - /// and a reference to the inner exception that is the cause of this exception. - /// - /// The error message that explains the reason for the exception. - /// Optional. The exception that is the cause of the current exception. - /// Optional. A collection of type that contains additional data - /// about the exception, which must be encrypted when stored. - /// Optional. A collection of type that contains additional data - /// about the exception, which needn't be encrypted when stored. - public ProgrammaticException(string message, Exception innerException = null, Tags encrypted = null, Tags unencrypted = null) - : base(message, innerException, encrypted, unencrypted) { } - - /// - /// Initializes a new instance of the class with serialized data. - /// - /// The that holds the serialized object data about the - /// exception being thrown. - /// The that contains contextual information about the - /// source or destination. - /// The parameter is null. - /// The class name is null or is zero - /// (0). - protected ProgrammaticException(SerializationInfo info, StreamingContext context) - : base(info, context) { } - } - - /// - /// This exception is thrown by services when they encounter any unhandled exception that doesn't derive from - /// (e.g. ). It contains the original - /// exception in its property. On the client-side, they are instead exposed - /// as an RemoteServiceException, having an inner exception copied over. You should never throw this exception from - /// your code. - /// - [Serializable, Obsolete("No longer used, preserved for backwards compatibility with older servers.")] - public class UnhandledException : ProgrammaticException - { - /// - /// Initializes a new instance of the class with the specified inner exception - /// that is the cause of this exception. - /// - /// The exception that is the cause of the current exception. - /// Optional. A collection of type that contains additional data - /// about the exception, which must be encrypted when stored. - /// Optional. A collection of type that contains additional data - /// about the exception, which needn't be encrypted when stored. - public UnhandledException(Exception innerException, Tags encrypted = null, Tags unencrypted = null) - : base("An unhandled exception occurred when processing this request. See InnerException for details.", innerException, encrypted, unencrypted) { } - - /// - /// Initializes a new instance of the class with serialized data. - /// - /// The that holds the serialized object data about the - /// exception being thrown. - /// The that contains contextual information about the - /// source or destination. - /// The parameter is null. - /// The class name is null or is zero - /// (0). - protected UnhandledException(SerializationInfo info, StreamingContext context) - : base(info, context) { } - } -} diff --git a/Gigya.ServiceContract/Exceptions/RemoteServiceException.cs b/Gigya.ServiceContract/Exceptions/RemoteServiceException.cs deleted file mode 100644 index 5b32b108..00000000 --- a/Gigya.ServiceContract/Exceptions/RemoteServiceException.cs +++ /dev/null @@ -1,57 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Runtime.Serialization; -using Gigya.Common.Contracts.Exceptions; - -namespace Gigya.Common.Application.HttpService.Client -{ - [Serializable] - public class RemoteServiceException : EnvironmentException - { - public string RequestedUri { get; private set; } - - /// - /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - /// - /// The error message that explains the reason for the exception. - /// The URI requested when the remote service call failed. - /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. - /// Optional. A collection of type that contains additional data about the exception, which must be encrypted when stored. - /// Optional. A collection of type that contains additional data about the exception, which needn't be encrypted when stored. - /// Optional. Additional details about the exception. - public RemoteServiceException(string message, string requestedUri, Exception innerException = null, Tags encrypted = null, Tags unencrypted = null, string details = null) - : base(message, innerException, encrypted, unencrypted) - { - RequestedUri = requestedUri; - } - - /// Initializes a new instance of the class with serialized data. - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). - // ReSharper disable once UnusedMember.Global - protected RemoteServiceException(SerializationInfo info, StreamingContext context) : base(info, context) { } - } -} \ No newline at end of file diff --git a/Gigya.ServiceContract/Exceptions/RequestException.cs b/Gigya.ServiceContract/Exceptions/RequestException.cs deleted file mode 100644 index a35074e5..00000000 --- a/Gigya.ServiceContract/Exceptions/RequestException.cs +++ /dev/null @@ -1,101 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Runtime.Serialization; - -namespace Gigya.Common.Contracts.Exceptions -{ - /// - /// This exception denotes a problem in an incoming request. For example, a missing required parameter, bad - /// format, no permissions, trying to act on an entity that was deleted (e.g. site, user), etc. It should NOT be thrown - /// when the request is valid but we fail to process it due to some internal error; - /// or should be thrown instead. Exceptions of this type are the same kind of errors - /// that cause web servers to return HTTP 4xx errors. Note that clients to external systems should catch exceptions of - /// this type and re-throw them as . - /// - [Serializable] - public class RequestException : SerializableException - { - /// - /// Represents custom error code for easily distinguish between different types of request exceptions. - /// - public virtual int? ErrorCode { get; private set; } - - - /// - /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - /// - /// The error message that explains the reason for the exception. - /// Optional. A collection of type that contains additional data about the exception, which must be encrypted when stored. - /// Optional. A collection of type that contains additional data about the exception, which needn't be encrypted when stored. - /// Optional. The exception that is the cause of the current exception. - public RequestException(string message, Exception innerException = null, Tags encrypted = null, Tags unencrypted = null): this(message, null, innerException, encrypted, unencrypted) - { - } - - /// The error message that explains the reason for the exception. - /// Represents custom error code for easily distinguish between different types of request exceptions. - /// Optional. The exception that is the cause of the current exception. - /// Optional. A collection of type that contains additional data about the exception, which must be encrypted when stored. - /// Optional. A collection of type that contains additional data about the exception, which needn't be encrypted when stored. - /// - /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - /// - public RequestException(string message, int? errorCode, Exception innerException = null, Tags encrypted = null, Tags unencrypted = null) - : base(message, innerException, encrypted, unencrypted) - { - ErrorCode = errorCode; - } - - /// Initializes a new instance of the class with serialized data. - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). - protected RequestException(SerializationInfo info, StreamingContext context) : base(info, context) { } - } - - - - [Serializable] - public class SecureRequestException : RequestException - { - - /// - /// Initializes a new instance of the class with a specified error message and a reference to the inner exception that is the cause of this exception. - /// - /// The error message that explains the reason for the exception. - /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. - /// Optional. A collection of type that contains additional data about the exception, which must be encrypted when stored. - /// Optional. A collection of type that contains additional data about the exception, which needn't be encrypted when stored. - public SecureRequestException(string message, Exception innerException = null, Tags encrypted = null, Tags unencrypted = null) : base(message, innerException, encrypted: encrypted, unencrypted: unencrypted) { } - - /// Initializes a new instance of the class with serialized data. - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - /// The parameter is null. - /// The class name is null or is zero (0). - protected SecureRequestException(SerializationInfo info, StreamingContext context) : base(info, context) { } - - } -} diff --git a/Gigya.ServiceContract/Exceptions/SerializableException.cs b/Gigya.ServiceContract/Exceptions/SerializableException.cs deleted file mode 100644 index 8046de60..00000000 --- a/Gigya.ServiceContract/Exceptions/SerializableException.cs +++ /dev/null @@ -1,329 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Linq; -using System.Reflection; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters.Binary; -using System.Text; -using Gigya.ServiceContract.Exceptions; - -namespace Gigya.Common.Contracts.Exceptions -{ - /// - /// Abstract base class for all exceptions which support advanced serialization features, such as automatic property - /// serialization and tags. When writing custom exceptions, please read the remarks section. - /// - /// - /// - /// When writing custom exceptions, make sure you do the following: - /// - /// - /// Mark the exception with the SerializableAttribute. - /// - /// - /// Do not inherit from SerializableException, but instead inherit from one of the three concrete - /// implementations: - /// , , . - /// - /// - /// Make sure to call the appropriate base constructor from your constructors. - /// - /// - /// Include a protected constructor with parameters (, - /// ) which calls the base constructor with same parameters. - /// - /// - /// - /// Exception that correctly inherit as described above, have all their public properties that have a setter - /// (including a non-public setter) serialized and deserialized automatically, in addition to tags (fields are not - /// serialized). The values of those properties must be marked with a SerializableAttribute since the - /// serialization is sometimes performed by (within Orleans). Also, the values of - /// these properties should be immutable. - /// - /// If a getter of a property returns null or throws an exception during serialization, it will not be serialized. - /// However, if a setter of a property throws an exception during deserialization, it will throw a - /// . - /// - /// There is no need to override the GetObjectData method in your custom exception to have your properties - /// automatically serialized. - /// - /// When an attempt is made to deserialize an exception, but the exact type of the exception is not available in - /// that context (e.g. a derived exception type that only exists on the serializing side, not the deserializing - /// side), then an attempt is made to deserialize that exception as it's base-type (the inheritance hierarchy is - /// serialized together with the exception), and if that fails, with the base-base-type, etc. When deserializing an - /// exception into a base type, there could be some properties that existed on the original derived type but do not - /// exist on the base type. Those properties were serialized, but there is no corresponding property to deserialize - /// them into. These values will be available in the the property. This can also - /// occur when an exception class changes (e.g. a property is renamed or removed), but only the serializing side is - /// using the new version, therefore there will be properties that will not match and will be accessible on the - /// deserializing side via the property. - /// - /// Those differences can also mean that data could be missing for a certain property (if that property was removed - /// from the class definition on the serializing side). In such a case, the property will be left uninitialized - /// (with its default value), unless it is marked with a , in which case the - /// deserialization will fail with a specifying which required property values - /// are missing. - /// - /// - /// - /// The following is an example of a correctly implemented exception: - /// - /// - [Serializable] - public abstract class SerializableException : Exception - { - private const string EXTENDED_PROPERTIES_NAMES_KEY = "ExtendedPropertiesNames"; - private const string EXTENDED_PROPERTIES_VALUES_KEY = "ExtendedPropertiesValues"; - private const string BREADCRUMBS_KEY = "Breadcrumbs"; - - private readonly Dictionary _extendedProperties; - private Breadcrumb[] _breadcrumbs; - - /// - /// A read-only dictionary of tags that must be encrypted when stored. They are, however, serialized (and - /// therefore transmitted) without encryption. - /// - public IReadOnlyDictionary EncryptedTags { get; private set; } - /// - /// A read-only dictionary of tags that needn't be encrypted when stored. - /// - public IReadOnlyDictionary UnencryptedTags { get; private set; } - - /// - /// A read-only dictionary of property values that failed to deserialize into a matching property (either - /// because there was no property with a matching name, or the setter of the property threw an exception). Each - /// key is the name of the serialized property and the value is the - /// serialized property's value. - /// - public IReadOnlyDictionary ExtendedProperties => new ReadOnlyDictionary(_extendedProperties); - - public IReadOnlyList Breadcrumbs => new ReadOnlyCollection(_breadcrumbs); - - /// - /// Initializes a new instance of the class with a specified error message - /// and a reference to the inner exception that is the cause of this exception. - /// - /// The error message that explains the reason for the exception. - /// Optional. The exception that is the cause of the current exception. - /// Optional. A collection of type that contains additional data - /// about the exception, which must be encrypted when stored. - /// Optional. A collection of type that contains additional data - /// about the exception, which needn't be encrypted when stored. - protected SerializableException(string message, Exception innerException = null, Tags encrypted = null, Tags unencrypted = null) : base(message, innerException) - { - if (encrypted != null && encrypted.Any()) - EncryptedTags = new ReadOnlyDictionary(new Dictionary(encrypted)); - - if (unencrypted != null && unencrypted.Any()) - UnencryptedTags = new ReadOnlyDictionary(new Dictionary(unencrypted)); - - _extendedProperties = new Dictionary(); - _breadcrumbs = new Breadcrumb[0]; - } - - /// Initializes a new instance of the class with serialized - /// data. - /// The that holds the serialized object data about the - /// exception being thrown. - /// The that contains contextual information about the - /// source or destination. - /// The parameter is null. - /// The class name is null, is zero (0) - /// or deserialization of extended properties encountered an error. - protected SerializableException(SerializationInfo info, StreamingContext context) : base(info, new StreamingContext(StreamingContextStates.CrossAppDomain, context.State)) - { - _extendedProperties = new Dictionary(); - - var extendedPropertiesNames = (string[])info.GetValue(EXTENDED_PROPERTIES_NAMES_KEY, typeof(string[])); - var extendedPropertiesValues = (object[])info.GetValue(EXTENDED_PROPERTIES_VALUES_KEY, typeof(object[])); - - if (extendedPropertiesNames == null && extendedPropertiesValues == null) - return; - - if (extendedPropertiesNames == null || extendedPropertiesValues == null || extendedPropertiesNames.Length != extendedPropertiesValues.Length) - throw new SerializationException("Failed to deserialize exception - bad extended properties data."); - - for (int i = 0; i < extendedPropertiesNames.Length; i++) - _extendedProperties.Add(extendedPropertiesNames[i], extendedPropertiesValues[i]); - - _extendedProperties.TryGetValue(nameof(EncryptedTags), out object tags); - EncryptedTags = tags as IReadOnlyDictionary; - _extendedProperties.Remove(nameof(EncryptedTags)); - - _extendedProperties.TryGetValue(nameof(UnencryptedTags), out tags); - UnencryptedTags = tags as IReadOnlyDictionary; - _extendedProperties.Remove(nameof(UnencryptedTags)); - - var properties = GetProperties().ToDictionary(p => p.Name); - - foreach (var extendedProperty in _extendedProperties.ToArray()) - { - - if (properties.TryGetValue(extendedProperty.Key, out PropertyInfo property)) - { - try - { - property.SetValue(this, JsonHelper.ConvertWeaklyTypedValue(extendedProperty.Value, property.PropertyType)); - _extendedProperties.Remove(extendedProperty.Key); - properties.Remove(extendedProperty.Key); - } - catch (Exception ex) - { - throw new SerializationException($"Failed to deserialize exception - failed to populate extended property '{property.Name}'. See InnerException for details.", ex); - } - } - } - - try - { - _breadcrumbs = (Breadcrumb[])info.GetValue(BREADCRUMBS_KEY, typeof(Breadcrumb[])); - } - catch (SerializationException) - { - _breadcrumbs = new Breadcrumb[0]; - } - } - - - /// - /// When overridden in a derived class, sets the - /// with information about the exception. - /// - /// The that holds the - /// serialized object data about the exception being thrown. - /// The that contains - /// contextual information about the source or destination. - /// The parameter is a null reference - /// (Nothing in Visual Basic). - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - info.AddValue("_Messages", string.Join(" --> ", GetAllExceptions(this).Reverse().Select(e => $"[{e.GetType().Name}] {e.Message}"))); - - base.GetObjectData(info, context); - - var properties = GetCustomAndExtendedProperties(); - properties.Add(nameof(EncryptedTags), EncryptedTags); - properties.Add(nameof(UnencryptedTags), UnencryptedTags); - - // Must split dictionary into keys and values because dictionary implements ISerializable itself and - // different serializers (BinaryFormatter, JSON.NET) behave differently for non-root ISerializable - // objects in the object graph. See http://stackoverflow.com/a/18379360/149265. - info.AddValue(EXTENDED_PROPERTIES_NAMES_KEY, properties.Keys.ToArray()); - info.AddValue(EXTENDED_PROPERTIES_VALUES_KEY, properties.Values.ToArray()); - - info.AddValue(BREADCRUMBS_KEY, _breadcrumbs); - } - - private static IEnumerable GetAllExceptions(Exception ex) - { - while (ex != null) - { - yield return ex; - ex = ex.InnerException; - } - } - - - /// - /// Returns a dictionary with all the custom properties and any values in . - /// - /// A where the key, of type , is the name of - /// the property and the value, of type , is the property value. - public Dictionary GetCustomAndExtendedProperties() - { - var properties = new Dictionary(_extendedProperties); - - foreach (var prop in GetProperties()) - { - object value = null; - - try - { - value = prop.GetValue(this); - } - catch { } - - if (value != null) - properties[prop.Name] = value; - } - - return properties; - } - - private IEnumerable GetProperties() - { - return GetType() - .GetProperties() - .Select(p => p.DeclaringType.GetProperty(p.Name)) - .Where(p => p.DeclaringType != typeof(Exception) && p.DeclaringType != typeof(SerializableException) && p.CanWrite); - } - - - public override string Message => - base.Message - + GetCustomAndExtendedProperties().Select(_ => new KeyValuePair(_.Key, _.Value.ToString())) - .Concat((EncryptedTags?.Keys ?? Enumerable.Empty()).Select(_ => new KeyValuePair(_, ""))) - .Concat(UnencryptedTags ?? Enumerable.Empty>()) - .Aggregate(new StringBuilder(), (sb, pair) => sb.Append($"{(sb.Length == 0 ? "; " : ", ")}{pair.Key}={pair.Value}")); - - public string RawMessage => base.Message; - - internal void AddBreadcrumb(Breadcrumb breadcrumb) - { - _breadcrumbs = _breadcrumbs.Concat(new[] { breadcrumb }).ToArray(); - } - } - - [Serializable] - public class Tags : Dictionary - { - public Tags() - { - - } - - protected Tags(SerializationInfo info, StreamingContext context):base(info,context) - { - - } - } -} diff --git a/Gigya.ServiceContract/Gigya.ServiceContract.csproj b/Gigya.ServiceContract/Gigya.ServiceContract.csproj deleted file mode 100644 index ef1a3fd7..00000000 --- a/Gigya.ServiceContract/Gigya.ServiceContract.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - netstandard2.0 - Gigya.ServiceContract - Gigya - Gigya.ServiceContract - © 2017 Gigya Inc. - 2.7.7 - 2.7.7 - 2.7.7 - - - \ No newline at end of file diff --git a/Gigya.ServiceContract/HttpService/IRevocable.cs b/Gigya.ServiceContract/HttpService/IRevocable.cs deleted file mode 100644 index 09211c01..00000000 --- a/Gigya.ServiceContract/HttpService/IRevocable.cs +++ /dev/null @@ -1,38 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System.Collections.Generic; - -namespace Gigya.ServiceContract.HttpService -{ - internal interface IRevocable - { - IEnumerable RevokeKeys { get; } - } - - public class Revocable : IRevocable - { - public T Value { get; set; } - - public IEnumerable RevokeKeys { get; set; } - } -} \ No newline at end of file diff --git a/Gigya.ServiceContract/HttpService/ServiceSchema.cs b/Gigya.ServiceContract/HttpService/ServiceSchema.cs deleted file mode 100644 index 353a3c42..00000000 --- a/Gigya.ServiceContract/HttpService/ServiceSchema.cs +++ /dev/null @@ -1,278 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.Serialization; -using System.Security.Cryptography; -using System.Threading.Tasks; -using Gigya.ServiceContract.HttpService; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Gigya.Common.Contracts.HttpService -{ - - /// - /// Contains a collection of Binterfaces, methods and method parameters, along with their attributes. Parameter types - /// and attributes are both weakly and strongly deserialized, so clients can convenienetly work with real objects if - /// they reference the needed assemblies, or work against strings/JObjects if they don't. - /// - public class ServiceSchema - { - public InterfaceSchema[] Interfaces { get; set; } - - public ServiceSchema() { } - - public ServiceSchema(Type[] interfaces) - { - Interfaces = interfaces.Select(_ => new InterfaceSchema(_)).ToArray(); - SetHashCode(); - } - - public string Hash { get; set; } - - private void SetHashCode() - { - var stream = new MemoryStream(); - using (var writer = new StreamWriter(stream) { AutoFlush = true }) - using (SHA1 sha = new SHA1CryptoServiceProvider()) - { - JsonSerializer.Create().Serialize(writer, this); - stream.Seek(0, SeekOrigin.Begin); - Hash = Convert.ToBase64String(sha.ComputeHash(stream)); - } - } - - } - - public class InterfaceSchema - { - public string Name { get; set; } - - public AttributeSchema[] Attributes { get; set; } - - public MethodSchema[] Methods { get; set; } - - public InterfaceSchema() { } - - public InterfaceSchema(Type iface) - { - if (!iface.IsInterface) - throw new ArgumentException("Not an interface"); - - Name = iface.FullName; - Methods = iface.GetMethods().Select(m => new MethodSchema(m)).ToArray(); - Attributes = iface - .GetCustomAttributes() - .Where(AttributeSchema.FilterAttributes) - .Select(a => new AttributeSchema(a)) - .ToArray(); - } - } - - public class MethodSchema - { - public string Name { get; set; } - - public ParameterSchema[] Parameters { get; set; } - - public bool IsRevocable { get; set; } - - [Obsolete("Use Response.TypeName instead")] - public string ResponseType { get; set; } - - public TypeSchema Response { get; set; } - - public AttributeSchema[] Attributes { get; set; } - - public MethodSchema() { } - - public MethodSchema(MethodInfo info) - { - Name = info.Name; - - - if (info.ReturnType == typeof(Task)) - { - Response = null; - - } - else if (info.ReturnType.IsGenericType && info.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)) - { - var resultType = info.ReturnType.GetGenericArguments().Single(); - if (resultType.IsGenericType && resultType.GetGenericTypeDefinition() == typeof(Revocable<>)) - { - IsRevocable = true; - resultType = resultType.GetGenericArguments().Single(); - } - Response = new TypeSchema(resultType, info.ReturnType.GetCustomAttributes()); - } - else - { - Response = new TypeSchema(info.ReturnType, info.ReturnType.GetCustomAttributes()); - } - - ResponseType = Response?.TypeName; - Parameters = info.GetParameters().Select(p => new ParameterSchema(p)).ToArray(); - Attributes = info - .GetCustomAttributes() - .Where(AttributeSchema.FilterAttributes) - .Select(a => new AttributeSchema(a)) - .ToArray(); - } - } - - public class SimpleTypeSchema - { - [JsonIgnore] - public Type Type { get; set; } - - public string TypeName { get; set; } - - public AttributeSchema[] Attributes { get; set; } - - public SimpleTypeSchema() { } - - public SimpleTypeSchema(Type type, IEnumerable attributes) - { - Type = type; - TypeName = type.AssemblyQualifiedName; - Attributes = attributes - .Where(AttributeSchema.FilterAttributes) - .Select(a => new AttributeSchema(a)) - .ToArray(); - } - - [OnDeserialized] - private void OnDeserialized(StreamingContext context) - { - try - { - Type = Type.GetType(TypeName); - } - catch { } - } - } - - public class TypeSchema : SimpleTypeSchema - { - public FieldSchema[] Fields { get; set; } - - public TypeSchema() { } - - public TypeSchema(Type type, IEnumerable attributes) : base(type, attributes) - { - if (IsCompositeType(type)) - Fields = GetFields(type).ToArray(); - - } - - private IEnumerable GetFields(Type type) - { - var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(_ => new FieldSchema(_)); - var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance).Select(_ => new FieldSchema(_)); - return properties.Concat(fields); - } - - private bool IsCompositeType(Type type) - { - - return !type.IsValueType && !(type == typeof(string)); - } - } - - public class ParameterSchema : TypeSchema - { - public string Name { get; set; } - - public ParameterSchema() { } - - public ParameterSchema(ParameterInfo param) : this(param.Name, param.ParameterType, param.GetCustomAttributes()) - { - } - - protected ParameterSchema(string name, Type type, IEnumerable attributes) : base(type, attributes) - { - Name = name; - } - } - - public class FieldSchema : SimpleTypeSchema - { - public string Name { get; set; } - - public FieldSchema() { } - - public FieldSchema(FieldInfo field) : base(field.FieldType, field.GetCustomAttributes()) - { - Name = field.Name; - } - - public FieldSchema(PropertyInfo property) : base(property.PropertyType, property.GetCustomAttributes()) - { - Name = property.Name; - } - } - - - public class AttributeSchema - { - [JsonIgnore] - public Attribute Attribute { get; set; } - - public string TypeName { get; set; } - - public JObject Data { get; set; } - - public AttributeSchema() { } - - public AttributeSchema(Attribute attribute) - { - Attribute = attribute; - TypeName = attribute.GetType().AssemblyQualifiedName; - Data = JObject.FromObject(attribute); - } - - [OnDeserialized] - private void OnDeserialized(StreamingContext context) - { - try - { - Type t = Type.GetType(TypeName); - - if (t != null) - Attribute = (Attribute)Data.ToObject(t); - } - catch { } - } - - internal static bool FilterAttributes(Attribute a) - { - return a.GetType().Namespace?.StartsWith("System.Diagnostics") == false && a.GetType().Namespace?.StartsWith("System.Security") == false; - } - } - -} diff --git a/Gigya.ServiceContract/JsonHelper.cs b/Gigya.ServiceContract/JsonHelper.cs deleted file mode 100644 index 56626491..00000000 --- a/Gigya.ServiceContract/JsonHelper.cs +++ /dev/null @@ -1,100 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Linq; -using System.Text.RegularExpressions; -using Gigya.ServiceContract.Exceptions; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Gigya.Common.Contracts -{ - /// - /// Utility class for converting between JSON and .NET values. - /// - public static class JsonHelper - { - private static JsonSerializer Serializer { get; } = new JsonSerializer { DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind }; - - private const string ParamCaptureName = "param"; - private static readonly Regex ParamRegex = new Regex(@"Path\s'(?<" + ParamCaptureName + ">.*)'.$", RegexOptions.Compiled | RegexOptions.CultureInvariant); - - - /// - /// Converts values that were deserialized from JSON with weak typing (e.g. into ) back into - /// their strong type, according to the specified target type. - /// - /// The value to convert. - /// The type the value should be converted into. - /// - public static object ConvertWeaklyTypedValue(object value, Type targetType) - { - if (targetType == null) - throw new ArgumentNullException(nameof(targetType)); - - if (value == null || targetType.IsInstanceOfType(value)) - return value; - - var paramType = Nullable.GetUnderlyingType(targetType) ?? targetType; - - if (paramType == typeof(DateTime) && value is DateTimeOffset) - { - var dto = (DateTimeOffset)value; - - if (dto.Offset == TimeSpan.Zero) - return dto.UtcDateTime; - else - return dto.LocalDateTime; - } - - try - { - if (value is string && Type.GetTypeCode(paramType) == TypeCode.Object && - paramType != typeof(DateTimeOffset) && paramType != typeof(TimeSpan) && paramType != typeof(Guid) && - paramType != typeof(byte[])) - return JsonConvert.DeserializeObject((string) value, paramType); - - return JToken.FromObject(value).ToObject(targetType, Serializer); - } - catch (JsonReaderException jsException) - { - var parameterPath = string.IsNullOrEmpty(jsException.Path) ? new string[0] : jsException.Path.Split('.'); - throw new InvalidParameterValueException(null, parameterPath, jsException.Message, innerException: jsException); - } - catch (JsonSerializationException serException) - { - string parameterPathStr = null; - var match = ParamRegex.Match(serException.Message); - if (match.Success) - parameterPathStr = match.Groups[ParamCaptureName]?.Value; - - throw new InvalidParameterValueException(null, parameterPathStr?.Split('.') ?? new string[0], serException.Message, innerException: serException); - } - catch (Exception ex) - { - throw new InvalidParameterValueException(null, null, ex.Message, innerException: ex); - } - - } - } -} diff --git a/Gigya.ServiceContract/Properties/AssemblyInfo.cs b/Gigya.ServiceContract/Properties/AssemblyInfo.cs deleted file mode 100644 index 4a12bbeb..00000000 --- a/Gigya.ServiceContract/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,40 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -[assembly: InternalsVisibleTo("Gigya.Microdot.ServiceProxy")] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("db6d3561-835e-40d5-b9d4-83951cf426df")] - - - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] -[assembly: CLSCompliant(false)] - -[assembly: InternalsVisibleTo("Gigya.Microdot.SharedLogic")] \ No newline at end of file diff --git a/Gigya.ServiceContract/ServiceContract.sln b/Gigya.ServiceContract/ServiceContract.sln deleted file mode 100644 index 47abaafb..00000000 --- a/Gigya.ServiceContract/ServiceContract.sln +++ /dev/null @@ -1,42 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27130.2027 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gigya.ServiceContract", "Gigya.ServiceContract.csproj", "{DB6D3561-835E-40D5-B9D4-83951CF426DF}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".paket", ".paket", "{E38B2044-FCF9-4FA7-A9AD-D3B4FDAA91CF}" - ProjectSection(SolutionItems) = preProject - paket.dependencies = paket.dependencies - paket.lock = paket.lock - EndProjectSection -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Gigya.Microdot.ServiceContract.UnitTests", "..\tests\Gigya.Microdot.ServiceContract.UnitTests\Gigya.Microdot.ServiceContract.UnitTests.csproj", "{C224F79A-EAB5-48B8-B587-65772B0966EF}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{6D04C065-F8ED-408D-BE23-722DA84AD2F5}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {DB6D3561-835E-40D5-B9D4-83951CF426DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DB6D3561-835E-40D5-B9D4-83951CF426DF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DB6D3561-835E-40D5-B9D4-83951CF426DF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DB6D3561-835E-40D5-B9D4-83951CF426DF}.Release|Any CPU.Build.0 = Release|Any CPU - {C224F79A-EAB5-48B8-B587-65772B0966EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C224F79A-EAB5-48B8-B587-65772B0966EF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C224F79A-EAB5-48B8-B587-65772B0966EF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C224F79A-EAB5-48B8-B587-65772B0966EF}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {C224F79A-EAB5-48B8-B587-65772B0966EF} = {6D04C065-F8ED-408D-BE23-722DA84AD2F5} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {7F592F51-0A62-4EA9-8FA8-4544B4888416} - EndGlobalSection -EndGlobal diff --git a/Gigya.ServiceContract/paket.dependencies b/Gigya.ServiceContract/paket.dependencies deleted file mode 100644 index 300f99f6..00000000 --- a/Gigya.ServiceContract/paket.dependencies +++ /dev/null @@ -1,8 +0,0 @@ -source https://api.nuget.org/v3/index.json - -framework: auto-detect -redirects: off -content: once -copy_content_to_output_dir: always - -nuget Newtonsoft.Json >= 12 \ No newline at end of file diff --git a/Gigya.ServiceContract/paket.lock b/Gigya.ServiceContract/paket.lock deleted file mode 100644 index 9e52026e..00000000 --- a/Gigya.ServiceContract/paket.lock +++ /dev/null @@ -1,7 +0,0 @@ -REDIRECTS: OFF -COPY-CONTENT-TO-OUTPUT-DIR: ALWAYS -CONTENT: ONCE -RESTRICTION: == netstandard2.0 -NUGET - remote: https://api.nuget.org/v3/index.json - Newtonsoft.Json (12.0.3) diff --git a/Gigya.ServiceContract/paket.references b/Gigya.ServiceContract/paket.references deleted file mode 100644 index 1063d003..00000000 --- a/Gigya.ServiceContract/paket.references +++ /dev/null @@ -1 +0,0 @@ -Newtonsoft.Json \ No newline at end of file diff --git a/Gigya.ServiceContract/paket.template b/Gigya.ServiceContract/paket.template deleted file mode 100644 index 47705514..00000000 --- a/Gigya.ServiceContract/paket.template +++ /dev/null @@ -1,12 +0,0 @@ -type - project -description - Referenced by microservice public-facing interfaces. Provides common - facilities that are needed to define a service's contract. Part of the - Microdot framework. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices contracts \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 00000000..87ebb866 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,14 @@ +@Library("pipeline-libs@microdot") _ +node('base-win'){ + dotnetLibGitHubPipeline( + [ + projectName: "microdot", + group: "gigya", + dotnetVersion: "5.0.403", + coveragePercentageThreshold: 1, + runTests: false, + coverageFilter: "-:*.Interface;-:*Tests*;-:type=*OrleansCodeGen*", + releaseNugetBranches: ['main', 'master'] + ] + ) +} diff --git a/Metrics/AdvancedMetricsContext.cs b/Metrics/AdvancedMetricsContext.cs index 73349d12..08576399 100644 --- a/Metrics/AdvancedMetricsContext.cs +++ b/Metrics/AdvancedMetricsContext.cs @@ -1,7 +1,7 @@ -using System; -using Metrics.Core; +using Metrics.Core; using Metrics.MetricData; using Metrics.Sampling; +using System; namespace Metrics { diff --git a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicIntArray.cs b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicIntArray.cs index 62eb83fd..b6288e87 100644 --- a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicIntArray.cs +++ b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicIntArray.cs @@ -29,7 +29,7 @@ namespace Metrics.ConcurrencyUtilities #if CONCURRENCY_UTILS_PUBLIC public #else -internal + internal #endif struct AtomicIntArray { diff --git a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicInteger.cs b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicInteger.cs index e8eefdf3..b207b83f 100644 --- a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicInteger.cs +++ b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicInteger.cs @@ -34,7 +34,7 @@ namespace Metrics.ConcurrencyUtilities #if CONCURRENCY_UTILS_PUBLIC public #else -internal + internal #endif struct AtomicInteger { diff --git a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicLong.cs b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicLong.cs index 15b8c10c..25340d17 100644 --- a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicLong.cs +++ b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicLong.cs @@ -34,7 +34,7 @@ namespace Metrics.ConcurrencyUtilities #if CONCURRENCY_UTILS_PUBLIC public #else -internal + internal #endif struct AtomicLong { diff --git a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicLongArray.cs b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicLongArray.cs index 213240af..7f72f669 100644 --- a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicLongArray.cs +++ b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/AtomicLongArray.cs @@ -34,7 +34,7 @@ namespace Metrics.ConcurrencyUtilities #if CONCURRENCY_UTILS_PUBLIC public #else -internal + internal #endif struct AtomicLongArray { diff --git a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/Striped64.cs b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/Striped64.cs index b2331998..212a2b9f 100644 --- a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/Striped64.cs +++ b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/Striped64.cs @@ -45,7 +45,7 @@ namespace Metrics.ConcurrencyUtilities #if CONCURRENCY_UTILS_PUBLIC public #else -internal + internal #endif abstract class Striped64 { diff --git a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/StripedLongAdder.cs b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/StripedLongAdder.cs index 337797af..d5d0fbe4 100644 --- a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/StripedLongAdder.cs +++ b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/StripedLongAdder.cs @@ -54,7 +54,7 @@ namespace Metrics.ConcurrencyUtilities #if CONCURRENCY_UTILS_PUBLIC public #else -internal + internal #endif sealed class StripedLongAdder : Striped64 { diff --git a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/ThreadLocalLongAdder.cs b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/ThreadLocalLongAdder.cs index 68b75e3a..6e20ed63 100644 --- a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/ThreadLocalLongAdder.cs +++ b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/ThreadLocalLongAdder.cs @@ -36,7 +36,7 @@ namespace Metrics.ConcurrencyUtilities #if CONCURRENCY_UTILS_PUBLIC public #else -internal + internal #endif sealed class ThreadLocalLongAdder { diff --git a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/ThreadLocalRandom.cs b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/ThreadLocalRandom.cs index 3a5821d5..81679220 100644 --- a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/ThreadLocalRandom.cs +++ b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/ThreadLocalRandom.cs @@ -31,7 +31,7 @@ namespace Metrics.ConcurrencyUtilities #if CONCURRENCY_UTILS_PUBLIC public #else -internal + internal #endif static class ThreadLocalRandom { diff --git a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/VolatileDouble.cs b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/VolatileDouble.cs index 209db7c4..4aade3a6 100644 --- a/Metrics/App_Packages/ConcurrencyUtils.0.1.4/VolatileDouble.cs +++ b/Metrics/App_Packages/ConcurrencyUtils.0.1.4/VolatileDouble.cs @@ -34,7 +34,7 @@ namespace Metrics.ConcurrencyUtilities #if CONCURRENCY_UTILS_PUBLIC public #else -internal + internal #endif struct VolatileDouble { diff --git a/Metrics/App_Packages/HdrHistogram/AbstractHistogram.cs b/Metrics/App_Packages/HdrHistogram/AbstractHistogram.cs index 0e896852..307d1dc2 100644 --- a/Metrics/App_Packages/HdrHistogram/AbstractHistogram.cs +++ b/Metrics/App_Packages/HdrHistogram/AbstractHistogram.cs @@ -4,9 +4,9 @@ // Ported to .NET by Iulian Margarintescu under the same license and terms as the java version // Java Version repo: https://github.com/HdrHistogram/HdrHistogram // Latest ported version is available in the Java submodule in the root of the repo +using Metrics.ConcurrencyUtilities; using System; using System.Diagnostics; -using Metrics.ConcurrencyUtilities; namespace HdrHistogram { diff --git a/Metrics/App_Packages/HdrHistogram/AbstractHistogramBase.cs b/Metrics/App_Packages/HdrHistogram/AbstractHistogramBase.cs index 0e92c070..53b2e6d5 100644 --- a/Metrics/App_Packages/HdrHistogram/AbstractHistogramBase.cs +++ b/Metrics/App_Packages/HdrHistogram/AbstractHistogramBase.cs @@ -5,8 +5,8 @@ // Java Version repo: https://github.com/HdrHistogram/HdrHistogram // Latest ported version is available in the Java submodule in the root of the repo -using System; using Metrics.ConcurrencyUtilities; +using System; namespace HdrHistogram { diff --git a/Metrics/App_Packages/HdrHistogram/Recorder.cs b/Metrics/App_Packages/HdrHistogram/Recorder.cs index 6ffb208e..2830e948 100644 --- a/Metrics/App_Packages/HdrHistogram/Recorder.cs +++ b/Metrics/App_Packages/HdrHistogram/Recorder.cs @@ -4,10 +4,10 @@ // Ported to .NET by Iulian Margarintescu under the same license and terms as the java version // Java Version repo: https://github.com/HdrHistogram/HdrHistogram // Latest ported version is available in the Java submodule in the root of the repo +using Metrics.ConcurrencyUtilities; using System; using System.Diagnostics; using System.Runtime.CompilerServices; -using Metrics.ConcurrencyUtilities; namespace HdrHistogram { diff --git a/Metrics/App_Packages/HdrHistogram/WriterReaderPhaser.cs b/Metrics/App_Packages/HdrHistogram/WriterReaderPhaser.cs index f5cfbb9a..9e324999 100644 --- a/Metrics/App_Packages/HdrHistogram/WriterReaderPhaser.cs +++ b/Metrics/App_Packages/HdrHistogram/WriterReaderPhaser.cs @@ -4,9 +4,9 @@ // Ported to .NET by Iulian Margarintescu under the same license and terms as the java version // Java Version repo: https://github.com/HdrHistogram/HdrHistogram // Latest ported version is available in the Java submodule in the root of the repo +using Metrics.ConcurrencyUtilities; using System; using System.Threading; -using Metrics.ConcurrencyUtilities; namespace HdrHistogram { diff --git a/Metrics/Core/CounterMetric.cs b/Metrics/Core/CounterMetric.cs index c1f90cd8..3d17b27b 100644 --- a/Metrics/Core/CounterMetric.cs +++ b/Metrics/Core/CounterMetric.cs @@ -1,9 +1,9 @@ -using System; +using Metrics.ConcurrencyUtilities; +using Metrics.MetricData; +using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Threading; -using Metrics.ConcurrencyUtilities; -using Metrics.MetricData; namespace Metrics.Core { diff --git a/Metrics/Core/DefaultDataProvider.cs b/Metrics/Core/DefaultDataProvider.cs index 3eaf96ab..ec5ceb4c 100644 --- a/Metrics/Core/DefaultDataProvider.cs +++ b/Metrics/Core/DefaultDataProvider.cs @@ -1,7 +1,7 @@ -using System; +using Metrics.MetricData; +using System; using System.Collections.Generic; using System.Linq; -using Metrics.MetricData; namespace Metrics.Core { diff --git a/Metrics/Core/DefaultMetricsBuilder.cs b/Metrics/Core/DefaultMetricsBuilder.cs index 5fd795d7..4bcc9fd5 100644 --- a/Metrics/Core/DefaultMetricsBuilder.cs +++ b/Metrics/Core/DefaultMetricsBuilder.cs @@ -1,8 +1,8 @@  -using System; using Metrics.MetricData; using Metrics.PerfCounters; using Metrics.Sampling; +using System; namespace Metrics.Core { public sealed class DefaultMetricsBuilder : MetricsBuilder diff --git a/Metrics/Core/DefaultRegistryDataProvider.cs b/Metrics/Core/DefaultRegistryDataProvider.cs index 617d99ab..104473ce 100644 --- a/Metrics/Core/DefaultRegistryDataProvider.cs +++ b/Metrics/Core/DefaultRegistryDataProvider.cs @@ -1,6 +1,6 @@ -using System; +using Metrics.MetricData; +using System; using System.Collections.Generic; -using Metrics.MetricData; namespace Metrics.Core { diff --git a/Metrics/Core/GaugeMetric.cs b/Metrics/Core/GaugeMetric.cs index c844ba95..adf3e815 100644 --- a/Metrics/Core/GaugeMetric.cs +++ b/Metrics/Core/GaugeMetric.cs @@ -1,6 +1,6 @@  -using System; using Metrics.MetricData; +using System; namespace Metrics.Core { public interface GaugeImplementation : MetricValueProvider { } diff --git a/Metrics/Core/HistogramMetric.cs b/Metrics/Core/HistogramMetric.cs index 81064947..344dbeee 100644 --- a/Metrics/Core/HistogramMetric.cs +++ b/Metrics/Core/HistogramMetric.cs @@ -1,6 +1,6 @@ -using System; -using Metrics.MetricData; +using Metrics.MetricData; using Metrics.Sampling; +using System; namespace Metrics.Core { diff --git a/Metrics/Core/MetricsBuilder.cs b/Metrics/Core/MetricsBuilder.cs index f5b5fc40..271fc667 100644 --- a/Metrics/Core/MetricsBuilder.cs +++ b/Metrics/Core/MetricsBuilder.cs @@ -1,7 +1,7 @@  -using System; using Metrics.MetricData; using Metrics.Sampling; +using System; namespace Metrics.Core { diff --git a/Metrics/Core/MetricsRegistry.cs b/Metrics/Core/MetricsRegistry.cs index 4d126280..646fb7c8 100644 --- a/Metrics/Core/MetricsRegistry.cs +++ b/Metrics/Core/MetricsRegistry.cs @@ -1,7 +1,7 @@  +using Metrics.MetricData; using System; using System.Collections.Generic; -using Metrics.MetricData; namespace Metrics.Core { public interface RegistryDataProvider diff --git a/Metrics/Core/ReadOnlyMetricsContext.cs b/Metrics/Core/ReadOnlyMetricsContext.cs index b658e45e..3282003f 100644 --- a/Metrics/Core/ReadOnlyMetricsContext.cs +++ b/Metrics/Core/ReadOnlyMetricsContext.cs @@ -1,5 +1,5 @@ -using System; -using Metrics.MetricData; +using Metrics.MetricData; +using System; namespace Metrics.Core { diff --git a/Metrics/Core/TimerMetric.cs b/Metrics/Core/TimerMetric.cs index c1798efb..824a1c9a 100644 --- a/Metrics/Core/TimerMetric.cs +++ b/Metrics/Core/TimerMetric.cs @@ -1,8 +1,8 @@ -using System; -using Metrics.ConcurrencyUtilities; +using Metrics.ConcurrencyUtilities; using Metrics.MetricData; using Metrics.Sampling; using Metrics.Utils; +using System; namespace Metrics.Core { diff --git a/Metrics/Endpoints/MetricsHttpListener.cs b/Metrics/Endpoints/MetricsHttpListener.cs index 9af973dd..3da4b36d 100644 --- a/Metrics/Endpoints/MetricsHttpListener.cs +++ b/Metrics/Endpoints/MetricsHttpListener.cs @@ -1,4 +1,5 @@ -using System; +using Metrics.Logging; +using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; @@ -7,7 +8,6 @@ using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; -using Metrics.Logging; namespace Metrics.Endpoints { diff --git a/Metrics/EventCounters/CPU/CpuHelper.cs b/Metrics/EventCounters/CPU/CpuHelper.cs new file mode 100644 index 00000000..1800eb0e --- /dev/null +++ b/Metrics/EventCounters/CPU/CpuHelper.cs @@ -0,0 +1,75 @@ +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +#if NET6_0_OR_GREATER +using System.Runtime.Versioning; +#endif + +namespace Metrics.EventCounters.CPU +{ + public static class CpuHelper + { + public static ICpuUsageCalculator GetOSCpuUsageCalculator() + { + ICpuUsageCalculator calculator; + + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + calculator = new WindowsCpuUsageCalculator(); + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + calculator = new LinuxCpuUsageCalculator(); + else + throw new NotSupportedException($"Platform '{RuntimeInformation.OSDescription}' not supported"); + + calculator.Init(); + + return calculator; + } + +#if NET6_0_OR_GREATER + [SupportedOSPlatformGuard("windows")] + [SupportedOSPlatformGuard("linux")] +#endif + public static long GetNumberOfActiveCores(Process process) + { + try + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + return NumberOfSetBits(process.ProcessorAffinity.ToInt64()); + else + throw new NotSupportedException($"Platform '{RuntimeInformation.OSDescription}' not supported"); + } + catch (NotSupportedException) + { + return ProcessorInfo.ProcessorCount; + } + catch + { + return ProcessorInfo.ProcessorCount; + } + } + private static long NumberOfSetBits(long i) + { + i -= (i >> 1) & 0x5555555555555555; + i = (i & 0x3333333333333333) + ((i >> 2) & 0x3333333333333333); + return (((i + (i >> 4)) & 0xF0F0F0F0F0F0F0F) * 0x101010101010101) >> 56; + } + public static (long TotalProcessorTimeTicks, long TimeTicks) GetProcessTimes(Process process) + { + try + { + var timeTicks = SystemTime.UtcNow.Ticks; + var totalProcessorTime = process.TotalProcessorTime.Ticks; + return (TotalProcessorTimeTicks: totalProcessorTime, TimeTicks: timeTicks); + } + catch (NotSupportedException) + { + return (0, 0); + } + catch + { + + return (0, 0); + } + } + } +} diff --git a/Metrics/EventCounters/CPU/CpuUsageCalculator.cs b/Metrics/EventCounters/CPU/CpuUsageCalculator.cs new file mode 100644 index 00000000..89664540 --- /dev/null +++ b/Metrics/EventCounters/CPU/CpuUsageCalculator.cs @@ -0,0 +1,75 @@ +using System; + +namespace Metrics.EventCounters.CPU +{ + public abstract class CpuUsageCalculator : ICpuUsageCalculator where T : ProcessInfo + { + public readonly (double MachineCpuUsage, double ProcessCpuUsage, double? MachineIoWait) _emptyCpuUsage = (0, 0, null); + public readonly object _locker = new object(); + + public (double MachineCpuUsage, double ProcessCpuUsage, double? MachineIoWait)? LastCpuUsage; + + public T PreviousInfo; + + public void Init() + { + PreviousInfo = GetProcessInfo(); + } + + public abstract (double MachineCpuUsage, double? MachineIoWait) CalculateMachineCpuUsage(T processInfo); + + public (double MachineCpuUsage, double ProcessCpuUsage, double? MachineIoWait) Calculate() + { + // this is a pretty quick method (sys call only), and shouldn't be + // called heavily, so it is easier to make sure that this is thread + // safe by just holding a lock. + lock (_locker) + { + if (PreviousInfo == null) + return _emptyCpuUsage; + + var currentInfo = GetProcessInfo(); + if (currentInfo == null) + return _emptyCpuUsage; + + var machineCpuUsage = CalculateMachineCpuUsage(currentInfo); + var processCpuUsage = CalculateProcessCpuUsage(currentInfo, machineCpuUsage.MachineCpuUsage); + + PreviousInfo = currentInfo; + + LastCpuUsage = (machineCpuUsage.MachineCpuUsage, processCpuUsage, machineCpuUsage.MachineIoWait); + return (machineCpuUsage.MachineCpuUsage, processCpuUsage, machineCpuUsage.MachineIoWait); + } + } + + public abstract T GetProcessInfo(); + + public double CalculateProcessCpuUsage(ProcessInfo currentInfo, double machineCpuUsage) + { + var processorTimeDiff = currentInfo.TotalProcessorTimeTicks - PreviousInfo.TotalProcessorTimeTicks; + var timeDiff = currentInfo.TimeTicks - PreviousInfo.TimeTicks; + if (timeDiff <= 0) + { + return LastCpuUsage?.ProcessCpuUsage ?? 0; + } + + if (currentInfo.ActiveCores <= 0) + { + return LastCpuUsage?.ProcessCpuUsage ?? 0; + } + + var processCpuUsage = (processorTimeDiff * 100.0) / timeDiff / currentInfo.ActiveCores; + if ((int)currentInfo.ActiveCores == ProcessorInfo.ProcessorCount) + { + // min as sometimes +-1% due to time sampling + processCpuUsage = Math.Min(processCpuUsage, machineCpuUsage); + } + + return Math.Min(100, processCpuUsage); + } + + public void Dispose() + { + } + } +} diff --git a/Metrics/EventCounters/CPU/ICpuUsageCalculator.cs b/Metrics/EventCounters/CPU/ICpuUsageCalculator.cs new file mode 100644 index 00000000..3720a82d --- /dev/null +++ b/Metrics/EventCounters/CPU/ICpuUsageCalculator.cs @@ -0,0 +1,11 @@ +using System; + +namespace Metrics.EventCounters.CPU +{ + public interface ICpuUsageCalculator : IDisposable + { + (double MachineCpuUsage, double ProcessCpuUsage, double? MachineIoWait) Calculate(); + + void Init(); + } +} diff --git a/Metrics/EventCounters/CPU/LinuxCpuUsageCalculator.cs b/Metrics/EventCounters/CPU/LinuxCpuUsageCalculator.cs new file mode 100644 index 00000000..13d69c6c --- /dev/null +++ b/Metrics/EventCounters/CPU/LinuxCpuUsageCalculator.cs @@ -0,0 +1,67 @@ +using System; +using System.IO; + +namespace Metrics.EventCounters.CPU +{ + + public class LinuxCpuUsageCalculator : CpuUsageCalculator + { + private readonly char[] _separators = { ' ', '\t' }; + + public override (double MachineCpuUsage, double? MachineIoWait) CalculateMachineCpuUsage(LinuxInfo linuxInfo) + { + double machineCpuUsage = 0; + double? machineIoWait = 0; + if (linuxInfo.TotalIdle >= PreviousInfo.TotalIdle && + linuxInfo.TotalWorkTime >= PreviousInfo.TotalWorkTime) + { + var idleDiff = linuxInfo.TotalIdle - PreviousInfo.TotalIdle; + var workDiff = linuxInfo.TotalWorkTime - PreviousInfo.TotalWorkTime; + var totalSystemWork = idleDiff + workDiff; + var ioWaitDiff = linuxInfo.TotalIoWait - PreviousInfo.TotalIoWait; + + if (totalSystemWork > 0) + { + machineCpuUsage = (workDiff * 100.0) / totalSystemWork; + machineIoWait = (ioWaitDiff * 100.0) / totalSystemWork; + } + } + else if (LastCpuUsage != null) + { + // overflow + machineCpuUsage = LastCpuUsage.Value.MachineCpuUsage; + machineIoWait = LastCpuUsage.Value.MachineIoWait; + } + + return (machineCpuUsage, machineIoWait); + } + + public override LinuxInfo GetProcessInfo() + { + var lines = File.ReadLines("/proc/stat"); + foreach (var line in lines) + { + if (line.StartsWith("cpu", StringComparison.OrdinalIgnoreCase) == false) + continue; + + var items = line.Split(_separators, StringSplitOptions.RemoveEmptyEntries); + if (items.Length == 0 || items.Length < 9) + continue; + + return new LinuxInfo + { + TotalUserTime = ulong.Parse(items[1]), + TotalUserLowTime = ulong.Parse(items[2]), + TotalSystemTime = ulong.Parse(items[3]), + TotalIdleTime = ulong.Parse(items[4]), + TotalIoWait = ulong.Parse(items[5]), + TotalIRQTime = ulong.Parse(items[6]), + TotalSoftIRQTime = ulong.Parse(items[7]), + TotalStealTime = ulong.Parse(items[8]) + }; + } + + return null; + } + } +} diff --git a/Metrics/EventCounters/CPU/LinuxInfo.cs b/Metrics/EventCounters/CPU/LinuxInfo.cs new file mode 100644 index 00000000..ba8edf06 --- /dev/null +++ b/Metrics/EventCounters/CPU/LinuxInfo.cs @@ -0,0 +1,28 @@ + +namespace Metrics.EventCounters.CPU +{ + public class LinuxInfo : ProcessInfo + { + public ulong TotalUserTime { private get; set; } + + public ulong TotalUserLowTime { private get; set; } + + public ulong TotalSystemTime { private get; set; } + + public ulong TotalIdleTime { private get; set; } + + public ulong TotalIoWait { get; set; } + + public ulong TotalIRQTime { private get; set; } + + public ulong TotalSoftIRQTime { private get; set; } + + public ulong TotalStealTime { private get; set; } + + public ulong TotalWorkTime => TotalUserTime + TotalUserLowTime + TotalSystemTime + + TotalIRQTime + TotalSoftIRQTime + TotalStealTime; + + public ulong TotalIdle => TotalIdleTime + TotalIoWait; + } + +} diff --git a/Metrics/EventCounters/CPU/ProcessInfo.cs b/Metrics/EventCounters/CPU/ProcessInfo.cs new file mode 100644 index 00000000..1b6e6d83 --- /dev/null +++ b/Metrics/EventCounters/CPU/ProcessInfo.cs @@ -0,0 +1,43 @@ +using System; +using System.Diagnostics; + +namespace Metrics.EventCounters.CPU +{ + public class ProcessInfo + { + public ProcessInfo() + { + using (var process = Process.GetCurrentProcess()) + { + var processTimes = CpuHelper.GetProcessTimes(process); + TotalProcessorTimeTicks = processTimes.TotalProcessorTimeTicks; + TimeTicks = processTimes.TimeTicks; + + ActiveCores = CpuHelper.GetNumberOfActiveCores(process); + } + } + + public long TotalProcessorTimeTicks { get; } + + public long TimeTicks { get; } + + public long ActiveCores { get; } + } + + public class SystemTime + { + private static readonly SystemTime Instance = new SystemTime(); + + public Func UtcDateTime; + + // public Action WaitCalled; + + public DateTime GetUtcNow() + { + var temp = UtcDateTime; + return temp?.Invoke() ?? DateTime.UtcNow; + } + + public static DateTime UtcNow => Instance.GetUtcNow(); + } +} diff --git a/Metrics/EventCounters/CPU/ProcessorInfo.cs b/Metrics/EventCounters/CPU/ProcessorInfo.cs new file mode 100644 index 00000000..67936f3a --- /dev/null +++ b/Metrics/EventCounters/CPU/ProcessorInfo.cs @@ -0,0 +1,15 @@ +using System; + +namespace Metrics.EventCounters.CPU +{ + public class ProcessorInfo + { + public static readonly int ProcessorCount = GetProcessorCount(); + + public static int GetProcessorCount() + { + return Environment.ProcessorCount; + } + } + +} diff --git a/Metrics/EventCounters/CPU/WindowsCpuUsageCalculator.cs b/Metrics/EventCounters/CPU/WindowsCpuUsageCalculator.cs new file mode 100644 index 00000000..18bed0c8 --- /dev/null +++ b/Metrics/EventCounters/CPU/WindowsCpuUsageCalculator.cs @@ -0,0 +1,64 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Metrics.EventCounters.CPU +{ + + public class WindowsCpuUsageCalculator : CpuUsageCalculator + { + public override (double MachineCpuUsage, double? MachineIoWait) CalculateMachineCpuUsage(WindowsInfo windowsInfo) + { + var systemIdleDiff = windowsInfo.SystemIdleTime - PreviousInfo.SystemIdleTime; + var systemKernelDiff = windowsInfo.SystemKernelTime - PreviousInfo.SystemKernelTime; + var systemUserDiff = windowsInfo.SystemUserTime - PreviousInfo.SystemUserTime; + var sysTotal = systemKernelDiff + systemUserDiff; + + double machineCpuUsage = 0; + if (sysTotal > 0) + { + machineCpuUsage = (sysTotal - systemIdleDiff) * 100.00 / sysTotal; + } + + return (machineCpuUsage, null); + } + + public override WindowsInfo GetProcessInfo() + { + var systemIdleTime = new FileTime(); + var systemKernelTime = new FileTime(); + var systemUserTime = new FileTime(); + if (GetSystemTimes(ref systemIdleTime, ref systemKernelTime, ref systemUserTime) == false) + { + return null; + } + + return new WindowsInfo + { + SystemIdleTime = GetTime(systemIdleTime), + SystemKernelTime = GetTime(systemKernelTime), + SystemUserTime = GetTime(systemUserTime) + }; + } + + [return: MarshalAs(UnmanagedType.Bool)] + [DllImport("kernel32.dll", SetLastError = true)] + internal static extern bool GetSystemTimes( + ref FileTime lpIdleTime, + ref FileTime lpKernelTime, + ref FileTime lpUserTime); + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ulong GetTime(FileTime fileTime) + { + return ((ulong)fileTime.dwHighDateTime << 32) | (uint)fileTime.dwLowDateTime; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct FileTime + { + public int dwLowDateTime; + public int dwHighDateTime; + } + } + +} diff --git a/Metrics/EventCounters/CPU/WindowsInfo.cs b/Metrics/EventCounters/CPU/WindowsInfo.cs new file mode 100644 index 00000000..15074ea7 --- /dev/null +++ b/Metrics/EventCounters/CPU/WindowsInfo.cs @@ -0,0 +1,12 @@ + +namespace Metrics.EventCounters.CPU +{ + public class WindowsInfo : ProcessInfo + { + public ulong SystemIdleTime { get; set; } + + public ulong SystemKernelTime { get; set; } + + public ulong SystemUserTime { get; set; } + } +} diff --git a/Metrics/HealthChecks.cs b/Metrics/HealthChecks.cs index 15706e4e..c7d44c8f 100644 --- a/Metrics/HealthChecks.cs +++ b/Metrics/HealthChecks.cs @@ -1,8 +1,8 @@ -using System; +using Metrics.Core; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; -using Metrics.Core; namespace Metrics { diff --git a/Metrics/Json/JsonBuilderV2.cs b/Metrics/Json/JsonBuilderV2.cs index ddfa7e41..4bde90f2 100644 --- a/Metrics/Json/JsonBuilderV2.cs +++ b/Metrics/Json/JsonBuilderV2.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; -using System.Globalization; -using Metrics.MetricData; +using Metrics.MetricData; using Metrics.Utils; +using System.Collections.Generic; +using System.Globalization; namespace Metrics.Json { diff --git a/Metrics/Json/JsonCounter.cs b/Metrics/Json/JsonCounter.cs index ee7eaf95..400d452c 100644 --- a/Metrics/Json/JsonCounter.cs +++ b/Metrics/Json/JsonCounter.cs @@ -1,7 +1,7 @@  +using Metrics.MetricData; using System.Collections.Generic; using System.Linq; -using Metrics.MetricData; namespace Metrics.Json { public class JsonCounter : JsonMetric diff --git a/Metrics/Json/JsonGauge.cs b/Metrics/Json/JsonGauge.cs index 78d329c2..e30643cd 100644 --- a/Metrics/Json/JsonGauge.cs +++ b/Metrics/Json/JsonGauge.cs @@ -1,6 +1,6 @@  -using System.Collections.Generic; using Metrics.MetricData; +using System.Collections.Generic; namespace Metrics.Json { diff --git a/Metrics/Json/JsonHealthChecks.cs b/Metrics/Json/JsonHealthChecks.cs index 1272385f..8c9df574 100644 --- a/Metrics/Json/JsonHealthChecks.cs +++ b/Metrics/Json/JsonHealthChecks.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; +using Metrics.Utils; +using System.Collections.Generic; using System.Globalization; using System.Linq; -using Metrics.Utils; namespace Metrics.Json { diff --git a/Metrics/Json/JsonHistogram.cs b/Metrics/Json/JsonHistogram.cs index 479ccfa5..68bde3f3 100644 --- a/Metrics/Json/JsonHistogram.cs +++ b/Metrics/Json/JsonHistogram.cs @@ -1,6 +1,6 @@  -using System.Collections.Generic; using Metrics.MetricData; +using System.Collections.Generic; namespace Metrics.Json { public class JsonHistogram : JsonMetric diff --git a/Metrics/Json/JsonMeter.cs b/Metrics/Json/JsonMeter.cs index bd8ba73d..7ada390c 100644 --- a/Metrics/Json/JsonMeter.cs +++ b/Metrics/Json/JsonMeter.cs @@ -1,8 +1,8 @@  -using System.Collections.Generic; -using System.Linq; using Metrics.MetricData; using Metrics.Utils; +using System.Collections.Generic; +using System.Linq; namespace Metrics.Json { public class JsonMeter : JsonMetric diff --git a/Metrics/Json/JsonMetricsContext.cs b/Metrics/Json/JsonMetricsContext.cs index 81ef799f..e98b4360 100644 --- a/Metrics/Json/JsonMetricsContext.cs +++ b/Metrics/Json/JsonMetricsContext.cs @@ -1,8 +1,8 @@ -using System; +using Metrics.MetricData; +using Metrics.Utils; +using System; using System.Collections.Generic; using System.Linq; -using Metrics.MetricData; -using Metrics.Utils; namespace Metrics.Json { diff --git a/Metrics/Json/JsonTimer.cs b/Metrics/Json/JsonTimer.cs index 802574d5..579f061a 100644 --- a/Metrics/Json/JsonTimer.cs +++ b/Metrics/Json/JsonTimer.cs @@ -1,7 +1,7 @@  -using System.Collections.Generic; using Metrics.MetricData; using Metrics.Utils; +using System.Collections.Generic; namespace Metrics.Json { diff --git a/Metrics/Metric.cs b/Metrics/Metric.cs index a30a0113..ca5f308a 100644 --- a/Metrics/Metric.cs +++ b/Metrics/Metric.cs @@ -1,10 +1,10 @@ -using System; +using Metrics.Logging; +using Metrics.Utils; +using System; using System.Configuration; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; -using Metrics.Logging; -using Metrics.Utils; namespace Metrics { diff --git a/Metrics/Metrics.csproj b/Metrics/Metrics.csproj index 074b5f49..60606208 100644 --- a/Metrics/Metrics.csproj +++ b/Metrics/Metrics.csproj @@ -1,24 +1,22 @@  - - netstandard2.0 - true - true - Metrics - Metrics - - - - - - ..\..\bin\$(Configuration)\Metrics.XML - 1591; 1570; 1587; - - - - - Endpoints\metrics_32.png - - - + + Metrics + Gigya.Metrics + Infrastructure used for hosting Orleans Microdot services, part of the Microdot framework. + + + + + + + + Endpoints\metrics_32.png + + + + + + + \ No newline at end of file diff --git a/Metrics/MetricsConfig.cs b/Metrics/MetricsConfig.cs index f587c9d7..d32ccc4b 100644 --- a/Metrics/MetricsConfig.cs +++ b/Metrics/MetricsConfig.cs @@ -1,13 +1,13 @@ -using System; +using Metrics.Endpoints; +using Metrics.Logging; +using Metrics.MetricData; +using Metrics.Reports; +using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; -using Metrics.Endpoints; -using Metrics.Logging; -using Metrics.MetricData; -using Metrics.Reports; namespace Metrics { diff --git a/Metrics/MetricsContext.cs b/Metrics/MetricsContext.cs index 492396c9..ff7a2b69 100644 --- a/Metrics/MetricsContext.cs +++ b/Metrics/MetricsContext.cs @@ -1,5 +1,5 @@ -using System; -using Metrics.MetricData; +using Metrics.MetricData; +using System; namespace Metrics { /// diff --git a/Metrics/MetricsErrorHandler.cs b/Metrics/MetricsErrorHandler.cs index c256d595..29b70c38 100644 --- a/Metrics/MetricsErrorHandler.cs +++ b/Metrics/MetricsErrorHandler.cs @@ -1,8 +1,8 @@  +using Metrics.Logging; using System; using System.Collections.Concurrent; using System.Diagnostics; -using Metrics.Logging; namespace Metrics { public class MetricsErrorHandler diff --git a/Metrics/PerfCounters/IPerformanceCounterGauge.cs b/Metrics/PerfCounters/IPerformanceCounterGauge.cs new file mode 100644 index 00000000..0831ae67 --- /dev/null +++ b/Metrics/PerfCounters/IPerformanceCounterGauge.cs @@ -0,0 +1,8 @@ +namespace Metrics.PerfCounters +{ + public interface IPerformanceCounterGauge + { + double GetValue(bool resetMetric = false); + double Value { get; } + } +} diff --git a/Metrics/PerfCounters/PerformanceCounterGauge.cs b/Metrics/PerfCounters/PerformanceCounterGauge.cs index 2ac59809..256631c1 100644 --- a/Metrics/PerfCounters/PerformanceCounterGauge.cs +++ b/Metrics/PerfCounters/PerformanceCounterGauge.cs @@ -1,13 +1,12 @@ using Metrics.MetricData; using System; -using System.Diagnostics; -using System.Security.Principal; +using System.Runtime.InteropServices; namespace Metrics.PerfCounters { public class PerformanceCounterGauge : MetricValueProvider { - private readonly PerformanceCounter performanceCounter; + private readonly IPerformanceCounterGauge _performanceCounterGauge; public PerformanceCounterGauge(string category, string counter) : this(category, counter, instance: null) @@ -15,54 +14,19 @@ public PerformanceCounterGauge(string category, string counter) public PerformanceCounterGauge(string category, string counter, string instance) { - try - { - this.performanceCounter = instance == null ? - new PerformanceCounter(category, counter, true) : - new PerformanceCounter(category, counter, instance, true); - Metric.Internal.Counter("Performance Counters", Unit.Custom("Perf Counters")).Increment(); - } - catch (Exception x) - { - var message = "Error reading performance counter data. The application is currently running as user " + GetIdentity() + - ". Make sure the user has access to the performance counters. The user needs to be either Admin or belong to Performance Monitor user group."; - MetricsErrorHandler.Handle(x, message); - } + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + _performanceCounterGauge = new PerformanceCounterGaugeWindows(category, counter, instance); + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + _performanceCounterGauge = new PerformanceCounterGaugeLinux(category, counter, instance); + else + throw new NotSupportedException($"Platform '{RuntimeInformation.OSDescription}' not supported"); } - - private static string GetIdentity() - { - try - { - return Environment.UserName; - } - catch (Exception x) - { - return "[Unknown user | " + x.Message + " ]"; - } - } - + public double GetValue(bool resetMetric = false) { - return this.Value; + return _performanceCounterGauge.GetValue(resetMetric); } - public double Value - { - get - { - try - { - return this.performanceCounter?.NextValue() ?? double.NaN; - } - catch (Exception x) - { - var message = "Error reading performance counter data. The application is currently running as user " + GetIdentity() + - ". Make sure the user has access to the performance counters. The user needs to be either Admin or belong to Performance Monitor user group."; - MetricsErrorHandler.Handle(x, message); - return double.NaN; - } - } - } + public double Value => _performanceCounterGauge.Value; } } diff --git a/Metrics/PerfCounters/PerformanceCounterGaugeLinux.cs b/Metrics/PerfCounters/PerformanceCounterGaugeLinux.cs new file mode 100644 index 00000000..caeb36ae --- /dev/null +++ b/Metrics/PerfCounters/PerformanceCounterGaugeLinux.cs @@ -0,0 +1,31 @@ +using Metrics.MetricData; +using System; + +namespace Metrics.PerfCounters +{ + public class PerformanceCounterGaugeLinux : MetricValueProvider, IPerformanceCounterGauge + { + public PerformanceCounterGaugeLinux(string category, string counter) + : this(category, counter, instance: null) + { } + + public PerformanceCounterGaugeLinux(string category, string counter, string instance) + { + try + { + Metric.Internal.Counter("Performance Counters", Unit.Custom("Perf Counters")).Increment(); + } + catch (Exception x) + { + MetricsErrorHandler.Handle(x); + } + } + + public double GetValue(bool resetMetric = false) + { + return this.Value; + } + + public double Value => double.NaN; + } +} diff --git a/Metrics/PerfCounters/PerformanceCounterGaugeWindows.cs b/Metrics/PerfCounters/PerformanceCounterGaugeWindows.cs new file mode 100644 index 00000000..c20c0eba --- /dev/null +++ b/Metrics/PerfCounters/PerformanceCounterGaugeWindows.cs @@ -0,0 +1,76 @@ +using Metrics.MetricData; +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace Metrics.PerfCounters +{ + public class PerformanceCounterGaugeWindows : MetricValueProvider, IPerformanceCounterGauge + { + private readonly PerformanceCounter _performanceCounter; + public PerformanceCounterGaugeWindows(string category, string counter) + : this(category, counter, instance: null) + { } + + public PerformanceCounterGaugeWindows(string category, string counter, string instance) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + try + { + _performanceCounter = new PerformanceCounter(category, counter, instance ?? "", true); + Metric.Internal.Counter("Performance Counters", Unit.Custom("Perf Counters")).Increment(); + } + catch (Exception x) + { + var message = + "Error reading performance counter data. The application is currently running as user " + + GetIdentity() + + ". Make sure the user has access to the performance counters. The user needs to be either Admin or belong to Performance Monitor user group."; + MetricsErrorHandler.Handle(x, message); + } + } + } + + private static string GetIdentity() + { + try + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return System.Security.Principal.WindowsIdentity.GetCurrent().Name; + + return Environment.UserName; + } + catch (Exception x) + { + return "[Unknown user | " + x.Message + " ]"; + } + } + + public double GetValue(bool resetMetric = false) + { + return Value; + } + + public double Value + { + get + { + try + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return _performanceCounter?.NextValue() ?? double.NaN; + + return double.NaN; + } + catch (Exception x) + { + var message = "Error reading performance counter data. The application is currently running as user " + GetIdentity() + + ". Make sure the user has access to the performance counters. The user needs to be either Admin or belong to Performance Monitor user group."; + MetricsErrorHandler.Handle(x, message); + return double.NaN; + } + } + } + } +} diff --git a/Metrics/PerfCounters/PerformanceCounters.cs b/Metrics/PerfCounters/PerformanceCounters.cs index 4f5bcbe1..93796a94 100644 --- a/Metrics/PerfCounters/PerformanceCounters.cs +++ b/Metrics/PerfCounters/PerformanceCounters.cs @@ -1,18 +1,15 @@ - -using Metrics.Core; +using Metrics.Core; using Metrics.Logging; using System; using System.Diagnostics; using System.Linq; -using System.Security.Principal; +using System.Runtime.InteropServices; namespace Metrics.PerfCounters { internal static class PerformanceCounters { - private static readonly ILog log = LogProvider.GetCurrentClassLogger(); - - private static readonly bool isMono = Type.GetType("Mono.Runtime") != null; + private static readonly ILog Log = LogProvider.GetCurrentClassLogger(); private const string TotalInstance = "_Total"; @@ -115,44 +112,38 @@ private static string GetIdentity() { try { - return WindowsIdentity.GetCurrent().Name; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + return System.Security.Principal.WindowsIdentity.GetCurrent().Name; } catch (Exception x) { return "[Unknown user | " + x.Message + " ]"; } + return "[Unknown user]"; } + private static void WrappedRegister(MetricsContext context, string name, Unit unit, string category, string counter, string instance = null, Func derivate = null, MetricTags tags = default(MetricTags)) { - log.Debug(() => $"Registering performance counter [{counter}] in category [{category}] for instance [{instance ?? "none"}]"); + Log.Debug(() => $"Registering performance counter [{counter}] in category [{category}] for instance [{instance ?? "none"}]"); - if (PerformanceCounterCategory.Exists(category)) + if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !PerformanceCounterCategory.Exists(category)) + return; + + var counterTags = new MetricTags(tags.Tags.Concat(new[] { "PerfCounter" })); + if (derivate == null) { - if (instance == null || PerformanceCounterCategory.InstanceExists(instance, category)) - { - if (PerformanceCounterCategory.CounterExists(counter, category)) - { - var counterTags = new MetricTags(tags.Tags.Concat(new[] { "PerfCounter" })); - if (derivate == null) - { - context.Advanced.Gauge(name, () => new PerformanceCounterGauge(category, counter, instance), unit, counterTags); - } - else - { - context.Advanced.Gauge(name, () => new DerivedGauge(new PerformanceCounterGauge(category, counter, instance), derivate), unit, counterTags); - } - return; - } - } + context.Advanced.Gauge(name, + () => new PerformanceCounterGauge(category, counter, instance), unit, counterTags); } - - if (!isMono) + else { - log.ErrorFormat("Performance counter does not exist [{0}] in category [{1}] for instance [{2}]", counter, category, instance ?? "none"); + context.Advanced.Gauge(name, + () => new DerivedGauge(new PerformanceCounterGauge(category, counter, instance), + derivate), unit, counterTags); } } } diff --git a/Metrics/Properties/AssemblyInfo.cs b/Metrics/Properties/AssemblyInfo.cs index d76dd1f0..5f282702 100644 --- a/Metrics/Properties/AssemblyInfo.cs +++ b/Metrics/Properties/AssemblyInfo.cs @@ -1 +1 @@ -using System.Reflection; + \ No newline at end of file diff --git a/Metrics/RemoteMetrics/HttpRemoteMetrics.cs b/Metrics/RemoteMetrics/HttpRemoteMetrics.cs index 39e86d68..1b168429 100644 --- a/Metrics/RemoteMetrics/HttpRemoteMetrics.cs +++ b/Metrics/RemoteMetrics/HttpRemoteMetrics.cs @@ -1,8 +1,8 @@ -using System; +using Metrics.Json; +using System; using System.Net; using System.Threading; using System.Threading.Tasks; -using Metrics.Json; namespace Metrics.RemoteMetrics { diff --git a/Metrics/RemoteMetrics/RemoteMetricsContext.cs b/Metrics/RemoteMetrics/RemoteMetricsContext.cs index 2bfde2a4..e3bffb86 100644 --- a/Metrics/RemoteMetrics/RemoteMetricsContext.cs +++ b/Metrics/RemoteMetrics/RemoteMetricsContext.cs @@ -1,5 +1,5 @@ using System; -using System.Threading; +using System.Net.Http; using System.Threading.Tasks; using Metrics.Core; using Metrics.Json; @@ -10,9 +10,9 @@ namespace Metrics.RemoteMetrics { public sealed class RemoteMetricsContext : ReadOnlyMetricsContext, MetricsDataProvider { - private readonly Scheduler scheduler; - - private MetricsData currentData = MetricsData.Empty; + private readonly Scheduler _scheduler; + private readonly HttpClient _httpClient; + private MetricsData _currentData = MetricsData.Empty; public RemoteMetricsContext(Uri remoteUri, TimeSpan updateInterval, Func deserializer) : this(new ActionScheduler(), remoteUri, updateInterval, deserializer) @@ -20,36 +20,39 @@ public RemoteMetricsContext(Uri remoteUri, TimeSpan updateInterval, Func deserializer) { - this.scheduler = scheduler; - this.scheduler.Start(updateInterval, c => UpdateMetrics(remoteUri, deserializer, c)); + _scheduler = scheduler; + _scheduler.Start(updateInterval, c => UpdateMetrics(remoteUri, deserializer)); } - private async Task UpdateMetrics(Uri remoteUri, Func deserializer, CancellationToken token) + private async Task UpdateMetrics(Uri remoteUri, Func deserializer) { try { - var remoteContext = await HttpRemoteMetrics.FetchRemoteMetrics(remoteUri, deserializer, token).ConfigureAwait(false); + string response = await _httpClient.GetStringAsync(remoteUri); + JsonMetricsContext remoteContext = deserializer(response); remoteContext.Environment.Add("RemoteUri", remoteUri.ToString()); remoteContext.Environment.Add("RemoteVersion", remoteContext.Version); remoteContext.Environment.Add("RemoteTimestamp", Clock.FormatTimestamp(remoteContext.Timestamp)); - - this.currentData = remoteContext.ToMetricsData(); + + _currentData = remoteContext.ToMetricsData(); } catch (Exception x) { MetricsErrorHandler.Handle(x, "Error updating metrics data from " + remoteUri); - this.currentData = MetricsData.Empty; + _currentData = MetricsData.Empty; } } - public override MetricsDataProvider DataProvider { get { return this; } } - public MetricsData CurrentMetricsData { get { return this.currentData; } } + public override MetricsDataProvider DataProvider => this; + public MetricsData CurrentMetricsData => _currentData; protected override void Dispose(bool disposing) { if (disposing) { - using (this.scheduler) { } + _httpClient?.Dispose(); + + using (_scheduler) { } } base.Dispose(disposing); } diff --git a/Metrics/RemoteMetrics/RemoteMetricsExtensions.cs b/Metrics/RemoteMetrics/RemoteMetricsExtensions.cs index 6ca84e1c..f6b8573b 100644 --- a/Metrics/RemoteMetrics/RemoteMetricsExtensions.cs +++ b/Metrics/RemoteMetrics/RemoteMetricsExtensions.cs @@ -1,6 +1,6 @@ -using System; -using Metrics.Json; +using Metrics.Json; using Metrics.RemoteMetrics; +using System; namespace Metrics { diff --git a/Metrics/Reporters/EndpointReporterConfig.cs b/Metrics/Reporters/EndpointReporterConfig.cs index ef2f3743..8b4cc648 100644 --- a/Metrics/Reporters/EndpointReporterConfig.cs +++ b/Metrics/Reporters/EndpointReporterConfig.cs @@ -1,10 +1,10 @@ -using System; -using System.Linq; -using System.Text; -using Metrics.Endpoints; +using Metrics.Endpoints; using Metrics.Json; using Metrics.MetricData; using Metrics.Reports; +using System; +using System.Linq; +using System.Text; namespace Metrics.Reporters { diff --git a/Metrics/Reporters/HumanReadableReport.cs b/Metrics/Reporters/HumanReadableReport.cs index f079e864..365e40db 100644 --- a/Metrics/Reporters/HumanReadableReport.cs +++ b/Metrics/Reporters/HumanReadableReport.cs @@ -1,6 +1,6 @@ -using System.Linq; -using Metrics.MetricData; +using Metrics.MetricData; using Metrics.Utils; +using System.Linq; namespace Metrics.Reporters { diff --git a/Metrics/Reporters/MetricsEndpointReports.cs b/Metrics/Reporters/MetricsEndpointReports.cs index 7a57e5cb..b84e35a7 100644 --- a/Metrics/Reporters/MetricsEndpointReports.cs +++ b/Metrics/Reporters/MetricsEndpointReports.cs @@ -1,8 +1,8 @@ -using System; -using System.Collections.Generic; -using Metrics.Endpoints; +using Metrics.Endpoints; using Metrics.MetricData; using Metrics.Reporters; +using System; +using System.Collections.Generic; namespace Metrics.Reports { diff --git a/Metrics/Reporters/MetricsReport.cs b/Metrics/Reporters/MetricsReport.cs index c86b5872..09069d18 100644 --- a/Metrics/Reporters/MetricsReport.cs +++ b/Metrics/Reporters/MetricsReport.cs @@ -1,6 +1,6 @@ -using System; +using Metrics.MetricData; +using System; using System.Threading; -using Metrics.MetricData; namespace Metrics.Reporters { diff --git a/Metrics/Reporters/MetricsReports.cs b/Metrics/Reporters/MetricsReports.cs index d22b5354..55066274 100644 --- a/Metrics/Reporters/MetricsReports.cs +++ b/Metrics/Reporters/MetricsReports.cs @@ -1,9 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Configuration; -using Metrics.MetricData; +using Metrics.MetricData; using Metrics.Reporters; using Metrics.Utils; +using System; +using System.Collections.Generic; +using System.Configuration; namespace Metrics.Reports { diff --git a/Metrics/Reporters/ScheduledReporter.cs b/Metrics/Reporters/ScheduledReporter.cs index 74775835..08e4d3db 100644 --- a/Metrics/Reporters/ScheduledReporter.cs +++ b/Metrics/Reporters/ScheduledReporter.cs @@ -1,7 +1,7 @@ -using System; -using System.Threading; -using Metrics.MetricData; +using Metrics.MetricData; using Metrics.Utils; +using System; +using System.Threading; namespace Metrics.Reporters { diff --git a/Metrics/Sampling/ExponentiallyDecayingReservoir.cs b/Metrics/Sampling/ExponentiallyDecayingReservoir.cs index 54057ca4..8e473544 100644 --- a/Metrics/Sampling/ExponentiallyDecayingReservoir.cs +++ b/Metrics/Sampling/ExponentiallyDecayingReservoir.cs @@ -1,8 +1,8 @@ -using System; +using Metrics.ConcurrencyUtilities; +using Metrics.Utils; +using System; using System.Collections.Generic; using System.Threading; -using Metrics.ConcurrencyUtilities; -using Metrics.Utils; namespace Metrics.Sampling { diff --git a/Metrics/Sampling/HdrSnapshot.cs b/Metrics/Sampling/HdrSnapshot.cs index 3f93534e..2ed7bd0f 100644 --- a/Metrics/Sampling/HdrSnapshot.cs +++ b/Metrics/Sampling/HdrSnapshot.cs @@ -1,6 +1,6 @@ -using System.Collections.Generic; +using HdrHistogram; +using System.Collections.Generic; using System.Linq; -using HdrHistogram; namespace Metrics.Sampling { diff --git a/Metrics/Sampling/SlidingWindowReservoir.cs b/Metrics/Sampling/SlidingWindowReservoir.cs index c08fe280..f3c14062 100644 --- a/Metrics/Sampling/SlidingWindowReservoir.cs +++ b/Metrics/Sampling/SlidingWindowReservoir.cs @@ -1,6 +1,6 @@ -using System; +using Metrics.ConcurrencyUtilities; +using System; using System.Linq; -using Metrics.ConcurrencyUtilities; namespace Metrics.Sampling { diff --git a/Metrics/Timer.cs b/Metrics/Timer.cs index 18131ed4..3b29dca8 100644 --- a/Metrics/Timer.cs +++ b/Metrics/Timer.cs @@ -1,5 +1,5 @@ -using System; -using Metrics.Utils; +using Metrics.Utils; +using System; namespace Metrics { diff --git a/Metrics/Unit.cs b/Metrics/Unit.cs index 5809d837..87dbe1a6 100644 --- a/Metrics/Unit.cs +++ b/Metrics/Unit.cs @@ -1,8 +1,8 @@  +using Metrics.Utils; using System; using System.Diagnostics; using System.Globalization; -using Metrics.Utils; namespace Metrics { [DebuggerDisplay("{Name}")] diff --git a/Metrics/Utils/AppEnvironment.cs b/Metrics/Utils/AppEnvironment.cs index 7adfbe9c..435fc69e 100644 --- a/Metrics/Utils/AppEnvironment.cs +++ b/Metrics/Utils/AppEnvironment.cs @@ -1,12 +1,12 @@ -using System; +using Metrics.Logging; +using Metrics.MetricData; +using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.Sockets; using System.Reflection; -using Metrics.Logging; -using Metrics.MetricData; namespace Metrics.Utils { diff --git a/Metrics/Utils/EWMA.cs b/Metrics/Utils/EWMA.cs index 3d08a080..a1e21a3b 100644 --- a/Metrics/Utils/EWMA.cs +++ b/Metrics/Utils/EWMA.cs @@ -1,7 +1,7 @@  +using Metrics.ConcurrencyUtilities; using System; using System.Diagnostics; -using Metrics.ConcurrencyUtilities; namespace Metrics.Utils { diff --git a/Metrics/paket.references b/Metrics/paket.references deleted file mode 100644 index bedc83c3..00000000 --- a/Metrics/paket.references +++ /dev/null @@ -1,4 +0,0 @@ -System.Diagnostics.PerformanceCounter -LibLog -Microsoft.CSharp -System.Configuration.ConfigurationManager \ No newline at end of file diff --git a/Metrics/paket.template b/Metrics/paket.template deleted file mode 100644 index 7a49aa11..00000000 --- a/Metrics/paket.template +++ /dev/null @@ -1,13 +0,0 @@ -type - project -description - Infrastructure used for hosting Orleans Microdot services, part of the - Microdot framework. -projectUrl - https://github.com/gigya/microdot -licenseUrl - https://github.com/gigya/microdot/blob/master/LICENSE.md -tags - gigya microdot microservice microservices -authors - metrics.net \ No newline at end of file diff --git a/Microdot.sln b/Microdot.sln index f09b2b07..a6063296 100644 --- a/Microdot.sln +++ b/Microdot.sln @@ -9,12 +9,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".Solution Items", ".Solutio ProjectSection(SolutionItems) = preProject Changelog.md = Changelog.md Directory.Build.props = Directory.Build.props + Directory.Build.targets = Directory.Build.targets + global.json = global.json LICENSE.md = LICENSE.md main.ruleset = main.ruleset - paket.dependencies = paket.dependencies - paket.lock = paket.lock README.md = README.md - SolutionVersion.cs = SolutionVersion.cs + test.runsettings = test.runsettings EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Gigya.Microdot.Fakes", "Gigya.Microdot.Fakes\Gigya.Microdot.Fakes.csproj", "{2865F69B-D847-4901-8945-4941E463F94E}" @@ -41,8 +41,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Gigya.Microdot.Testing.Shar EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Gigya.Microdot.ServiceDiscovery", "Gigya.Microdot.ServiceDiscovery\Gigya.Microdot.ServiceDiscovery.csproj", "{37E6909E-51E2-4BBA-8EFC-DBDF086D860E}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Gigya.Microdot.ServiceContract.UnitTests", "tests\Gigya.Microdot.ServiceContract.UnitTests\Gigya.Microdot.ServiceContract.UnitTests.csproj", "{C224F79A-EAB5-48B8-B587-65772B0966EF}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Gigya.Microdot.Logging.NLog", "Gigya.Microdot.Logging.NLog\Gigya.Microdot.Logging.NLog.csproj", "{06E45085-5A54-4BFE-BD24-E9C3983A2689}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Gigya.Microdot.Orleans.Hosting.UnitTests", "tests\Gigya.Microdot.Orleans.Hosting.UnitTests\Gigya.Microdot.Orleans.Hosting.UnitTests.csproj", "{8E548D57-5880-4283-BDF5-7386886D481D}" @@ -65,21 +63,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CalculatorService.Orleans", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Gigya.Microdot.Common.Tests", "Gigya.Microdot.Common.Tests\Gigya.Microdot.Common.Tests.csproj", "{47CBF637-AB8F-4568-86D6-EAB6EF08B9CE}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ServiceContract", "ServiceContract", "{A14C7201-FAAC-487C-AED3-8A0CA86A8A88}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Gigya.ServiceContract", "Gigya.ServiceContract\Gigya.ServiceContract.csproj", "{DB6D3561-835E-40D5-B9D4-83951CF426DF}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Gigya.Microdot.LanguageExtensions", "Gigya.Microdot.LanguageExtensions\Gigya.Microdot.LanguageExtensions.csproj", "{54F30C07-4D6C-4E8F-8C38-BCD8B0ECEE43}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{9E13FD47-A463-4D69-A078-59EECAEC294F}" - ProjectSection(SolutionItems) = preProject - Changelog.md = Changelog.md - Directory.Build.props = Directory.Build.props - paket.dependencies = paket.dependencies - README.md = README.md - test.runsettings = test.runsettings - EndProjectSection -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Metrics", "Metrics\Metrics.csproj", "{C4AB90EF-198B-47E8-B5EE-0B517C7250D6}" EndProject Global @@ -136,10 +121,6 @@ Global {37E6909E-51E2-4BBA-8EFC-DBDF086D860E}.Debug|Any CPU.Build.0 = Debug|Any CPU {37E6909E-51E2-4BBA-8EFC-DBDF086D860E}.Release|Any CPU.ActiveCfg = Release|Any CPU {37E6909E-51E2-4BBA-8EFC-DBDF086D860E}.Release|Any CPU.Build.0 = Release|Any CPU - {C224F79A-EAB5-48B8-B587-65772B0966EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C224F79A-EAB5-48B8-B587-65772B0966EF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C224F79A-EAB5-48B8-B587-65772B0966EF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C224F79A-EAB5-48B8-B587-65772B0966EF}.Release|Any CPU.Build.0 = Release|Any CPU {06E45085-5A54-4BFE-BD24-E9C3983A2689}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {06E45085-5A54-4BFE-BD24-E9C3983A2689}.Debug|Any CPU.Build.0 = Debug|Any CPU {06E45085-5A54-4BFE-BD24-E9C3983A2689}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -180,10 +161,6 @@ Global {47CBF637-AB8F-4568-86D6-EAB6EF08B9CE}.Debug|Any CPU.Build.0 = Debug|Any CPU {47CBF637-AB8F-4568-86D6-EAB6EF08B9CE}.Release|Any CPU.ActiveCfg = Release|Any CPU {47CBF637-AB8F-4568-86D6-EAB6EF08B9CE}.Release|Any CPU.Build.0 = Release|Any CPU - {DB6D3561-835E-40D5-B9D4-83951CF426DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DB6D3561-835E-40D5-B9D4-83951CF426DF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DB6D3561-835E-40D5-B9D4-83951CF426DF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DB6D3561-835E-40D5-B9D4-83951CF426DF}.Release|Any CPU.Build.0 = Release|Any CPU {54F30C07-4D6C-4E8F-8C38-BCD8B0ECEE43}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {54F30C07-4D6C-4E8F-8C38-BCD8B0ECEE43}.Debug|Any CPU.Build.0 = Debug|Any CPU {54F30C07-4D6C-4E8F-8C38-BCD8B0ECEE43}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -197,7 +174,6 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution - {C224F79A-EAB5-48B8-B587-65772B0966EF} = {F8A1B754-3C63-4051-A1A5-C51E916F90EB} {8E548D57-5880-4283-BDF5-7386886D481D} = {F8A1B754-3C63-4051-A1A5-C51E916F90EB} {0A24AE97-EE88-4E8B-8B92-092884D41399} = {F8A1B754-3C63-4051-A1A5-C51E916F90EB} {A17C9A6D-317D-441C-B33A-3807B67B4FA2} = {F8A1B754-3C63-4051-A1A5-C51E916F90EB} @@ -206,7 +182,6 @@ Global {BCD894C2-29B3-4C76-8E5D-5781A5A10C67} = {79538186-DFAD-463C-B4D1-CD0917CF5954} {10E10FDE-8A2C-4D5D-8FC1-15FACF844E80} = {79538186-DFAD-463C-B4D1-CD0917CF5954} {47CBF637-AB8F-4568-86D6-EAB6EF08B9CE} = {F8A1B754-3C63-4051-A1A5-C51E916F90EB} - {DB6D3561-835E-40D5-B9D4-83951CF426DF} = {A14C7201-FAAC-487C-AED3-8A0CA86A8A88} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EnterpriseLibraryConfigurationToolBinariesPathV6 = packages\EnterpriseLibrary.TransientFaultHandling.6.0.1304.0\lib\portable-net45+win+wp8 diff --git a/Sample/CalculatorService.Client/App.config b/Sample/CalculatorService.Client/App.config deleted file mode 100644 index e5a96187..00000000 --- a/Sample/CalculatorService.Client/App.config +++ /dev/null @@ -1,17 +0,0 @@ - - - -
- - - - - - - - - - - - - diff --git a/Sample/CalculatorService.Client/CalculatorService.Client.csproj b/Sample/CalculatorService.Client/CalculatorService.Client.csproj index 1ddfc7c3..444f019d 100644 --- a/Sample/CalculatorService.Client/CalculatorService.Client.csproj +++ b/Sample/CalculatorService.Client/CalculatorService.Client.csproj @@ -1,26 +1,28 @@  - - Exe - net472 - true - true - 1591 - - - - PreserveNewest - - - - - - - - - - - - - + + CalculatorService.Client + Exe + false + true + net472;net5.0;net6.0 + false + + + + PreserveNewest + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Sample/CalculatorService.Client/Program.cs b/Sample/CalculatorService.Client/Program.cs index b87e0ede..95973a15 100644 --- a/Sample/CalculatorService.Client/Program.cs +++ b/Sample/CalculatorService.Client/Program.cs @@ -1,75 +1,68 @@ -using System; -using System.Diagnostics; -using System.Net; -using System.Threading.Tasks; -using CalculatorService.Interface; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; -using Gigya.Microdot.Interfaces; -using Gigya.Microdot.Interfaces.Configuration; -using Gigya.Microdot.Logging.NLog; -using Gigya.Microdot.Ninject; -using Gigya.Microdot.ServiceProxy.Caching; -using Gigya.Microdot.SharedLogic.Events; -using Gigya.Microdot.SharedLogic.SystemWrappers; -using Gigya.Microdot.UnitTests.Caching; -using Ninject; - -namespace CalculatorService.Client -{ - class Program - { - static FakeRevokingManager _fakeRevokingManager = new FakeRevokingManager(); - - static async Task Main(string[] args) - { - try - { - using (var microdotInitializer = new MicrodotInitializer("test-client", new NLogModule(), k => - { - k.Rebind().ToConstant(_fakeRevokingManager); - })) - { - //NLog.LogManager.GlobalThreshold = NLog.LogLevel.Info; - var calculatorService = microdotInitializer.Kernel.Get(); - - Task.Factory.StartNew(() => ListenToRevokes()); - - while (true) - { - try - { - var result = await calculatorService.Add(1, 2); - Console.WriteLine($"Value: {result}"); - } - catch (Exception e) - { - Console.WriteLine($"Error: {e.Message}"); - // throw; - } - - await Task.Delay(1000); - +using CalculatorService.Interface; +using Gigya.Microdot.Logging.NLog; +using Gigya.Microdot.Ninject; +using Gigya.Microdot.ServiceProxy.Caching; +using Gigya.Microdot.UnitTests.Caching; +using Ninject; +using System; +using System.Threading.Tasks; + +namespace CalculatorService.Client +{ + class Program + { + static FakeRevokingManager _fakeRevokingManager = new FakeRevokingManager(); + + static async Task Main(string[] args) + { + try + { + Random rnd = new Random(Guid.NewGuid().GetHashCode()); + using (var microdotInitializer = new MicrodotInitializer("test-client", new NLogModule(), k => + { + k.Rebind().ToConstant(_fakeRevokingManager); + })) + { + //NLog.LogManager.GlobalThreshold = NLog.LogLevel.Info; + var calculatorService = microdotInitializer.Kernel.Get(); + + Task.Factory.StartNew(() => ListenToRevokes()); + + while (true) + { + try + { + int a = rnd.Next(100); + int b = rnd.Next(100); + var result = await calculatorService.Add(a, b); + Console.WriteLine($"{a}+{b}={result}"); + await Task.Delay(1000); + } + catch (Exception e) + { + Console.WriteLine($"Error: {e.Message}"); + throw; + } } - } - } - catch (Exception ex) - { - Console.Error.WriteLine(ex); - } - } - - private static async Task ListenToRevokes() - { + } + } + catch (Exception ex) + { + Console.Error.WriteLine(ex); + } + } + + private static async Task ListenToRevokes() + { while (true) - { - var revokeKey = Console.ReadLine(); - + { + var revokeKey = Console.ReadLine(); + Console.WriteLine($"Before revoke of {revokeKey}"); - await _fakeRevokingManager.Revoke(revokeKey); - Console.WriteLine($"After revoke of {revokeKey}"); + await _fakeRevokingManager.Revoke(revokeKey); + Console.WriteLine($"After revoke of {revokeKey}"); } - } - } -} + } + } +} diff --git a/Sample/CalculatorService.Client/Properties/AssemblyInfo.cs b/Sample/CalculatorService.Client/Properties/AssemblyInfo.cs index de64a2e5..13b32751 100644 --- a/Sample/CalculatorService.Client/Properties/AssemblyInfo.cs +++ b/Sample/CalculatorService.Client/Properties/AssemblyInfo.cs @@ -1,6 +1,4 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from diff --git a/Sample/CalculatorService.Client/paket.references b/Sample/CalculatorService.Client/paket.references deleted file mode 100644 index b156c01a..00000000 --- a/Sample/CalculatorService.Client/paket.references +++ /dev/null @@ -1,2 +0,0 @@ -Ninject -Ninject.Extensions.Factory diff --git a/Sample/CalculatorService.Interface/CalculatorService.Interface.csproj b/Sample/CalculatorService.Interface/CalculatorService.Interface.csproj index f490d31f..46785158 100644 --- a/Sample/CalculatorService.Interface/CalculatorService.Interface.csproj +++ b/Sample/CalculatorService.Interface/CalculatorService.Interface.csproj @@ -1,26 +1,9 @@  - - {1FB8E464-6A36-44A2-A343-8E95B51B4542} - net472 - Gigya.Microdot.Sample.CalculatorService.Interface - Gigya.Microdot.Sample.CalculatorService.Interface - Copyright © 2018 - false - bin\$(Configuration)\ - $(SolutionDir)main.ruleset - - - full - 3 - - - pdbonly - - - - Designer - - - + + Gigya.Microdot.Sample.CalculatorService.Interface + + + + \ No newline at end of file diff --git a/Sample/CalculatorService.Interface/ICalculatorService.cs b/Sample/CalculatorService.Interface/ICalculatorService.cs index d630734e..08b8d2e4 100644 --- a/Sample/CalculatorService.Interface/ICalculatorService.cs +++ b/Sample/CalculatorService.Interface/ICalculatorService.cs @@ -20,10 +20,10 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Threading.Tasks; using Gigya.Common.Contracts.Attributes; using Gigya.Common.Contracts.HttpService; using Gigya.ServiceContract.HttpService; +using System.Threading.Tasks; namespace CalculatorService.Interface { diff --git a/Sample/CalculatorService.Interface/Properties/AssemblyInfo.cs b/Sample/CalculatorService.Interface/Properties/AssemblyInfo.cs index d431ae21..db33ea10 100644 --- a/Sample/CalculatorService.Interface/Properties/AssemblyInfo.cs +++ b/Sample/CalculatorService.Interface/Properties/AssemblyInfo.cs @@ -1,6 +1,4 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from diff --git a/Sample/CalculatorService.Interface/paket.references b/Sample/CalculatorService.Interface/paket.references deleted file mode 100644 index d94f2433..00000000 --- a/Sample/CalculatorService.Interface/paket.references +++ /dev/null @@ -1 +0,0 @@ -Gigya.ServiceContract \ No newline at end of file diff --git a/Sample/CalculatorService.Orleans/App.config b/Sample/CalculatorService.Orleans/App.config deleted file mode 100644 index 18cc2f61..00000000 --- a/Sample/CalculatorService.Orleans/App.config +++ /dev/null @@ -1,22 +0,0 @@ - - - -
- - - - - - - - - - - - - - - - - - diff --git a/Sample/CalculatorService.Orleans/CalculatorService.Orleans.csproj b/Sample/CalculatorService.Orleans/CalculatorService.Orleans.csproj index 0bd85344..bcf5856c 100644 --- a/Sample/CalculatorService.Orleans/CalculatorService.Orleans.csproj +++ b/Sample/CalculatorService.Orleans/CalculatorService.Orleans.csproj @@ -1,26 +1,27 @@  - - Exe - net472 - true - false - $(SolutionDir)main.ruleset - - - - PreserveNewest - - - - - - - - - - - - - + + CalculatorService.Orleans + Exe + false + true + net472;net5.0;net6.0 + Linux + + + + + + + + + + + + + + + PreserveNewest + + \ No newline at end of file diff --git a/Sample/CalculatorService.Orleans/CalculatorService.cs b/Sample/CalculatorService.Orleans/CalculatorService.cs index 514d87dd..610b1417 100644 --- a/Sample/CalculatorService.Orleans/CalculatorService.cs +++ b/Sample/CalculatorService.Orleans/CalculatorService.cs @@ -1,11 +1,9 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using CalculatorService.Interface; -using Gigya.Microdot.SharedLogic.Security; +using CalculatorService.Interface; using Gigya.ServiceContract.HttpService; using Orleans; using Orleans.Concurrency; +using System.Threading; +using System.Threading.Tasks; namespace CalculatorService.Orleans { @@ -17,15 +15,12 @@ public interface ICalculatorServiceGrain : ICalculatorService, IGrainWithInteger [StatelessWorker, Reentrant] public class CalculatorService : Grain, ICalculatorServiceGrain { - private readonly IMicrodotTypePolicySerializationBinder _binder; - - public CalculatorService(IMicrodotTypePolicySerializationBinder binder) + public CalculatorService() { - _binder = binder; + } public Task Add(int a, int b) { - _binder.BindToType("foo","bar"); return Task.FromResult((a + b).ToString()); } diff --git a/Sample/CalculatorService.Orleans/CalculatorServiceHost.cs b/Sample/CalculatorService.Orleans/CalculatorServiceHost.cs index ac7ac4cd..f7dbe269 100644 --- a/Sample/CalculatorService.Orleans/CalculatorServiceHost.cs +++ b/Sample/CalculatorService.Orleans/CalculatorServiceHost.cs @@ -1,9 +1,9 @@ -using System; -using Gigya.Microdot.Logging.NLog; +using Gigya.Microdot.Logging.NLog; using Gigya.Microdot.Ninject; using Gigya.Microdot.Orleans.Ninject.Host; -using System.Threading.Tasks; using Orleans; +using System; +using System.Threading.Tasks; namespace CalculatorService.Orleans { diff --git a/Sample/CalculatorService.Orleans/Dockerfile b/Sample/CalculatorService.Orleans/Dockerfile new file mode 100644 index 00000000..4c22383e --- /dev/null +++ b/Sample/CalculatorService.Orleans/Dockerfile @@ -0,0 +1,20 @@ +#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. + +FROM mcr.microsoft.com/dotnet/runtime:6.0 AS base +WORKDIR /app + +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build +WORKDIR /src +COPY ["CalculatorService.Orleans/CalculatorService.Orleans.csproj", "CalculatorService.Orleans/"] +RUN dotnet restore "CalculatorService.Orleans/CalculatorService.Orleans.csproj" +COPY . . + WORKDIR "/src/CalculatorService.Orleans" +RUN dotnet build "CalculatorService.Orleans.csproj" -c Release -o /app/build + +FROM build AS publish +RUN dotnet publish "CalculatorService.Orleans.csproj" -c Release -o /app/publish + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . + ENTRYPOINT ["dotnet", "CalculatorService.Orleans.dll"] \ No newline at end of file diff --git a/Sample/CalculatorService.Orleans/Properties/AssemblyInfo.cs b/Sample/CalculatorService.Orleans/Properties/AssemblyInfo.cs index 9941fcbd..576eefd2 100644 --- a/Sample/CalculatorService.Orleans/Properties/AssemblyInfo.cs +++ b/Sample/CalculatorService.Orleans/Properties/AssemblyInfo.cs @@ -1,6 +1,4 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from diff --git a/Sample/CalculatorService.Orleans/Properties/launchSettings.json b/Sample/CalculatorService.Orleans/Properties/launchSettings.json new file mode 100644 index 00000000..376591af --- /dev/null +++ b/Sample/CalculatorService.Orleans/Properties/launchSettings.json @@ -0,0 +1,16 @@ +{ + "profiles": { + "CalculatorService": { + "commandName": "Project", + "commandLineArgs": "--ServiceStartupMode:CommandLineInteractive --ConsoleOutputMode:Color" + }, + "Docker": { + "commandName": "Docker", + "commandLineArgs": "--ServiceStartupMode:CommandLineInteractive --ConsoleOutputMode:Color", + "environmentVariables": { + "GIGYA_ENVVARS_FILE": "/gigya/environmentVariablesLinux.json" + }, + "DockerfileRunArguments": "-v C:\\Gigya:/gigya -p 12323:12323 -p 12324:12324 -p 12325:12325 -p 12326:12326 -p 12327:12327 -p 12328:12328 -e ENV=st11 -e DC=il1 -e region=il1 -e GIGYA_BASE_PATH=/gigya -e GIGYA_CONFIG_PATHS_FILE=/gigya/config/loadPathsWithLocal.json -e GIGYA_CONFIG_ROOT=/gigya/config -e CONSUL=consul.service.il1.gigya.io:8500 -e GIGYA_SERVICE_INSTANCE_NAME=A" + } + } +} \ No newline at end of file diff --git a/Sample/CalculatorService.Orleans/docker-entrypoint.sh b/Sample/CalculatorService.Orleans/docker-entrypoint.sh new file mode 100644 index 00000000..60fd6944 --- /dev/null +++ b/Sample/CalculatorService.Orleans/docker-entrypoint.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash + +usage() +{ + echo "Please enter the following arguments: \ + --cert_filepath: pfx certificate file path. \ + --cert_password: pfx certificate password." +} + +cert_filepath="" +cert_password="" + +while [[ "$1" != "" ]]; do + case $1 in + --cert_filepath ) shift + cert_filepath=$1 + ;; + --cert_password ) shift + cert_password=$1 + ;; + -h | --help ) usage + exit + ;; + * ) usage + exit 1 + esac + shift +done + + +# Install certificate and run application +./certificate-tool add -f ${cert_filepath} -p ${cert_password} +dotnet ./CalculatorService.Orleans.dll \ No newline at end of file diff --git a/Sample/CalculatorService.Orleans/paket.references b/Sample/CalculatorService.Orleans/paket.references deleted file mode 100644 index d9b3f90f..00000000 --- a/Sample/CalculatorService.Orleans/paket.references +++ /dev/null @@ -1,5 +0,0 @@ -Ninject -Microsoft.Orleans.CodeGenerator.MsBuild -Microsoft.Orleans.Core - -# Solve binding redirect issue, related to project vs nuget references. OrleansDashboard depends on. diff --git a/Sample/CalculatorService/App.config b/Sample/CalculatorService/App.config deleted file mode 100644 index ce399b0e..00000000 --- a/Sample/CalculatorService/App.config +++ /dev/null @@ -1,17 +0,0 @@ - - - -
- - - - - - - - - - - - - diff --git a/Sample/CalculatorService/CalculatorService.cs b/Sample/CalculatorService/CalculatorService.cs index f3592864..df503df4 100644 --- a/Sample/CalculatorService/CalculatorService.cs +++ b/Sample/CalculatorService/CalculatorService.cs @@ -1,7 +1,7 @@ -using System.Threading; -using System.Threading.Tasks; -using CalculatorService.Interface; +using CalculatorService.Interface; using Gigya.ServiceContract.HttpService; +using System.Threading; +using System.Threading.Tasks; namespace CalculatorService { diff --git a/Sample/CalculatorService/CalculatorService.csproj b/Sample/CalculatorService/CalculatorService.csproj index 7d54ae08..0677168c 100644 --- a/Sample/CalculatorService/CalculatorService.csproj +++ b/Sample/CalculatorService/CalculatorService.csproj @@ -1,62 +1,24 @@  - - {5B1BA713-F5BA-466B-B79E-95261DB27FA9} - Exe - net472 - true - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - 1591 - CalculatorService - CalculatorService - Copyright © 2018 - false - bin\$(Configuration)\ - - - full - 3 - - - pdbonly - - - - ..\..\packages\System.Threading.Tasks.Dataflow\lib\netstandard1.1\System.Threading.Tasks.Dataflow.dll - False - - - - - PreserveNewest - - - - - - - - - - - - - - - - + + CalculatorService + Exe + false + true + net472;net5.0;net6.0 + Linux + + + + PreserveNewest + + + + + + + + + + \ No newline at end of file diff --git a/Sample/CalculatorService/CalculatorServiceHost.cs b/Sample/CalculatorService/CalculatorServiceHost.cs index 043d16c6..0c6fedf7 100644 --- a/Sample/CalculatorService/CalculatorServiceHost.cs +++ b/Sample/CalculatorService/CalculatorServiceHost.cs @@ -1,15 +1,10 @@ -using System; -using CalculatorService.Interface; -using Gigya.Microdot.Configuration; -using Gigya.Microdot.Hosting.Environment; -using Gigya.Microdot.Interfaces.Configuration; -using Gigya.Microdot.Interfaces.SystemWrappers; +using CalculatorService.Interface; using Gigya.Microdot.Logging.NLog; using Gigya.Microdot.Ninject; using Gigya.Microdot.Ninject.Host; using Gigya.Microdot.SharedLogic; -using Gigya.Microdot.SharedLogic.SystemWrappers; using Ninject; +using System; namespace CalculatorService { diff --git a/Sample/CalculatorService/Dockerfile b/Sample/CalculatorService/Dockerfile new file mode 100644 index 00000000..296007e7 --- /dev/null +++ b/Sample/CalculatorService/Dockerfile @@ -0,0 +1,20 @@ +#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging. + +FROM mcr.microsoft.com/dotnet/runtime:6.0 AS base +WORKDIR /app + +FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build +WORKDIR /src +COPY ["CalculatorService/CalculatorService.csproj", "CalculatorService/"] +RUN dotnet restore "CalculatorService/CalculatorService.csproj" +COPY . . + WORKDIR "/src/CalculatorService" +RUN dotnet build "CalculatorService.csproj" -c Release -o /app/build + +FROM build AS publish +RUN dotnet publish "CalculatorService.csproj" -c Release -o /app/publish + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . + ENTRYPOINT ["dotnet", "CalculatorService.dll"] \ No newline at end of file diff --git a/Sample/CalculatorService/Properties/AssemblyInfo.cs b/Sample/CalculatorService/Properties/AssemblyInfo.cs index 2999f545..9fca098f 100644 --- a/Sample/CalculatorService/Properties/AssemblyInfo.cs +++ b/Sample/CalculatorService/Properties/AssemblyInfo.cs @@ -1,6 +1,4 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from diff --git a/Sample/CalculatorService/Properties/launchSettings.json b/Sample/CalculatorService/Properties/launchSettings.json new file mode 100644 index 00000000..376591af --- /dev/null +++ b/Sample/CalculatorService/Properties/launchSettings.json @@ -0,0 +1,16 @@ +{ + "profiles": { + "CalculatorService": { + "commandName": "Project", + "commandLineArgs": "--ServiceStartupMode:CommandLineInteractive --ConsoleOutputMode:Color" + }, + "Docker": { + "commandName": "Docker", + "commandLineArgs": "--ServiceStartupMode:CommandLineInteractive --ConsoleOutputMode:Color", + "environmentVariables": { + "GIGYA_ENVVARS_FILE": "/gigya/environmentVariablesLinux.json" + }, + "DockerfileRunArguments": "-v C:\\Gigya:/gigya -p 12323:12323 -p 12324:12324 -p 12325:12325 -p 12326:12326 -p 12327:12327 -p 12328:12328 -e ENV=st11 -e DC=il1 -e region=il1 -e GIGYA_BASE_PATH=/gigya -e GIGYA_CONFIG_PATHS_FILE=/gigya/config/loadPathsWithLocal.json -e GIGYA_CONFIG_ROOT=/gigya/config -e CONSUL=consul.service.il1.gigya.io:8500 -e GIGYA_SERVICE_INSTANCE_NAME=A" + } + } +} \ No newline at end of file diff --git a/Sample/CalculatorService/paket.references b/Sample/CalculatorService/paket.references deleted file mode 100644 index bb61dec0..00000000 --- a/Sample/CalculatorService/paket.references +++ /dev/null @@ -1 +0,0 @@ -Ninject diff --git a/SolutionVersion.cs b/SolutionVersion.cs deleted file mode 100644 index dace78f3..00000000 --- a/SolutionVersion.cs +++ /dev/null @@ -1,40 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Reflection; -using System.Runtime.InteropServices; - -[assembly: AssemblyCompany("Gigya Inc.")] -[assembly: AssemblyCopyright("© 2018 Gigya Inc.")] -[assembly: AssemblyDescription("Microdot Framework")] - -[assembly: AssemblyVersion("2.3.0.0")] -[assembly: AssemblyFileVersion("2.3.0.0")] -[assembly: AssemblyInformationalVersion("2.3.0.0")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] -[assembly: CLSCompliant(false)] - diff --git a/global.json b/global.json new file mode 100644 index 00000000..32de063a --- /dev/null +++ b/global.json @@ -0,0 +1,5 @@ +{ + "sdk": { + "version": "6.0.102" + } +} \ No newline at end of file diff --git a/paket.dependencies b/paket.dependencies deleted file mode 100644 index f8f498f5..00000000 --- a/paket.dependencies +++ /dev/null @@ -1,106 +0,0 @@ -source https://api.nuget.org/v3/index.json -source http://nuget.gigya.net/nugetForVS/nuget/ - -framework: auto-detect -redirects: off -content: once -copy_content_to_output_dir: always - -# Pinning to 3.1.17 as 5.0.0+ are net5 nugets -nuget Microsoft.AspNetCore.Http.Features == 3.1.17 -nuget Microsoft.AspNetCore.Connections.Abstractions == 3.1.17 -nuget Microsoft.Extensions.Primitives == 3.1.17 -nuget Microsoft.Extensions.Configuration.Abstractions == 3.1.17 -nuget Microsoft.Extensions.Options == 3.1.17 -nuget Microsoft.Extensions.DependencyInjection.Abstractions == 3.1.17 -nuget Microsoft.Extensions.Logging == 3.1.17 -nuget Microsoft.Extensions.Logging.Abstractions == 3.1.17 -nuget Microsoft.Extensions.Configuration == 3.1.17 -nuget Microsoft.Extensions.Configuration.Binder == 3.1.17 -nuget Microsoft.Extensions.Configuration.EnvironmentVariables == 3.1.17 -nuget Microsoft.Extensions.Configuration.FileExtensions == 3.1.17 -nuget Microsoft.Extensions.DependencyInjection == 3.1.17 -nuget Microsoft.Extensions.DependencyModel == 3.1.6 -nuget Microsoft.Extensions.FileProviders.Abstractions == 3.1.17 -nuget Microsoft.Extensions.FileProviders.Physical == 3.1.17 -nuget Microsoft.Extensions.FileSystemGlobbing == 3.1.17 -nuget Microsoft.Extensions.Hosting.Abstractions == 3.1.17 -nuget Microsoft.Extensions.Logging.Configuration == 3.1.17 -nuget Microsoft.Extensions.Logging.Console == 3.1.17 -nuget Microsoft.Extensions.ObjectPool == 3.1.17 -nuget Microsoft.Extensions.Options.ConfigurationExtensions == 3.1.17 - - - -nuget Gigya.ServiceContract ~> 2.7.7 - -# .Net -# Pinning to 4.7.0 as 5.0.0+ are net5 nugets -nuget Microsoft.CSharp ~> 4.7 -nuget System.ComponentModel.Annotations ~> 4.7 -nuget System.Diagnostics.PerformanceCounter ~> 4.7 -nuget System.Runtime.Caching ~> 4.7 -nuget System.ServiceProcess.ServiceController ~> 4.7 -nuget System.Reflection.Emit ~> 4.7 -nuget System.Configuration.ConfigurationManager ~> 4.7 - -nuget System.Data.DataSetExtensions -nuget System.Net.Http -nuget System.ValueTuple - - -# -nuget Newtonsoft.Json ~> 12 -nuget Nito.AsyncEx ~> 5.0 -nuget System.Threading.Tasks.Dataflow ~> 4.0 -nuget ZooKeeperNetEx ~> 3.0 - -# Orleans -nuget Microsoft.Orleans.Core == 3.4.1 -nuget Microsoft.Orleans.OrleansRuntime == 3.4.1 -nuget Microsoft.Orleans.OrleansProviders == 3.4.1 -nuget Microsoft.Orleans.OrleansZooKeeperUtils == 3.4.1 -nuget Microsoft.Orleans.OrleansCodeGenerator == 3.4.1 -nuget Microsoft.Orleans.CodeGenerator.MSBuild == 3.4.1 -nuget Microsoft.Orleans.Client == 3.4.1 -nuget Microsoft.Orleans.OrleansTelemetryConsumers.Counters == 3.4.1 -nuget Microsoft.Orleans.Server == 3.4.1 -nuget Microsoft.Orleans.Core.Abstractions == 3.4.1 -nuget Microsoft.Orleans.Connections.Security == 3.4.1 -nuget Microsoft.Orleans.Clustering.AdoNet == 3.4.1 -nuget Microsoft.Orleans.Persistence.AdoNet == 3.4.1 -nuget Microsoft.Orleans.Reminders.AdoNet == 3.4.1 - -nuget Microsoft.Orleans.Runtime.Abstractions == 3.4.1 -nuget Microsoft.Orleans.OrleansSqlUtils ~> 2.4 - -nuget Microsoft.AspNetCore.Hosting ~> 2.2 -nuget Microsoft.AspNetCore.Server.Kestrel ~> 2.2 -nuget Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets == 2.2.1 - - - -# TODO: remove this dependency once we move to dotnet core and go back to using the original dashboard -nuget Gigya.OrleansDashboard.NetStandard ~> 3 - -nuget LibLog ~> 4.2.3 - -nuget Microsoft.CodeAnalysis.CSharp ~> 3 -nuget Microsoft.CodeAnalysis.Common ~> 3 - -# Ninject -nuget Ninject ~> 3.3 -nuget Ninject.Extensions.Factory ~> 3.3 -nuget Ninject.Extensions.Conventions ~> 3.3 -nuget Castle.Core ~> 4 - -# Tests only dependencies -nuget NUnit ~> 3 -nuget NUnit3TestAdapter ~> 3 -nuget RichardSzalay.MockHttp ~> 5 -nuget NSubstitute ~> 4 -nuget FluentAssertions ~> 5 -nuget Nuget.CommandLine ~> 5 -nuget Shouldly ~> 3 -nuget NLog ~> 4 -nuget Microsoft.NET.Test.Sdk ~> 16 diff --git a/paket.lock b/paket.lock deleted file mode 100644 index efa5ee2c..00000000 --- a/paket.lock +++ /dev/null @@ -1,795 +0,0 @@ -REDIRECTS: OFF -COPY-CONTENT-TO-OUTPUT-DIR: ALWAYS -CONTENT: ONCE -RESTRICTION: || (== net472) (== netstandard2.0) -NUGET - remote: https://api.nuget.org/v3/index.json - Castle.Core (4.4.1) - NETStandard.Library (>= 1.6.1) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Collections.Specialized (>= 4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.ComponentModel (>= 4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.ComponentModel.TypeConverter (>= 4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Diagnostics.TraceSource (>= 4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Dynamic.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Reflection (>= 4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Reflection.Emit (>= 4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Reflection.TypeExtensions (>= 4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Xml.XmlDocument (>= 4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - FluentAssertions (5.10.3) - System.Configuration.ConfigurationManager (>= 4.4) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (>= netcoreapp2.0)) (&& (== net472) (>= netcoreapp2.1)) (&& (== net472) (>= netstandard2.1)) (== netstandard2.0) - LibLog (4.2.6) - Microsoft.AspNetCore.Connections.Abstractions (3.1.17) - Microsoft.AspNetCore.Http.Features (>= 3.1.17) - Microsoft.Bcl.AsyncInterfaces (>= 1.1.1) - System.IO.Pipelines (>= 4.7.4) - Microsoft.AspNetCore.Hosting (2.2.7) - Microsoft.AspNetCore.Hosting.Abstractions (>= 2.2) - Microsoft.AspNetCore.Http (>= 2.2) - Microsoft.AspNetCore.Http.Extensions (>= 2.2) - Microsoft.Extensions.Configuration (>= 2.2) - Microsoft.Extensions.Configuration.EnvironmentVariables (>= 2.2.4) - Microsoft.Extensions.Configuration.FileExtensions (>= 2.2) - Microsoft.Extensions.DependencyInjection (>= 2.2) - Microsoft.Extensions.FileProviders.Physical (>= 2.2) - Microsoft.Extensions.Hosting.Abstractions (>= 2.2) - Microsoft.Extensions.Logging (>= 2.2) - Microsoft.Extensions.Options (>= 2.2) - System.Diagnostics.DiagnosticSource (>= 4.5.1) - System.Reflection.Metadata (>= 1.6) - Microsoft.AspNetCore.Hosting.Abstractions (2.2) - Microsoft.AspNetCore.Hosting.Server.Abstractions (>= 2.2) - Microsoft.AspNetCore.Http.Abstractions (>= 2.2) - Microsoft.Extensions.Hosting.Abstractions (>= 2.2) - Microsoft.AspNetCore.Hosting.Server.Abstractions (2.2) - Microsoft.AspNetCore.Http.Features (>= 2.2) - Microsoft.Extensions.Configuration.Abstractions (>= 2.2) - Microsoft.AspNetCore.Http (2.2.2) - Microsoft.AspNetCore.Http.Abstractions (>= 2.2) - Microsoft.AspNetCore.WebUtilities (>= 2.2) - Microsoft.Extensions.ObjectPool (>= 2.2) - Microsoft.Extensions.Options (>= 2.2) - Microsoft.Net.Http.Headers (>= 2.2) - Microsoft.AspNetCore.Http.Abstractions (2.2) - Microsoft.AspNetCore.Http.Features (>= 2.2) - System.Text.Encodings.Web (>= 4.5) - Microsoft.AspNetCore.Http.Extensions (2.2) - Microsoft.AspNetCore.Http.Abstractions (>= 2.2) - Microsoft.Extensions.FileProviders.Abstractions (>= 2.2) - Microsoft.Net.Http.Headers (>= 2.2) - System.Buffers (>= 4.5) - Microsoft.AspNetCore.Http.Features (3.1.17) - Microsoft.Extensions.Primitives (>= 3.1.17) - System.IO.Pipelines (>= 4.7.4) - Microsoft.AspNetCore.Server.Kestrel (2.2) - Microsoft.AspNetCore.Hosting (>= 2.2) - Microsoft.AspNetCore.Server.Kestrel.Core (>= 2.2) - Microsoft.AspNetCore.Server.Kestrel.Https (>= 2.2) - Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets (>= 2.2) - Microsoft.AspNetCore.Server.Kestrel.Core (2.2) - Microsoft.AspNetCore.Hosting.Abstractions (>= 2.2) - Microsoft.AspNetCore.Http (>= 2.2) - Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions (>= 2.2) - Microsoft.AspNetCore.WebUtilities (>= 2.2) - Microsoft.Extensions.Configuration.Binder (>= 2.2) - Microsoft.Extensions.Logging.Abstractions (>= 2.2) - Microsoft.Extensions.Options (>= 2.2) - Microsoft.Net.Http.Headers (>= 2.2) - System.Memory (>= 4.5.1) - System.Numerics.Vectors (>= 4.5) - System.Runtime.CompilerServices.Unsafe (>= 4.5.1) - System.Security.Cryptography.Cng (>= 4.5) - System.Threading.Tasks.Extensions (>= 4.5.1) - Microsoft.AspNetCore.Server.Kestrel.Https (2.2) - Microsoft.AspNetCore.Http.Abstractions (>= 2.2) - Microsoft.AspNetCore.Server.Kestrel.Core (>= 2.2) - Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions (2.2) - Microsoft.AspNetCore.Connections.Abstractions (>= 2.2) - Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets (2.2.1) - Microsoft.AspNetCore.Hosting.Abstractions (>= 2.2) - Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions (>= 2.2) - Microsoft.Extensions.Options (>= 2.2) - Microsoft.AspNetCore.WebUtilities (2.2) - Microsoft.Net.Http.Headers (>= 2.2) - System.Text.Encodings.Web (>= 4.5) - Microsoft.Bcl.AsyncInterfaces (5.0) - System.Threading.Tasks.Extensions (>= 4.5.4) - Microsoft.CodeAnalysis.Analyzers (3.3.2) - Microsoft.CodeAnalysis.Common (3.10) - Microsoft.CodeAnalysis.Analyzers (>= 3.3.2) - System.Collections.Immutable (>= 5.0) - System.Memory (>= 4.5.4) - System.Reflection.Metadata (>= 5.0) - System.Runtime.CompilerServices.Unsafe (>= 5.0) - System.Text.Encoding.CodePages (>= 4.5.1) - System.Threading.Tasks.Extensions (>= 4.5.4) - Microsoft.CodeAnalysis.CSharp (3.10) - Microsoft.CodeAnalysis.Common (3.10) - Microsoft.CodeCoverage (16.10) - restriction: || (== net472) (&& (== netstandard2.0) (>= net45)) (&& (== netstandard2.0) (>= netcoreapp1.0)) - Microsoft.CSharp (4.7) - Microsoft.Extensions.Configuration (3.1.17) - Microsoft.Extensions.Configuration.Abstractions (>= 3.1.17) - Microsoft.Extensions.Configuration.Abstractions (3.1.17) - Microsoft.Extensions.Primitives (>= 3.1.17) - Microsoft.Extensions.Configuration.Binder (3.1.17) - Microsoft.Extensions.Configuration (>= 3.1.17) - Microsoft.Extensions.Configuration.EnvironmentVariables (3.1.17) - Microsoft.Extensions.Configuration (>= 3.1.17) - Microsoft.Extensions.Configuration.FileExtensions (3.1.17) - Microsoft.Extensions.Configuration (>= 3.1.17) - Microsoft.Extensions.FileProviders.Physical (>= 3.1.17) - Microsoft.Extensions.DependencyInjection (3.1.17) - Microsoft.Bcl.AsyncInterfaces (>= 1.1.1) - Microsoft.Extensions.DependencyInjection.Abstractions (>= 3.1.17) - Microsoft.Extensions.DependencyInjection.Abstractions (3.1.17) - Microsoft.Extensions.DependencyModel (3.1.6) - Newtonsoft.Json (>= 9.0.1) - restriction: || (== net472) (&& (== netstandard2.0) (>= net451)) (&& (== netstandard2.0) (< netstandard1.6)) - System.Runtime.InteropServices.RuntimeInformation (>= 4.0) - restriction: || (== net472) (&& (== netstandard2.0) (>= net451)) (&& (== netstandard2.0) (< netstandard1.6)) - System.Text.Json (>= 4.7.2) - restriction: || (&& (== net472) (< net451)) (== netstandard2.0) - Microsoft.Extensions.FileProviders.Abstractions (3.1.17) - Microsoft.Extensions.Primitives (>= 3.1.17) - Microsoft.Extensions.FileProviders.Physical (3.1.17) - Microsoft.Extensions.FileProviders.Abstractions (>= 3.1.17) - Microsoft.Extensions.FileSystemGlobbing (>= 3.1.17) - Microsoft.Extensions.FileSystemGlobbing (3.1.17) - Microsoft.Extensions.Hosting.Abstractions (3.1.17) - Microsoft.Bcl.AsyncInterfaces (>= 1.1.1) - Microsoft.Extensions.Configuration.Abstractions (>= 3.1.17) - Microsoft.Extensions.DependencyInjection.Abstractions (>= 3.1.17) - Microsoft.Extensions.FileProviders.Abstractions (>= 3.1.17) - Microsoft.Extensions.Logging.Abstractions (>= 3.1.17) - Microsoft.Extensions.Logging (3.1.17) - Microsoft.Extensions.Configuration.Binder (>= 3.1.17) - Microsoft.Extensions.DependencyInjection (>= 3.1.17) - Microsoft.Extensions.Logging.Abstractions (>= 3.1.17) - Microsoft.Extensions.Options (>= 3.1.17) - Microsoft.Extensions.Logging.Abstractions (3.1.17) - Microsoft.Extensions.Logging.Configuration (3.1.17) - Microsoft.Extensions.Logging (>= 3.1.17) - Microsoft.Extensions.Options.ConfigurationExtensions (>= 3.1.17) - Microsoft.Extensions.Logging.Console (3.1.17) - Microsoft.Extensions.Configuration.Abstractions (>= 3.1.17) - Microsoft.Extensions.Logging (>= 3.1.17) - Microsoft.Extensions.Logging.Configuration (>= 3.1.17) - Microsoft.Extensions.ObjectPool (3.1.17) - Microsoft.Extensions.Options (3.1.17) - Microsoft.Extensions.DependencyInjection.Abstractions (>= 3.1.17) - Microsoft.Extensions.Primitives (>= 3.1.17) - System.ComponentModel.Annotations (>= 4.7) - Microsoft.Extensions.Options.ConfigurationExtensions (3.1.17) - Microsoft.Extensions.Configuration.Abstractions (>= 3.1.17) - Microsoft.Extensions.Configuration.Binder (>= 3.1.17) - Microsoft.Extensions.DependencyInjection.Abstractions (>= 3.1.17) - Microsoft.Extensions.Options (>= 3.1.17) - Microsoft.Extensions.Primitives (3.1.17) - System.Memory (>= 4.5.2) - System.Runtime.CompilerServices.Unsafe (>= 4.7.1) - Microsoft.Net.Http.Headers (2.2.8) - Microsoft.Extensions.Primitives (>= 2.2) - System.Buffers (>= 4.5) - Microsoft.NET.Test.Sdk (16.10) - Microsoft.CodeCoverage (>= 16.10) - restriction: || (== net472) (&& (== netstandard2.0) (>= net45)) (&& (== netstandard2.0) (>= netcoreapp1.0)) - Microsoft.NETCore.Platforms (5.0.2) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (5.0) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.Orleans.Client (3.4.1) - Microsoft.Orleans.OrleansProviders (>= 3.4.1) - Microsoft.Orleans.Clustering.AdoNet (3.4.1) - Microsoft.Orleans.OrleansProviders (>= 3.4.1) - Microsoft.Orleans.Runtime.Abstractions (>= 3.4.1) - System.Data.Common (>= 4.3) - Microsoft.Orleans.CodeGenerator.MSBuild (3.4.1) - Microsoft.Orleans.Connections.Security (3.4.1) - Microsoft.AspNetCore.Connections.Abstractions (>= 3.0) - Microsoft.Extensions.Configuration (>= 3.0) - Microsoft.Extensions.Hosting.Abstractions (>= 3.0) - Microsoft.Extensions.Logging (>= 3.0) - Microsoft.Orleans.Core (>= 3.4.1) - Microsoft.Orleans.Runtime.Abstractions (>= 3.4.1) - System.Buffers (>= 4.5) - System.Diagnostics.EventLog (>= 4.7) - System.IO.Pipelines (>= 4.7) - System.Memory (>= 4.5.3) - System.Threading.Tasks.Extensions (>= 4.5.4) - Microsoft.Orleans.Core (3.4.1) - Microsoft.AspNetCore.Connections.Abstractions (>= 3.0) - Microsoft.Bcl.AsyncInterfaces (>= 1.1.1) - Microsoft.Extensions.Configuration (>= 3.0) - Microsoft.Extensions.DependencyInjection (>= 3.0) - Microsoft.Extensions.DependencyModel (>= 3.0) - Microsoft.Extensions.Hosting.Abstractions (>= 3.0) - Microsoft.Extensions.Logging (>= 3.0) - Microsoft.Extensions.ObjectPool (>= 3.0) - Microsoft.Extensions.Options.ConfigurationExtensions (>= 3.0) - Microsoft.Orleans.Core.Abstractions (>= 3.4.1) - Newtonsoft.Json (>= 10.0.3) - System.Buffers (>= 4.5) - System.Collections.Immutable (>= 1.7) - System.Diagnostics.DiagnosticSource (>= 4.7) - System.IO.Pipelines (>= 4.7) - System.Memory (>= 4.5.3) - System.Reflection.Emit (>= 4.7) - System.Reflection.Emit.Lightweight (>= 4.7) - System.Reflection.Metadata (>= 1.8) - System.Runtime (>= 4.3.1) - System.Threading.Channels (>= 4.7) - System.ValueTuple (>= 4.5) - Microsoft.Orleans.Core.Abstractions (3.4.1) - System.Memory (>= 4.5.3) - System.Threading.Tasks.Extensions (>= 4.5.4) - Microsoft.Orleans.OrleansCodeGenerator (3.4.1) - Microsoft.CodeAnalysis.CSharp (>= 3.4) - Microsoft.Orleans.Core (>= 3.4.1) - System.Runtime (>= 4.3.1) - System.Threading.Tasks.Extensions (>= 4.5.4) - Microsoft.Orleans.OrleansProviders (3.4.1) - Microsoft.Orleans.Core (>= 3.4.1) - Microsoft.Orleans.Runtime.Abstractions (>= 3.4.1) - Microsoft.Orleans.OrleansRuntime (3.4.1) - Microsoft.AspNetCore.Connections.Abstractions (>= 3.0) - Microsoft.Extensions.Hosting.Abstractions (>= 3.0) - Microsoft.Extensions.Options (>= 3.0) - Microsoft.Orleans.Core (>= 3.4.1) - Microsoft.Orleans.Runtime.Abstractions (>= 3.4.1) - System.Buffers (>= 4.5) - System.Memory (>= 4.5.3) - System.Threading.Channels (>= 4.7) - System.Threading.Tasks.Extensions (>= 4.5.4) - Microsoft.Orleans.OrleansSQLUtils (2.4.5) - Microsoft.Orleans.Clustering.AdoNet (>= 2.4.5) - Microsoft.Orleans.OrleansProviders (>= 2.4.5) - Microsoft.Orleans.Persistence.AdoNet (>= 2.4.5) - Microsoft.Orleans.Reminders.AdoNet (>= 2.4.5) - Microsoft.Orleans.Runtime.Abstractions (>= 2.4.5) - Microsoft.Orleans.OrleansTelemetryConsumers.Counters (3.4.1) - Microsoft.Extensions.Logging.Console (>= 3.0) - Microsoft.Orleans.Core (>= 3.4.1) - Microsoft.Orleans.Runtime.Abstractions (>= 3.4.1) - System.Diagnostics.PerformanceCounter (>= 4.7) - System.Management (>= 4.7) - Microsoft.Orleans.OrleansZooKeeperUtils (3.4.1) - Microsoft.Orleans.Runtime.Abstractions (>= 3.4.1) - ZooKeeperNetEx (>= 3.4.12.1) - Microsoft.Orleans.Persistence.AdoNet (3.4.1) - Microsoft.Orleans.OrleansProviders (>= 3.4.1) - Microsoft.Orleans.Runtime.Abstractions (>= 3.4.1) - System.Data.Common (>= 4.3) - Microsoft.Orleans.Reminders.AdoNet (3.4.1) - Microsoft.Orleans.OrleansProviders (>= 3.4.1) - Microsoft.Orleans.Runtime.Abstractions (>= 3.4.1) - System.Data.Common (>= 4.3) - System.Memory (>= 4.5.3) - Microsoft.Orleans.Runtime.Abstractions (3.4.1) - Microsoft.Extensions.Hosting.Abstractions (>= 3.0) - Microsoft.Extensions.Options (>= 3.0) - Microsoft.Orleans.Core (>= 3.4.1) - Microsoft.Orleans.Server (3.4.1) - Microsoft.Orleans.OrleansProviders (>= 3.4.1) - Microsoft.Orleans.OrleansRuntime (>= 3.4.1) - NETStandard.Library (2.0.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - Newtonsoft.Json (12.0.3) - Ninject (3.3.4) - System.Reflection.Emit.ILGeneration (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Emit.Lightweight (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Ninject.Extensions.Conventions (3.3) - Ninject.Extensions.Factory (>= 3.3.2) - Ninject.Extensions.Factory (3.3.3) - Castle.Core (>= 4.2) - Ninject (>= 3.3.3) - Nito.AsyncEx (5.1) - Nito.AsyncEx.Context (>= 5.1) - Nito.AsyncEx.Coordination (>= 5.1) - Nito.AsyncEx.Interop.WaitHandles (>= 5.1) - Nito.AsyncEx.Oop (>= 5.1) - Nito.AsyncEx.Tasks (>= 5.1) - Nito.Cancellation (>= 1.1) - Nito.AsyncEx.Context (5.1) - Nito.AsyncEx.Tasks (>= 5.1) - Nito.AsyncEx.Coordination (5.1) - Nito.AsyncEx.Tasks (>= 5.1) - Nito.Collections.Deque (>= 1.1) - Nito.AsyncEx.Interop.WaitHandles (5.1) - Nito.AsyncEx.Tasks (>= 5.1) - Nito.AsyncEx.Oop (5.1) - Nito.AsyncEx.Coordination (>= 5.1) - Nito.AsyncEx.Tasks (5.1) - Nito.Disposables (>= 2.2) - Nito.Cancellation (1.1) - Nito.Disposables (>= 2.2) - Nito.Collections.Deque (1.1) - Nito.Disposables (2.2) - System.Collections.Immutable (>= 1.4) - NLog (4.7.10) - NSubstitute (4.2.2) - Castle.Core (>= 4.4) - System.Threading.Tasks.Extensions (>= 4.3) - NuGet.CommandLine (5.9.1) - NUnit (3.13.2) - NETStandard.Library (>= 2.0) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - NUnit3TestAdapter (3.17) - RichardSzalay.MockHttp (5.0) - runtime.debian.8-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.debian.9-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.fedora.23-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.fedora.24-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.fedora.27-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.fedora.28-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.native.System (4.3.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1.1) - Microsoft.NETCore.Targets (>= 1.1.3) - runtime.native.System.Net.Http (4.3.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1.1) - Microsoft.NETCore.Targets (>= 1.1.3) - runtime.native.System.Security.Cryptography.Apple (4.3.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.osx.10.10-x64.runtime.native.System.Security.Cryptography.Apple (>= 4.3.1) - runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.debian.8-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.debian.9-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.fedora.23-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.fedora.24-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.fedora.27-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.fedora.28-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.opensuse.13.2-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.opensuse.42.1-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.opensuse.42.3-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.osx.10.10-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.rhel.7-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.ubuntu.14.04-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.ubuntu.16.04-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.ubuntu.16.10-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.ubuntu.18.04-x64.runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.3) - runtime.opensuse.13.2-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.opensuse.42.1-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.opensuse.42.3-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.osx.10.10-x64.runtime.native.System.Security.Cryptography.Apple (4.3.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.osx.10.10-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.rhel.7-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.ubuntu.14.04-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.ubuntu.16.04-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.ubuntu.16.10-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.ubuntu.18.04-x64.runtime.native.System.Security.Cryptography.OpenSsl (4.3.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Shouldly (3.0.2) - Microsoft.CSharp (>= 4.3) - restriction: || (&& (== net472) (< net40)) (== netstandard2.0) - System.Dynamic.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net40)) (== netstandard2.0) - System.Reflection.TypeExtensions (>= 4.3) - restriction: || (&& (== net472) (< net40)) (== netstandard2.0) - System.Buffers (4.5.1) - System.CodeDom (5.0) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (>= netcoreapp2.0)) (== netstandard2.0) - System.Collections (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Collections.Concurrent (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Diagnostics.Debug (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Diagnostics.Tracing (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading.Tasks (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Collections.Immutable (5.0) - System.Memory (>= 4.5.4) - System.Collections.NonGeneric (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Diagnostics.Debug (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Collections.Specialized (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Collections.NonGeneric (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Globalization.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.ComponentModel (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.ComponentModel.Annotations (4.7) - System.ComponentModel.Primitives (4.3) - restriction: || (&& (== net472) (< net35)) (&& (== net472) (< netstandard1.0) (>= win8)) (&& (== net472) (>= wp8)) (&& (== net472) (>= wpa81)) (== netstandard2.0) - System.ComponentModel (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.ComponentModel.TypeConverter (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Collections.NonGeneric (>= 4.3) - System.Collections.Specialized (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.ComponentModel (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.ComponentModel.Primitives (>= 4.3) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Linq (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Primitives (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.TypeExtensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Configuration.ConfigurationManager (4.7) - System.Security.Cryptography.ProtectedData (>= 4.7) - restriction: || (&& (== net472) (< net461)) (== netstandard2.0) - System.Security.Permissions (>= 4.7) - System.Data.Common (4.3) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net451)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net451)) (== netstandard2.0) - System.IO (>= 4.3) - restriction: || (&& (== net472) (< net451)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net451)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net451)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net451)) (== netstandard2.0) - System.Text.RegularExpressions (>= 4.3) - restriction: || (&& (== net472) (< net451)) (== netstandard2.0) - System.Threading.Tasks (>= 4.3) - restriction: || (&& (== net472) (< net451)) (== netstandard2.0) - System.Data.DataSetExtensions (4.5) - System.Diagnostics.Debug (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Diagnostics.DiagnosticSource (5.0.1) - System.Memory (>= 4.5.4) - System.Runtime.CompilerServices.Unsafe (>= 5.0) - System.Diagnostics.EventLog (5.0.1) - System.Security.Principal.Windows (>= 5.0) - System.Diagnostics.PerformanceCounter (4.7) - System.Diagnostics.TraceSource (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - runtime.native.System (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Diagnostics.Debug (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Diagnostics.Tracing (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Dynamic.Runtime (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Diagnostics.Debug (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Linq (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Linq.Expressions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.ObjectModel (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Emit (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Emit.ILGeneration (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Primitives (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.TypeExtensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Globalization (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Globalization.Calendars (4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Globalization.Extensions (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.InteropServices (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.IO (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Text.Encoding (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading.Tasks (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.IO.FileSystem (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.IO (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.IO.FileSystem.Primitives (>= 4.3) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Handles (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Text.Encoding (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Threading.Tasks (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.IO.FileSystem.Primitives (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.IO.Pipelines (5.0.1) - System.Buffers (>= 4.5.1) - System.Memory (>= 4.5.4) - System.Threading.Tasks.Extensions (>= 4.5.4) - System.Linq (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Diagnostics.Debug (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Linq.Expressions (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Diagnostics.Debug (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.IO (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Linq (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.ObjectModel (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Emit (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Emit.ILGeneration (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Emit.Lightweight (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Primitives (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.TypeExtensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Management (5.0) - System.CodeDom (>= 5.0) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (>= netcoreapp2.0)) (== netstandard2.0) - System.Memory (4.5.4) - System.Buffers (>= 4.5.1) - System.Numerics.Vectors (>= 4.4) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Numerics.Vectors (>= 4.5) - restriction: || (== net472) (&& (== netstandard2.0) (>= net461)) - System.Runtime.CompilerServices.Unsafe (>= 4.5.3) - System.Net.Http (4.3.4) - Microsoft.NETCore.Platforms (>= 1.1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.native.System (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.native.System.Net.Http (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.2) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Diagnostics.Debug (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Diagnostics.DiagnosticSource (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Diagnostics.Tracing (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Globalization.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.IO (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.IO.FileSystem (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Net.Primitives (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.Handles (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.InteropServices (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Security.Cryptography.Algorithms (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Security.Cryptography.Encoding (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Security.Cryptography.OpenSsl (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Security.Cryptography.Primitives (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Security.Cryptography.X509Certificates (>= 4.3) - System.Text.Encoding (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading.Tasks (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Net.Primitives (4.3.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1.1) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (< netstandard1.1)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1.3) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (< netstandard1.1)) (== netstandard2.0) - System.Runtime (>= 4.3.1) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (< netstandard1.1)) (== netstandard2.0) - System.Runtime.Handles (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Numerics.Vectors (4.5) - System.ObjectModel (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Diagnostics.Debug (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.IO (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Primitives (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Emit (4.7) - System.Reflection.Emit.ILGeneration (>= 4.7) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (< netstandard1.1)) (&& (== net472) (< netstandard2.0) (>= wpa81)) (&& (== net472) (>= uap10.1)) (== netstandard2.0) - System.Reflection.Emit.ILGeneration (4.7) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (< netstandard1.1)) (&& (== net472) (< netstandard2.0) (>= wpa81)) (&& (== net472) (>= uap10.1)) (== netstandard2.0) - System.Reflection.Emit.Lightweight (4.7) - System.Reflection.Emit.ILGeneration (>= 4.7) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (< netstandard2.0) (>= wpa81)) (&& (== net472) (< portable-net45+wp8)) (&& (== net472) (>= uap10.1)) (== netstandard2.0) - System.Reflection.Extensions (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.Metadata (5.0) - System.Collections.Immutable (>= 5.0) - System.Reflection.Primitives (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection.TypeExtensions (4.7) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Resources.ResourceManager (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Reflection (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (4.3.1) - Microsoft.NETCore.Platforms (>= 1.1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.Caching (4.7) - System.Configuration.ConfigurationManager (>= 4.7) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.CompilerServices.Unsafe (5.0) - System.Runtime.Extensions (4.3.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.Handles (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.InteropServices (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (>= netcoreapp1.1)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (>= netcoreapp1.1)) (== netstandard2.0) - System.Reflection (>= 4.3) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (>= netcoreapp1.1)) (== netstandard2.0) - System.Reflection.Primitives (>= 4.3) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (>= netcoreapp1.1)) (== netstandard2.0) - System.Runtime (>= 4.3) - System.Runtime.Handles (>= 4.3) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (>= netcoreapp1.1)) (== netstandard2.0) - System.Runtime.InteropServices.RuntimeInformation (4.3) - restriction: || (== net472) (&& (== netstandard2.0) (>= net451)) (&& (== netstandard2.0) (< netstandard1.6)) - System.Runtime.Numerics (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Security.AccessControl (5.0) - System.Security.Principal.Windows (>= 5.0) - System.Security.Cryptography.Algorithms (4.3.1) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - runtime.native.System.Security.Cryptography.Apple (>= 4.3.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.2) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.IO (>= 4.3) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime (>= 4.3) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Handles (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.InteropServices (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Numerics (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.Encoding (>= 4.3) - System.Security.Cryptography.Primitives (>= 4.3) - System.Text.Encoding (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.Cng (5.0) - System.Security.Cryptography.Algorithms (>= 4.3.1) - restriction: || (== net472) (&& (== netstandard2.0) (>= net47)) (&& (== netstandard2.0) (< netstandard1.4)) (&& (== netstandard2.0) (< netstandard1.6)) - System.Security.Cryptography.Csp (4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.IO (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Reflection (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Handles (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.InteropServices (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.Algorithms (>= 4.3) - System.Security.Cryptography.Encoding (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.Primitives (>= 4.3) - System.Text.Encoding (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.Encoding (4.3) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Collections.Concurrent (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Linq (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Handles (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.InteropServices (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.Primitives (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Text.Encoding (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.OpenSsl (5.0) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Security.Cryptography.Primitives (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Diagnostics.Debug (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.IO (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Threading.Tasks (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.ProtectedData (5.0) - restriction: || (&& (== net472) (< net461)) (== netstandard2.0) - System.Memory (>= 4.5.4) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.X509Certificates (4.3.2) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - runtime.native.System (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - runtime.native.System.Net.Http (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - runtime.native.System.Security.Cryptography.OpenSsl (>= 4.3.2) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Diagnostics.Debug (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Globalization.Calendars (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.IO (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.IO.FileSystem (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.IO.FileSystem.Primitives (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Handles (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.InteropServices (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Numerics (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.Algorithms (>= 4.3) - System.Security.Cryptography.Cng (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.Csp (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.Encoding (>= 4.3) - System.Security.Cryptography.OpenSsl (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Cryptography.Primitives (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Text.Encoding (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Security.Permissions (5.0) - System.Security.AccessControl (>= 5.0) - System.Security.Principal.Windows (5.0) - System.ServiceProcess.ServiceController (4.7) - System.Buffers (>= 4.5) - restriction: || (&& (== net472) (>= monoandroid)) (&& (== net472) (>= monotouch)) (&& (== net472) (< net461)) (&& (== net472) (>= xamarinios)) (&& (== net472) (>= xamarinmac)) (&& (== net472) (>= xamarintvos)) (&& (== net472) (>= xamarinwatchos)) (== netstandard2.0) - System.Diagnostics.EventLog (>= 4.7) - System.Memory (>= 4.5.3) - restriction: || (&& (== net472) (< net461)) (&& (== net472) (>= netcoreapp2.0)) (&& (== net472) (>= uap10.1)) (== netstandard2.0) - System.Text.Encoding (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Text.Encoding.CodePages (5.0) - System.Runtime.CompilerServices.Unsafe (>= 5.0) - System.Text.Encoding.Extensions (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Text.Encoding (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Text.Encodings.Web (5.0.1) - System.Buffers (>= 4.5.1) - System.Memory (>= 4.5.4) - System.Text.Json (5.0.2) - restriction: || (&& (== net472) (< net451)) (== netstandard2.0) - Microsoft.Bcl.AsyncInterfaces (>= 5.0) - System.Buffers (>= 4.5.1) - System.Memory (>= 4.5.4) - System.Numerics.Vectors (>= 4.5) - System.Runtime.CompilerServices.Unsafe (>= 5.0) - System.Text.Encodings.Web (>= 5.0.1) - System.Threading.Tasks.Extensions (>= 4.5.4) - System.Text.RegularExpressions (4.3.1) - restriction: || (&& (== net472) (< net451)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3.1) - restriction: || (&& (== net472) (< net45)) (&& (== net472) (>= netcoreapp1.1)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading.Tasks (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading.Channels (5.0) - System.Threading.Tasks.Extensions (>= 4.5.4) - System.Threading.Tasks (4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Platforms (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - Microsoft.NETCore.Targets (>= 1.1) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading.Tasks.Dataflow (4.11.1) - System.Threading.Tasks.Extensions (4.5.4) - System.Runtime.CompilerServices.Unsafe (>= 4.5.3) - System.ValueTuple (4.5) - System.Xml.ReaderWriter (4.3.1) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Diagnostics.Debug (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.IO (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.IO.FileSystem (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.IO.FileSystem.Primitives (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Runtime.InteropServices (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Text.Encoding (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Text.Encoding.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Text.RegularExpressions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading.Tasks (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Threading.Tasks.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net45)) (== netstandard2.0) - System.Xml.XmlDocument (4.3) - restriction: || (&& (== net472) (< net35)) (== netstandard2.0) - System.Collections (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Diagnostics.Debug (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Globalization (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.IO (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Resources.ResourceManager (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Runtime.Extensions (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Text.Encoding (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Threading (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - System.Xml.ReaderWriter (>= 4.3) - restriction: || (&& (== net472) (< net46)) (== netstandard2.0) - ZooKeeperNetEx (3.4.12.4) - remote: http://nuget.gigya.net/nugetForVS/nuget - Gigya.OrleansDashboard.NetStandard (3.0.8) - Microsoft.AspNetCore.Hosting (>= 2.2) - Microsoft.AspNetCore.Http (>= 2.2) - Microsoft.AspNetCore.Server.Kestrel (>= 2.2) - Microsoft.Orleans.Core (>= 3.2.2) - Microsoft.Orleans.OrleansRuntime (>= 3.2.2) - System.Collections.Immutable (>= 1.7.1) - Gigya.ServiceContract (2.7.7) - Newtonsoft.Json (>= 12.0) diff --git a/test.runsettings b/test.runsettings index 5b0f540f..e11cc6dd 100644 --- a/test.runsettings +++ b/test.runsettings @@ -1,7 +1,8 @@ - - - x64 - + + + + x64 + \ No newline at end of file diff --git a/tests/Gigya.Microdot.Hosting.UnitTests/Caching/RevokeNotifier/EquatableWeakReferenceTests.cs b/tests/Gigya.Microdot.Hosting.UnitTests/Caching/RevokeNotifier/EquatableWeakReferenceTests.cs index 40dfa245..8c48e06b 100644 --- a/tests/Gigya.Microdot.Hosting.UnitTests/Caching/RevokeNotifier/EquatableWeakReferenceTests.cs +++ b/tests/Gigya.Microdot.Hosting.UnitTests/Caching/RevokeNotifier/EquatableWeakReferenceTests.cs @@ -1,5 +1,4 @@ using Gigya.Microdot.ServiceProxy.Caching.RevokeNotifier; -using NSubstitute; using NUnit.Framework; using System; using System.Collections.Concurrent; diff --git a/tests/Gigya.Microdot.Hosting.UnitTests/Caching/RevokeNotifier/RevokeContextConcurrentCollectionTests.cs b/tests/Gigya.Microdot.Hosting.UnitTests/Caching/RevokeNotifier/RevokeContextConcurrentCollectionTests.cs index 85198161..c8879194 100644 --- a/tests/Gigya.Microdot.Hosting.UnitTests/Caching/RevokeNotifier/RevokeContextConcurrentCollectionTests.cs +++ b/tests/Gigya.Microdot.Hosting.UnitTests/Caching/RevokeNotifier/RevokeContextConcurrentCollectionTests.cs @@ -1,5 +1,4 @@ using Gigya.Microdot.ServiceProxy.Caching.RevokeNotifier; -using NSubstitute; using NUnit.Framework; using System; using System.Collections.Concurrent; diff --git a/tests/Gigya.Microdot.Hosting.UnitTests/Caching/RevokeNotifier/RevokeNotifierTests.cs b/tests/Gigya.Microdot.Hosting.UnitTests/Caching/RevokeNotifier/RevokeNotifierTests.cs index f4e45208..8c8c681d 100644 --- a/tests/Gigya.Microdot.Hosting.UnitTests/Caching/RevokeNotifier/RevokeNotifierTests.cs +++ b/tests/Gigya.Microdot.Hosting.UnitTests/Caching/RevokeNotifier/RevokeNotifierTests.cs @@ -1,19 +1,15 @@ -using Gigya.Microdot.Interfaces.Logging; -using Gigya.Microdot.ServiceProxy.Caching.RevokeNotifier; -using Metrics; -using NSubstitute; -using NUnit.Framework; -using System; -using System.ServiceModel; -using System.Threading; -using System.Threading.Tasks; -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; +using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Ninject; using Gigya.Microdot.ServiceProxy.Caching; +using Gigya.Microdot.ServiceProxy.Caching.RevokeNotifier; using Gigya.Microdot.UnitTests.Caching; using Ninject; -using Ninject.Extensions.Factory; using Ninject.Parameters; +using NSubstitute; +using NUnit.Framework; +using System; +using System.Threading; namespace Gigya.Microdot.Hosting.UnitTests.Caching.RevokeNotifier { diff --git a/tests/Gigya.Microdot.Hosting.UnitTests/Gigya.Microdot.Hosting.UnitTests.csproj b/tests/Gigya.Microdot.Hosting.UnitTests/Gigya.Microdot.Hosting.UnitTests.csproj index 967a3e4c..aad74bf5 100644 --- a/tests/Gigya.Microdot.Hosting.UnitTests/Gigya.Microdot.Hosting.UnitTests.csproj +++ b/tests/Gigya.Microdot.Hosting.UnitTests/Gigya.Microdot.Hosting.UnitTests.csproj @@ -1,34 +1,22 @@  - - net472 - true - true - 1591 - Gigya.Microdot.Orleans.Hosting.FunctionalTests - Gigya.Microdot.Orleans.Hosting.FunctionalTests - Copyright © 2017 - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - + + Gigya.Microdot.Orleans.Hosting.FunctionalTests + false + net472;net5.0;net6.0 + + + + + + + + + + + + + PreserveNewest + + \ No newline at end of file diff --git a/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/CalculatorServiceHost.cs b/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/CalculatorServiceHost.cs index dec55e30..9dac64ef 100644 --- a/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/CalculatorServiceHost.cs +++ b/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/CalculatorServiceHost.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using Gigya.Microdot.Common.Tests; using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Hosting.Validators; @@ -8,12 +7,12 @@ using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.HttpService; using Ninject; +using System.Collections.Generic; namespace Gigya.Microdot.Hosting.UnitTests.NonOrleansMicroService { public class CalculatorServiceHost : MicrodotServiceHost { - public IKernel Kernel; private readonly HostEnvironment environment; public override string ServiceName => "ICalculatorService"; diff --git a/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/ClientCallEventTests.cs b/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/ClientCallEventTests.cs index 25d0d326..4d8c1eb8 100644 --- a/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/ClientCallEventTests.cs +++ b/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/ClientCallEventTests.cs @@ -1,16 +1,4 @@ -using System; -using System.Linq; -using Gigya.Microdot.SharedLogic.Events; -using NUnit.Framework; -using System.Threading.Tasks; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Events; -using Gigya.Microdot.Hosting.UnitTests.NonOrleansMicroService; -using Gigya.Microdot.Interfaces.Events; -using Gigya.Microdot.Testing.Shared.Service; -using Ninject; - -namespace Gigya.Common.OrleansInfra.FunctionalTests.Events +namespace Gigya.Common.OrleansInfra.FunctionalTests.Events {/* [TestFixture, Parallelizable(ParallelScope.Fixtures)] public class ClientCallEventTests diff --git a/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/ICalculatorService.cs b/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/ICalculatorService.cs index 0f512c87..a67f1d9a 100644 --- a/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/ICalculatorService.cs +++ b/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/ICalculatorService.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Threading.Tasks; using Gigya.Common.Contracts.HttpService; +using System.Threading.Tasks; namespace Gigya.Microdot.Hosting.UnitTests.NonOrleansMicroService { diff --git a/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/MicroServiceTests.cs b/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/MicroServiceTests.cs index 6f892753..aadabb78 100644 --- a/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/MicroServiceTests.cs +++ b/tests/Gigya.Microdot.Hosting.UnitTests/NonOrleansMicroService/MicroServiceTests.cs @@ -1,7 +1,5 @@ -using Gigya.Microdot.Common.Tests; using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Hosting.Metrics; -using Gigya.Microdot.Ninject.Host; using Gigya.Microdot.SharedLogic; using NUnit.Framework; using Shouldly; diff --git a/tests/Gigya.Microdot.Hosting.UnitTests/Properties/AssemblyInfo.cs b/tests/Gigya.Microdot.Hosting.UnitTests/Properties/AssemblyInfo.cs index a2e3daf0..1728db55 100644 --- a/tests/Gigya.Microdot.Hosting.UnitTests/Properties/AssemblyInfo.cs +++ b/tests/Gigya.Microdot.Hosting.UnitTests/Properties/AssemblyInfo.cs @@ -20,7 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System.Reflection; using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible diff --git a/tests/Gigya.Microdot.Hosting.UnitTests/ServerCallEventTests.cs b/tests/Gigya.Microdot.Hosting.UnitTests/ServerCallEventTests.cs index e82f0b50..4e0bda00 100644 --- a/tests/Gigya.Microdot.Hosting.UnitTests/ServerCallEventTests.cs +++ b/tests/Gigya.Microdot.Hosting.UnitTests/ServerCallEventTests.cs @@ -1,20 +1,19 @@ -using System; -using System.Linq; -using Gigya.Microdot.SharedLogic.Events; -using NUnit.Framework; -using System.Threading.Tasks; using Gigya.Microdot.Common.Tests; using Gigya.Microdot.Hosting.Events; using Gigya.Microdot.Hosting.UnitTests.NonOrleansMicroService; using Gigya.Microdot.Interfaces.Events; +using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.HttpService; using Gigya.Microdot.Testing.Shared.Service; using Ninject; -using Gigya.Microdot.Hosting.Environment; +using NUnit.Framework; +using System; +using System.Linq; +using System.Threading.Tasks; namespace Gigya.Common.OrleansInfra.FunctionalTests.Events { - [TestFixture, Parallelizable(ParallelScope.Fixtures)] + [TestFixture, NonParallelizable] public class ServerCallEventTests { private const int REPEAT = 1; @@ -26,14 +25,6 @@ public class ServerCallEventTests [OneTimeSetUp] public void TestFixtureSetUp() { - //Environment.SetEnvironmentVariable("ZONE", "zone"); - //Environment.SetEnvironmentVariable("ENV", "env"); - - var config = new HostEnvironment(new TestHostEnvironmentSource( - zone: "zone", - deploymentEnvironment: "env", - appName: "ICalculatorService")); - _serviceTester = new NonOrleansServiceTester(); _serviceTester.CommunicationKernel.Rebind().To(); @@ -46,14 +37,10 @@ public void TestFixtureSetUp() [OneTimeTearDown] public void TestFixtureTearDown() { - _serviceTester?.Dispose(); - - //Environment.SetEnvironmentVariable("ZONE", null); - //Environment.SetEnvironmentVariable("ENV", null); + _serviceTester?.Dispose(); } [Test] - [Repeat(REPEAT)] public async Task SingleServerCall_CallSucceeds_PublishesEvent() { _flumeQueue.Clear(); @@ -71,55 +58,6 @@ public async Task SingleServerCall_CallSucceeds_PublishesEvent() Assert.AreEqual(nameof(ICalculatorService), serverReq.ServiceName); Assert.AreEqual("Add", serverReq.ServiceMethod); Assert.AreEqual(requestId, serverReq.RequestId); - } - - /* - [Test] - [Repeat(REPEAT)] - public async Task SingleServerCall_CallSucceeds_PublishesEvent_WithTags() - { - _flumeQueue.Clear(); - - var requestId = nameof(SingleServerCall_CallSucceeds_PublishesEvent_WithTags) + Guid.NewGuid(); - - TracingContext.SetRequestID(requestId); - TracingContext.TryGetRequestID(); - - using (var tag = TracingContext.Tags.TagUnencrypted("outsideOfScope", "IAmTag", true)) - { - - } - - - using (var tag = TracingContext.Tags.TagUnencrypted("scopedTag", "IAmTag", true)) - { - TracingContext.Tags.TagUnencrypted("int", 1, true); - TracingContext.Tags.TagUnencrypted("encrypted", "IAmEncryptedTag", encryptedLog: true); - await _serviceProxy.Add(5, 3); - } - - await Task.Delay(100); - - - var events = _flumeQueue.Events; - var serverReq = (ServiceCallEvent)events.Single(); - - Assert.Multiple(() => - { - var tags = serverReq.ContextTags.ToDictionary(x => x.Key, x => x.Value); - var encryptedTags = serverReq.ContextTagsEncrypted.ToDictionary(x => x.Key, x => x.Value); - - CollectionAssert.DoesNotContain(tags.Keys, "outsideOfScope"); - CollectionAssert.Contains(tags.Keys, "scopedTag"); - CollectionAssert.Contains(tags.Keys, "int"); - CollectionAssert.Contains(encryptedTags.Keys, "encrypted"); - - Assert.AreEqual("IAmTag", tags["scopedTag"]); - Assert.AreEqual(1, tags["int"]); - Assert.AreEqual("IAmEncryptedTag", encryptedTags["encrypted"]); - - }); - - }*/ + } } } \ No newline at end of file diff --git a/tests/Gigya.Microdot.Hosting.UnitTests/app.config b/tests/Gigya.Microdot.Hosting.UnitTests/app.config deleted file mode 100644 index e23fc2a3..00000000 --- a/tests/Gigya.Microdot.Hosting.UnitTests/app.config +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - True - - - - diff --git a/tests/Gigya.Microdot.Hosting.UnitTests/paket.references b/tests/Gigya.Microdot.Hosting.UnitTests/paket.references deleted file mode 100644 index d0466305..00000000 --- a/tests/Gigya.Microdot.Hosting.UnitTests/paket.references +++ /dev/null @@ -1,19 +0,0 @@ -Gigya.ServiceContract -Microsoft.Extensions.DependencyInjection -Microsoft.Orleans.OrleansCodeGenerator -Microsoft.Orleans.CodeGenerator.MsBuild -NSubstitute -NUnit -NUnit3TestAdapter -Ninject -Shouldly -Castle.Core -ZooKeeperNetEx -System.Threading.Tasks.Dataflow -Microsoft.AspNetCore.Hosting # Solve binding redirect issue, related to project vs nuget references. OrleansDashboard depends on. -Microsoft.CSharp -System.Net.Http -Microsoft.NET.Test.Sdk - -# Remove after the transition to netcore completed -System.ServiceProcess.ServiceController \ No newline at end of file diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/CalculatorServiceTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/CalculatorServiceTests.cs index d61cf27e..bfc467f7 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/CalculatorServiceTests.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/CalculatorServiceTests.cs @@ -23,12 +23,9 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Net; using System.Threading.Tasks; using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Interfaces; -using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.Ninject; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; @@ -40,7 +37,6 @@ using Gigya.ServiceContract.Attributes; using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using Ninject; using NUnit.Framework; using Shouldly; @@ -373,13 +369,6 @@ public async Task LogGrainId() await Service.LogGrainId(); } - [Test,Ignore("This silo need to run on separate app domain from nunit it should set default before any Regex is called")] - public async Task RegexTestWithTimeout() - { - //This silo need to run on separate app domain from nunit it should set default before any Regex is called - await Service.RegexTestWithDefaultTimeoutDefault(10); - } - #region MockData public class Person { diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Gigya.Microdot.Orleans.Hosting.UnitTests.csproj b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Gigya.Microdot.Orleans.Hosting.UnitTests.csproj index 093874ac..706cb53d 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Gigya.Microdot.Orleans.Hosting.UnitTests.csproj +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Gigya.Microdot.Orleans.Hosting.UnitTests.csproj @@ -1,36 +1,25 @@  - - net472 - true - true - Gigya.Microdot.Orleans.Hosting.FunctionalTests - Copyright © 2017 - $(SolutionDir)main.ruleset - - - - - - - - - - - - - - - - - - - - - - - PreserveNewest - - - + + Gigya.Microdot.Orleans.Hosting.FunctionalTests + false + net472;net5.0;net6.0 + + + + PreserveNewest + + + + + + + + + + + + + + \ No newline at end of file diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/GrainAgeLimitServiceTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/GrainAgeLimitServiceTests.cs deleted file mode 100644 index fa951a4b..00000000 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/GrainAgeLimitServiceTests.cs +++ /dev/null @@ -1,52 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Threading.Tasks; -using NUnit.Framework; - -namespace Gigya.Microdot.Orleans.Hosting.UnitTests -{ - [TestFixture,Parallelizable(ParallelScope.Fixtures)] - public class GrainAgeLimitServiceTests - { - - //TODO - [Ignore("should be implement ")] - [Test] - public async Task WithNoneAgeLimitTest() - { - //should test builder to our config - } - [Ignore("should be implement ")] - - [Test] - public async Task WithAgeLimitTest() - { - - } - - - - } -} - diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/GrainCallEventTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/GrainCallEventTests.cs index 1c460873..0be6cdd2 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/GrainCallEventTests.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/GrainCallEventTests.cs @@ -9,11 +9,10 @@ using Gigya.Microdot.Orleans.Hosting.Events; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; using Ninject; -using Gigya.Microdot.Hosting.Environment; namespace Gigya.Common.OrleansInfra.FunctionalTests.Events { - [TestFixture, Parallelizable(ParallelScope.Fixtures)] + [TestFixture, NonParallelizable] public class GrainCallEventTests { private const int REPEAT = 1; diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/HealthCheckTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/HealthCheckTests.cs index f8036fd4..4a18cf02 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/HealthCheckTests.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/HealthCheckTests.cs @@ -24,8 +24,6 @@ using System.Net; using System.Net.Http; using System.Threading.Tasks; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; using Gigya.Microdot.SharedLogic; @@ -36,11 +34,11 @@ namespace Gigya.Microdot.Orleans.Hosting.UnitTests { - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + [TestFixture, Parallelizable(ParallelScope.Fixtures)] public class HealthCheckTests { private ServiceTester _tester; - private int BasePort => _tester.Host.Arguments.BasePortOverride.Value; + private int BasePort => _tester.Host.Arguments.BasePortOverride ?? 0; [OneTimeSetUp] public void SetUp() @@ -51,51 +49,65 @@ public void SetUp() [OneTimeTearDown] public void TearDown() { - _tester.Dispose(); + try + { + _tester.Dispose(); + } + catch (Exception ex) + { + Console.WriteLine(ex); + } } [Test] - public async Task HealthCheck_ServcieDrain_StatueShouldBe521() + public async Task HealthCheck_ServiceDrain_StatueShouldBe521() { - int port = DisposablePort.GetPort().Port; - - //serviceDrainTimeSec: + int port = DisposablePort.GetPort().Port; + + //serviceDrainTimeSec: var serviceArguments = new ServiceArguments(ServiceStartupMode.CommandLineNonInteractive, ConsoleOutputMode.Disabled, - SiloClusterMode.PrimaryNode, port, serviceDrainTimeSec: 1, instanceName: "test", initTimeOutSec: 10); + SiloClusterMode.PrimaryNode, port, serviceDrainTimeSec: 10, instanceName: "test", initTimeOutSec: 10, onStopWaitTimeSec: 30); - var customServiceTester = new ServiceTester( - serviceArguments: serviceArguments); + var customServiceTester = new ServiceTester(serviceArguments); var dispose = Task.Run(() => customServiceTester.Dispose()); await Task.Delay(200); var httpResponseMessage = await new HttpClient().GetAsync(new Uri($"http://{CurrentApplicationInfo.HostName}:{port}/{nameof(IProgrammableHealth).Substring(1)}.status")); httpResponseMessage.StatusCode.ShouldBe((HttpStatusCode)521); - await dispose; + try + { + await dispose; + } + catch (Exception e) + { + Console.WriteLine(e); + } + } [Test] - public void HealthCheck_NotHealthy_ShouldReturn500() + public async Task HealthCheck_NotHealthy_ShouldReturn500() { - _tester.GrainClient.GetGrain(0).SetHealth(false); - var httpResponseMessage = new HttpClient().GetAsync(new Uri($"http://{CurrentApplicationInfo.HostName}:{BasePort}/{nameof(IProgrammableHealth).Substring(1)}.status")).Result; + await _tester.GrainClient.GetGrain(0).SetHealth(false); + var httpResponseMessage = await new HttpClient().GetAsync(new Uri($"http://{CurrentApplicationInfo.HostName}:{BasePort}/{nameof(IProgrammableHealth).Substring(1)}.status")); httpResponseMessage.StatusCode.ShouldBe(HttpStatusCode.InternalServerError); } [Test] - public void HealthCheck_Healthy_ShouldReturn200() + public async Task HealthCheck_Healthy_ShouldReturn200() { - _tester.GrainClient.GetGrain(0).SetHealth(true); - var httpResponseMessage = new HttpClient().GetAsync(new Uri($"http://{CurrentApplicationInfo.HostName}:{BasePort}/{nameof(IProgrammableHealth).Substring(1)}.status")).Result; + await _tester.GrainClient.GetGrain(0).SetHealth(true); + var httpResponseMessage = await new HttpClient().GetAsync(new Uri($"http://{CurrentApplicationInfo.HostName}:{BasePort}/{nameof(IProgrammableHealth).Substring(1)}.status")); httpResponseMessage.StatusCode.ShouldBe(HttpStatusCode.OK); } [Test] - public void HealthCheck_NotImplemented_ShouldReturn200() + public async Task HealthCheck_NotImplemented_ShouldReturn200() { - var httpResponseMessage = new HttpClient().GetAsync(new Uri($"http://{CurrentApplicationInfo.HostName}:{BasePort}/{nameof(ICalculatorService).Substring(1)}.status")).Result; + var httpResponseMessage = await new HttpClient().GetAsync(new Uri($"http://{CurrentApplicationInfo.HostName}:{BasePort}/{nameof(ICalculatorService).Substring(1)}.status")); httpResponseMessage.StatusCode.ShouldBe(HttpStatusCode.OK); httpResponseMessage.Content.ShouldNotBeNull(); } diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/HostTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/HostTests.cs index 4f4d7d7d..6b678136 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/HostTests.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/HostTests.cs @@ -16,31 +16,36 @@ using Gigya.Microdot.Interfaces.SystemWrappers; namespace Gigya.Microdot.Orleans.Hosting.UnitTests -{ - [TestFixture,Parallelizable(ParallelScope.Fixtures)] - internal class HostTests - { - private static int _counter = 0; - - [Test, Repeat(5)] - public void HostShouldStartAndStopMultipleTimes() - { - _counter++; - Stopwatch sw = Stopwatch.StartNew(); - Console.WriteLine($"-----------------------------Start run {_counter} time---------------"); - try - { - var host = new ServiceTester(); - host.GetServiceProxy(); - Console.WriteLine($"-----------------------------Silo Is running {_counter} time took, {sw.ElapsedMilliseconds}ms---------------"); - host.Dispose(); - } - finally - { - Console.WriteLine( - $"-----------------------------End run {_counter} time, took {sw.ElapsedMilliseconds}ms ---------------"); - } - } +{ + [TestFixture, Parallelizable(ParallelScope.Fixtures)] + internal class HostTests + { + private static int _counter; + + [Test, Repeat(5)] + public void HostShouldStartAndStopMultipleTimes() + { + _counter++; + Stopwatch sw = Stopwatch.StartNew(); + Console.WriteLine($"-----------------------------Start run {_counter} time---------------"); + try + { + var host = new ServiceTester(); + host.GetServiceProxy(); + Console.WriteLine( + $"-----------------------------Silo Is running {_counter} time took, {sw.ElapsedMilliseconds}ms---------------"); + host.Dispose(); + } + catch (Exception ex) + { + Console.WriteLine(ex); + } + finally + { + Console.WriteLine( + $"-----------------------------End run {_counter} time, took {sw.ElapsedMilliseconds}ms ---------------"); + } + } } internal class TestHost : MicrodotOrleansServiceHost @@ -52,13 +57,13 @@ public override ILoggingModule GetLoggingModule() return new FakesLoggersModules(); } - protected override void PreConfigure(IKernel kernel, ServiceArguments Arguments) + protected override void PreConfigure(IKernel kernel, ServiceArguments arguments) { var env = new HostEnvironment(new TestHostEnvironmentSource()); kernel.Rebind().ToConstant(env).InSingletonScope(); kernel.Rebind().ToConstant(env.ApplicationInfo).InSingletonScope(); - base.PreConfigure(kernel, Arguments); + base.PreConfigure(kernel, arguments); Console.WriteLine($"-----------------------------Silo is RebindForTests"); kernel.Rebind().To().InSingletonScope(); kernel.Rebind().To().InSingletonScope(); diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/CalculatorServiceGrain.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/CalculatorServiceGrain.cs index 0549e734..32fe7c05 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/CalculatorServiceGrain.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/CalculatorServiceGrain.cs @@ -130,7 +130,7 @@ public Task> GetVersion(string id) public Task LogData(string message) { _log.Warn(x => x(message)); - return TaskDone.Done; + return Task.CompletedTask; } public Task LogPram(string sensitive, string notSensitive, string notExists, string @default) diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/CalculatorServiceHost.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/CalculatorServiceHost.cs index 4efa27f7..b24ca3fd 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/CalculatorServiceHost.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/CalculatorServiceHost.cs @@ -46,9 +46,7 @@ public override ILoggingModule GetLoggingModule() { return new FakesLoggersModules(); } - - public IKernel Kernel; - + protected override void PreConfigure(IKernel kernel, ServiceArguments Arguments) { var env = new HostEnvironment(new TestHostEnvironmentSource()); diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/IGarinAgeLimitService.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/IGarinAgeLimitService.cs index 6590f355..e6b6d3d5 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/IGarinAgeLimitService.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/CalculatorService/IGarinAgeLimitService.cs @@ -21,11 +21,8 @@ #endregion -using System; -using System.Diagnostics; using System.Threading.Tasks; using Gigya.Common.Contracts.HttpService; -using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.Logging; using Orleans; using Orleans.Concurrency; diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/GCEndpointTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/GCEndpointTests.cs new file mode 100644 index 00000000..246ea4ca --- /dev/null +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/GCEndpointTests.cs @@ -0,0 +1,649 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using Gigya.Microdot.Fakes; +using Gigya.Microdot.Hosting.HttpService.Endpoints.GCEndpoint; +using Gigya.Microdot.Hosting.Service; +using Gigya.Microdot.Interfaces.Logging; +using Gigya.Microdot.Interfaces.SystemWrappers; +using Newtonsoft.Json; +using NSubstitute; +using NSubstitute.ClearExtensions; +using NUnit.Framework; + +namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice +{ + [TestFixture] + [NonParallelizable] + public class GCEndpointTests + { + private IGCEndpointHandler _gcEndpointHandler; + private ILog _logger; + private IDateTime _dateTime; + private IGCEndpointHandlerUtils _gcEndpointHandlerUtils; + private IGCTokenContainer _gcTokenContainer; + + [OneTimeSetUp] + public void OneTimeSetup() + { + _gcEndpointHandler = Substitute.For(); + _logger = Substitute.For(); + _dateTime = Substitute.For(); + _gcEndpointHandlerUtils = Substitute.For(); + _gcTokenContainer = Substitute.For(); + } + + [SetUp] + public void Setup() + { + _gcEndpointHandler.ClearSubstitute(); + _logger.ClearSubstitute(); + _dateTime.ClearSubstitute(); + _gcEndpointHandlerUtils.ClearSubstitute(); + _gcEndpointHandlerUtils.ClearSubstitute(); + } + + [Test] + public async Task HandledGcEndpointTest() + { + var gcCollectionResult = new GCCollectionResult(100, 10, 55); + var gcHandlingResult = + new GCHandlingResult(true, "foo bar", gcCollectionResult); + + _gcEndpointHandler + .Handle(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromResult(gcHandlingResult)); + + var responses = new List<(string, HttpStatusCode, string)>(); + + var gcEndpoint = new GCCustomEndpoint(_gcEndpointHandler); + var tryHandleResult = await gcEndpoint.TryHandle(null, async (data, status, type) => responses.Add((data, status, type))); + + var receivedCalls = _gcEndpointHandler + .Received(1) + .Handle(Arg.Any(), Arg.Any(), Arg.Any()); + + Assert.AreEqual(true, tryHandleResult); + Assert.AreEqual(1, responses.Count()); + + var deserializedResult = JsonConvert.DeserializeObject(responses.First().Item1); + Assert.AreEqual(gcHandlingResult.Message, deserializedResult.Message); + Assert.AreEqual(gcHandlingResult.GcCollectionResult.TotalMemoryAfterGC, deserializedResult.GcCollectionResult.TotalMemoryAfterGC); + Assert.AreEqual(gcHandlingResult.GcCollectionResult.TotalMemoryBeforeGC, deserializedResult.GcCollectionResult.TotalMemoryBeforeGC); + } + + [Test] + public async Task NotHandledGcEndpointTest() + { + _gcEndpointHandler + .Handle(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Task.FromResult(new GCHandlingResult(false))); + + var responses = new List<(string, HttpStatusCode, string)>(); + + var gcEndpoint = new GCCustomEndpoint(_gcEndpointHandler); + var tryHandleResult = await gcEndpoint.TryHandle(null, async (data, status, type) => responses.Add((data, status, type))); + + var receivedCalls = _gcEndpointHandler + .Received(1) + .Handle(Arg.Any(), Arg.Any(), Arg.Any()); + + Assert.AreEqual(false, tryHandleResult); + Assert.AreEqual(0, responses.Count()); + } + + [Test] + public async Task GCEndpointHandlerTest_Config_Off_Matching_Path() + { + var gcEndpointHandler = new GCEndpointHandler(() => new MicrodotHostingConfig() + { + GCEndpointEnabled = false + }, _logger, _gcEndpointHandlerUtils); + + var gcHandlingResult = await gcEndpointHandler + .Handle(new Uri("http://my-host-name/force-traffic-affecting-gc"), new NameValueCollection() + { + { "gcType", "gen0" } + },IPAddress.Parse("20.30.40.50")); + + Assert.IsFalse(gcHandlingResult.Successful); + Assert.IsNull(gcHandlingResult.Message); + Assert.IsNull(gcHandlingResult.GcCollectionResult); + } + + [Test] + public async Task GCEndpointHandlerTest_Config_On_Not_Matching_Path() + { + var gcEndpointHandler = new GCEndpointHandler(() => new MicrodotHostingConfig() + { + GCEndpointEnabled = true + }, + _logger, _gcEndpointHandlerUtils); + + var gcHandlingResult = await gcEndpointHandler + .Handle(new Uri("http://my-host-name/not-matching-path"), new NameValueCollection() + { + { "gcType", "someGcType" } + },IPAddress.Parse("20.30.40.50")); + + Assert.IsFalse(gcHandlingResult.Successful); + Assert.IsNull(gcHandlingResult.Message); + Assert.IsNull(gcHandlingResult.GcCollectionResult); + } + + [Test] + public async Task GCEndpointHandlerTest_Config_On_Token_Generation_Failed() + { + var expectedMessage = "Some Token Generation Failed Message"; + _gcEndpointHandlerUtils.TryProcessAsTokenGenerationRequest( + Arg.Any(), + Arg.Any(), + out Arg.Any()) + .Returns(x => + { + x[2] = expectedMessage; + return false; + }); + + var gcEndpointHandler = new GCEndpointHandler(() => new MicrodotHostingConfig() + { + GCEndpointEnabled = true + }, _logger, _gcEndpointHandlerUtils); + + var gcHandlingResult = await gcEndpointHandler + .Handle( + new Uri("http://my-host-name/force-traffic-affecting-gc"), + new NameValueCollection(), + IPAddress.Parse("20.30.40.50")); + + Assert.IsTrue(gcHandlingResult.Successful); + Assert.AreEqual(expectedMessage,gcHandlingResult.Message); + Assert.IsNull(gcHandlingResult.GcCollectionResult); + } + + [Test] + public async Task GCEndpointHandlerTest_Config_On_Token_Validation_Failed() + { + var expectedMessage = "Some Token Validation Failed Message"; + _gcEndpointHandlerUtils.TryProcessAsTokenGenerationRequest( + Arg.Any(), + Arg.Any(), + out Arg.Any()) + .Returns(false); + + _gcEndpointHandlerUtils.ValidateToken(Arg.Any(), + out Arg.Any()).Returns(x => + { + x[1] = expectedMessage; + return false; + }); + + var gcEndpointHandler = new GCEndpointHandler(() => new MicrodotHostingConfig() + { + GCEndpointEnabled = true + }, _logger, _gcEndpointHandlerUtils); + + var gcHandlingResult = await gcEndpointHandler + .Handle(new Uri("http://my-host-name/force-traffic-affecting-gc"), + new NameValueCollection(), + IPAddress.Parse("20.30.40.50")); + + Assert.IsTrue(gcHandlingResult.Successful); + Assert.AreEqual(expectedMessage,gcHandlingResult.Message); + Assert.IsNull(gcHandlingResult.GcCollectionResult); + } + + [Test] + public async Task GCEndpointHandlerTest_Config_On_GcType_Validation_Failed() + { + var expectedMessage = "Some GcType Validation Failed Message"; + + _gcEndpointHandlerUtils.TryProcessAsTokenGenerationRequest(Arg.Any(), + Arg.Any(), + out Arg.Any()).Returns(false); + + _gcEndpointHandlerUtils.ValidateGcType( + Arg.Any(), + out Arg.Any(), + out Arg.Any()) + .Returns(x => + { + x[1] = expectedMessage; + return false; + }); + + _gcEndpointHandlerUtils.ValidateToken(Arg.Any(), + out Arg.Any()).Returns(true); + + var gcEndpointHandler = new GCEndpointHandler(() => new MicrodotHostingConfig() + { + GCEndpointEnabled = true + }, _logger, _gcEndpointHandlerUtils); + + var gcHandlingResult = await gcEndpointHandler + .Handle( + new Uri("http://my-host-name/force-traffic-affecting-gc"), + new NameValueCollection(), + IPAddress.Parse("20.30.40.50")); + + Assert.IsTrue(gcHandlingResult.Successful); + Assert.AreEqual(expectedMessage,gcHandlingResult.Message); + Assert.IsNull(gcHandlingResult.GcCollectionResult); + } + + [Test] + public async Task GCTokenHandlerTest_No_GcType() + { + var gcTokenHandler = + new GCEndpointHandlerUtils( + () => new MicrodotHostingConfig(), + _logger, + _dateTime, + _gcTokenContainer); + + var validationResult = + gcTokenHandler.ValidateGcType( + new NameValueCollection(), + out var additionalInfo, + out var gcType); + + Assert.IsFalse(validationResult); + Assert.AreEqual("GCEndpoint called with unsupported GCType", additionalInfo); + } + + [Test] + public async Task GCTokenHandlerTest_Wrong_GcType() + { + var gcTokenHandler = + new GCEndpointHandlerUtils( + () => new MicrodotHostingConfig(), + _logger, + _dateTime, + _gcTokenContainer); + + var nameValueCollection = new NameValueCollection(); + nameValueCollection.Add("gcType", "fooBar"); + + var validationResult = + gcTokenHandler.ValidateGcType( + nameValueCollection, + out var additionalInfo, + out var gcType); + + Assert.IsFalse(validationResult); + Assert.AreEqual("GCEndpoint called with unsupported GCType", additionalInfo); + } + + [Test] + [TestCase("Gen0")] + [TestCase("Gen1")] + [TestCase("Gen2")] + [TestCase("LOHCompaction")] + [TestCase("BlockingLohCompaction")] + public async Task GCTokenHandlerTest_Valid_GcType(string gcTypeString) + { + var gcTokenHandler = + new GCEndpointHandlerUtils( + () => new MicrodotHostingConfig(), + _logger, + _dateTime, + _gcTokenContainer); + + var nameValueCollection = new NameValueCollection(); + nameValueCollection.Add("gcType", gcTypeString); + + var validationResult = + gcTokenHandler.ValidateGcType( + nameValueCollection, + out var additionalInfo, + out var gcType); + + Assert.IsTrue(validationResult); + Assert.AreEqual(gcType, Enum.Parse(typeof(GCType),gcTypeString)); + } + + [Test] + public async Task GCTokenHandlerTest_ValidateToken_No_Param() + { + var gcTokenHandler = + new GCEndpointHandlerUtils( + () => new MicrodotHostingConfig(), + _logger, + _dateTime, + _gcTokenContainer); + + var nameValueCollection = new NameValueCollection(); + + + var validateTokenResult = + gcTokenHandler.ValidateToken( + nameValueCollection, + out var additionalInfo); + + Assert.IsFalse(validateTokenResult); + Assert.AreEqual("Illegal request", additionalInfo); + } + + [Test] + public async Task GCTokenHandlerTest_ValidateToken_UnrecognizedToken() + { + var gcTokenHandler = + new GCEndpointHandlerUtils( + () => new MicrodotHostingConfig(), + _logger, + _dateTime, + _gcTokenContainer); + + var nameValueCollection = new NameValueCollection(); + nameValueCollection.Add("token", Guid.NewGuid().ToString()); + + var validateTokenResult = + gcTokenHandler.ValidateToken( + nameValueCollection, + out var additionalInfo); + + Assert.IsFalse(validateTokenResult); + Assert.AreEqual("Illegal request", additionalInfo); + } + + [Test] + public async Task GCTokenHandlerTest_ValidateToken_Illegal_Token() + { + var gcTokenHandler = + new GCEndpointHandlerUtils( + () => new MicrodotHostingConfig(), + _logger, + _dateTime, + _gcTokenContainer); + + var nameValueCollection = new NameValueCollection(); + nameValueCollection.Add("token", "foo_bar_buzz"); + + var validateTokenResult = + gcTokenHandler.ValidateToken( + nameValueCollection, + out var additionalInfo); + + Assert.IsFalse(validateTokenResult); + Assert.AreEqual("Illegal request", additionalInfo); + } + + [Test] + public async Task GCTokenHandlerTest_ValidateToken_RecognizedToken() + { + var expectedToken = Guid.NewGuid(); + _gcTokenContainer.ValidateToken(Arg.Is(expectedToken)).Returns(true); + + var gcTokenHandler = + new GCEndpointHandlerUtils( + () => new MicrodotHostingConfig(), + _logger, + _dateTime, + _gcTokenContainer); + + var nameValueCollection = new NameValueCollection(); + nameValueCollection.Add("token", expectedToken.ToString()); + + var validateTokenResult = + gcTokenHandler.ValidateToken( + nameValueCollection, + out var additionalInfo); + + Assert.IsTrue(validateTokenResult); + } + + [Test] + public async Task GCTokenHandlerTest_Generate_Token() + { + var now = DateTime.UtcNow; + var generatedToken = Guid.NewGuid(); + _dateTime.UtcNow.Returns(now); + var ipAddress = IPAddress.Parse("40.30.40.80"); + + _gcTokenContainer.GenerateToken().Returns(generatedToken); + _gcTokenContainer.ValidateToken(Arg.Is(x => x == generatedToken)).Returns(true); + + var gcTokenHandler = + new GCEndpointHandlerUtils( + () => new MicrodotHostingConfig() + { + GCGetTokenCooldown = null + }, + _logger, + _dateTime, + _gcTokenContainer); + + var nameValueCollection = new NameValueCollection(); + nameValueCollection.Add("getToken", null); + + var generateTokenResult = + gcTokenHandler.TryProcessAsTokenGenerationRequest( + nameValueCollection, + ipAddress, + out var additionalInfo); + + Assert.IsTrue(generateTokenResult); + + var logCalls = _logger.ReceivedCalls().Select(callback => + { + var logOperation = callback.GetArguments()[0] as Action; + + (string message, object encryptedTags, object unencryptedTags, Exception exception, bool + includeStack) callDetails = (null, null, null, null, false); + logOperation.Invoke((string message, object encryptedTags , object unencryptedTags , Exception exception , bool includeStack )=> + { + callDetails = (message, encryptedTags, unencryptedTags, exception, includeStack); + }); + + return callDetails; + + }).ToList(); + + Assert.IsTrue(logCalls.Count == 1); + + var tags = logCalls.First().unencryptedTags; + var loggedToken = tags.GetType().GetProperty("Token").GetValue(tags); + Assert.AreEqual(generatedToken, loggedToken); + var loggedIP = tags.GetType().GetProperty("IPAddress").GetValue(tags); + Assert.AreEqual(ipAddress.ToString(), loggedIP); + + } + + [Test] + public async Task GCTokenHandlerTest_Empty_No_GetToken() + { + var now = DateTime.UtcNow; + var generatedToken = Guid.NewGuid(); + _dateTime.UtcNow.Returns(now); + + _gcTokenContainer.GenerateToken().Returns(generatedToken); + _gcTokenContainer.ValidateToken(Arg.Is(x => x == generatedToken)).Returns(true); + + var gcTokenHandler = + new GCEndpointHandlerUtils( + () => new MicrodotHostingConfig() + { + GCGetTokenCooldown = null + }, + _logger, + _dateTime, + _gcTokenContainer); + + var nameValueCollection = new NameValueCollection(); + + var generateTokenResult = + gcTokenHandler.TryProcessAsTokenGenerationRequest( + nameValueCollection, + IPAddress.Parse("40.33.78.111"), + out var additionalInfo); + + Assert.IsFalse(generateTokenResult); + _logger.Received(0).Info(Arg.Any>()); + } + + [Test] + public async Task GCTokenHandlerTest_CoolDown_Test() + { + var now = DateTime.UtcNow; + var generatedToken = Guid.NewGuid(); + _dateTime.UtcNow.Returns(now); + + _gcTokenContainer.GenerateToken().Returns(generatedToken); + _gcTokenContainer.ValidateToken(Arg.Is(x => x == generatedToken)).Returns(true); + + var gcTokenHandler = + new GCEndpointHandlerUtils( + () => new MicrodotHostingConfig() + { + GCGetTokenCooldown = TimeSpan.FromMinutes(10) + }, + _logger, + _dateTime, + _gcTokenContainer); + + var nameValueCollection = new NameValueCollection(); + nameValueCollection.Add("getToken", null); + + var generateTokenResult = + gcTokenHandler.TryProcessAsTokenGenerationRequest( + nameValueCollection, + IPAddress.Parse("40.33.78.111"), + out var additionalInfo); + + Assert.IsTrue(generateTokenResult); + Assert.AreEqual("GC token generated", additionalInfo); + + _dateTime.UtcNow.Returns(now.AddMinutes(1)); + + generateTokenResult = + gcTokenHandler.TryProcessAsTokenGenerationRequest( + nameValueCollection, + IPAddress.Parse("40.33.78.111"), + out additionalInfo); + + Assert.IsTrue(generateTokenResult); + Assert.AreEqual($"GC getToken cooldown in effect, will be ready in {TimeSpan.FromMinutes(9)}", + additionalInfo); + + _dateTime.UtcNow.Returns(now.AddMinutes(11)); + generateTokenResult = + gcTokenHandler.TryProcessAsTokenGenerationRequest( + nameValueCollection, + IPAddress.Parse("40.33.78.111"), + out additionalInfo); + + Assert.IsTrue(generateTokenResult); + Assert.AreEqual("GC token generated", additionalInfo); + Assert.AreEqual(2,_logger.ReceivedCalls().Count()); + } + + [Test] + public async Task GCTokenContainer_Generate_And_Validate_Test() + { + var now = DateTime.Now; + _dateTime.UtcNow.Returns(now); + var gcTokenContainer = new GCTokenContainer(_dateTime); + var generatedToken = gcTokenContainer.GenerateToken(); + Assert.AreNotEqual(generatedToken, Guid.Empty); + Assert.IsTrue(gcTokenContainer.ValidateToken(generatedToken)); + } + + [Test] + public async Task GCTokenContainer_Generate_And_Validate_Test_Test_Cleanup() + { + var now = DateTime.Now; + _dateTime.UtcNow.Returns(now); + var gcTokenContainer = new GCTokenContainer(_dateTime); + var generatedToken = gcTokenContainer.GenerateToken(); + Assert.AreNotEqual(generatedToken, Guid.Empty); + Assert.IsTrue(gcTokenContainer.ValidateToken(generatedToken)); + _dateTime.UtcNow.Returns(now.AddMinutes(1)); + Assert.IsTrue(gcTokenContainer.ValidateToken(generatedToken)); + _dateTime.UtcNow.Returns(now.AddMinutes(31)); + Assert.IsFalse(gcTokenContainer.ValidateToken(generatedToken)); + } + + [Test] + [TestCase(GCType.Gen0)] + [TestCase(GCType.Gen1)] + [TestCase(GCType.Gen2)] + [TestCase(GCType.LOHCompaction)] + [TestCase(GCType.BlockingLohCompaction)] + public async Task GCEndpointHandlerTest_On_Matching_Path_Right_GcType(GCType gcType) + { + var totalMemoryBeforeGc = 500; + var totalMemoryAfterGc = 70; + var elapsedMilliseconds = 33; + var ipAddress = IPAddress.Parse("40.33.78.111"); + var logSpy = new LogSpy(); + + + _gcEndpointHandlerUtils.ValidateToken(Arg.Any(), out Arg.Any()) + .Returns(true); + _gcEndpointHandlerUtils.TryProcessAsTokenGenerationRequest( + Arg.Any(), + Arg.Any(), + out Arg.Any()) + .Returns(false); + _gcEndpointHandlerUtils.ValidateGcType( + Arg.Any(), + out Arg.Any(), + out Arg.Any()) + .Returns(x=> + { + x[2] = gcType; + return true; + }); + + _gcEndpointHandlerUtils.Collect(Arg.Any()).Returns( + new GCCollectionResult( + totalMemoryBeforeGc, + totalMemoryAfterGc, + elapsedMilliseconds) + ); + + var gcEndpointHandler = new GCEndpointHandler(() => new MicrodotHostingConfig() + { + GCEndpointEnabled = true, + }, logSpy, _gcEndpointHandlerUtils); + + var gcHandlingResult = await gcEndpointHandler + .Handle(new Uri("http://my-host-name/force-traffic-affecting-gc"), new NameValueCollection() + { + { "gcType", gcType.ToString() } + }, + ipAddress + ); + + Assert.IsTrue(gcHandlingResult.Successful); + Assert.AreEqual("GC ran successfully",gcHandlingResult.Message); + Assert.NotNull(gcHandlingResult.GcCollectionResult); + Assert.AreEqual(totalMemoryBeforeGc, gcHandlingResult.GcCollectionResult.TotalMemoryBeforeGC); + Assert.AreEqual(totalMemoryAfterGc, gcHandlingResult.GcCollectionResult.TotalMemoryAfterGC); + Assert.AreEqual(elapsedMilliseconds, gcHandlingResult.GcCollectionResult.ElapsedMilliseconds); + Assert.AreEqual(1, logSpy.LogEntries.Count()); + var logEntry = logSpy.LogEntries.Single(); + Assert.AreEqual(gcType.ToString(), logEntry.UnencryptedTags["tags.GcType"]); + Assert.AreEqual(ipAddress.ToString(), logEntry.UnencryptedTags["tags.IPAddress"]); + Assert.AreEqual(totalMemoryAfterGc.ToString(), logEntry.UnencryptedTags["tags.TotalMemoryAfterGC_i"]); + Assert.AreEqual(totalMemoryBeforeGc.ToString(), logEntry.UnencryptedTags["tags.TotalMemoryBeforeGC_i"]); + Assert.NotNull(logEntry.UnencryptedTags["tags.GCDuration_i"]); + } + + [Test] + [TestCase(GCType.Gen0)] + [TestCase(GCType.Gen1)] + [TestCase(GCType.Gen2)] + [TestCase(GCType.LOHCompaction)] + [TestCase(GCType.BlockingLohCompaction)] + public async Task GCCollectionRunner_Sanity(GCType genType) + { + var gcCollectionRunner = new GCEndpointHandlerUtils(() => new MicrodotHostingConfig(), + _logger, _dateTime, _gcTokenContainer); + Assert.DoesNotThrow(()=>gcCollectionRunner.Collect(genType)); + } + } +} \ No newline at end of file diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/GrainAgeLimitTestService/GrainAgeLimitTestServiceHost.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/GrainAgeLimitTestService/GrainAgeLimitTestServiceHost.cs deleted file mode 100644 index a2fc78ba..00000000 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/GrainAgeLimitTestService/GrainAgeLimitTestServiceHost.cs +++ /dev/null @@ -1,78 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Fakes.KernelUtils; -using Gigya.Microdot.Hosting.Validators; -using Gigya.Microdot.Ninject; -using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.WarmupTestService; -using Gigya.Microdot.Orleans.Ninject.Host; -using Ninject; -using Orleans; - -namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService -{ - public class GrainAgeLimitTestServiceHost : MicrodotOrleansServiceHost - { - public GrainAgeLimitTestServiceHost() - { } - - public override string ServiceName => "TestService"; - - public override ILoggingModule GetLoggingModule() - { - return new FakesLoggersModules(); - } - - public IKernel Kernel; - protected override void PreConfigure(IKernel kernel) - { - base.PreConfigure(kernel); - kernel.Rebind().To().InSingletonScope(); - kernel.Rebind().To().InSingletonScope(); - Func writeGrainLog = () => new GrainLoggingConfig{LogMicrodotGrains = true, LogRatio = 1, LogServiceGrains = true, LogOrleansGrains = true}; - kernel.Rebind>().ToConstant(writeGrainLog); - kernel.RebindForTests(); - Kernel = kernel; - - } - - protected override Task AfterOrleansStartup(IGrainFactory grainFactory) - { - if (grainFactory == null) throw new NullReferenceException("AfterOrleansStartup no grainFactory"); - return base.AfterOrleansStartup(grainFactory); - } - - public class MockServiceValidator : ServiceValidator - { - - public MockServiceValidator() - : base(new List().ToArray()) - { - - } - } - } -} \ No newline at end of file diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/Account.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/Account.cs index cb06ae16..577d1ad2 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/Account.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/Account.cs @@ -1,16 +1,4 @@ -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Fakes.KernelUtils; -using Gigya.Microdot.Ninject; -using Gigya.Microdot.Orleans.Hosting; -using Gigya.Microdot.Orleans.Ninject.Host; -using Ninject; -using Ninject.Syntax; -using Orleans; -using Orleans.Hosting; -using Orleans.Providers; -using System.Threading.Tasks; - -namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.StorageProviderTest +namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.StorageProviderTest { public class Account { diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/AccountGrain.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/AccountGrain.cs index b647cad3..9b2d0453 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/AccountGrain.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/AccountGrain.cs @@ -1,12 +1,4 @@ -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Fakes.KernelUtils; -using Gigya.Microdot.Ninject; -using Gigya.Microdot.Orleans.Hosting; -using Gigya.Microdot.Orleans.Ninject.Host; -using Ninject; -using Ninject.Syntax; -using Orleans; -using Orleans.Hosting; +using Orleans; using Orleans.Providers; using System.Threading.Tasks; diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/BindStorageTest.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/BindStorageTest.cs index b1dd6024..abca111d 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/BindStorageTest.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/BindStorageTest.cs @@ -1,9 +1,4 @@ -using Gigya; -using Gigya.Common; -using Gigya.Common.OrleansInfra; -using Gigya.Common.OrleansInfra.FunctionalTests; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; +using System; using Gigya.Microdot.Testing.Service; using NUnit.Framework; using System.Threading.Tasks; @@ -21,8 +16,16 @@ public async Task CanBindStorage() var accountGrain = selfHostService.GrainClient.GetGrain(0); await accountGrain.Save(new Account() { Name = "test" }); - var accunt = await accountGrain.Get(); - Assert.AreEqual("test", accunt.Name); + var account = await accountGrain.Get(); + Assert.AreEqual("test", account.Name); + try + { + selfHostService.Dispose(); + } + catch (Exception e) + { + Console.WriteLine(e); + } } } } diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/IAccountGrain.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/IAccountGrain.cs index 83889caa..59ed378a 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/IAccountGrain.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/IAccountGrain.cs @@ -1,13 +1,4 @@ -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Fakes.KernelUtils; -using Gigya.Microdot.Ninject; -using Gigya.Microdot.Orleans.Hosting; -using Gigya.Microdot.Orleans.Ninject.Host; -using Ninject; -using Ninject.Syntax; -using Orleans; -using Orleans.Hosting; -using Orleans.Providers; +using Orleans; using System.Threading.Tasks; namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.StorageProviderTest diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/MemoryServiceHost.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/MemoryServiceHost.cs index 92707211..2dfbb800 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/MemoryServiceHost.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/StorageProviderTest/MemoryServiceHost.cs @@ -4,15 +4,10 @@ using Gigya.Microdot.Hosting.Validators; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.Ninject; -using Gigya.Microdot.Orleans.Hosting; using Gigya.Microdot.Orleans.Ninject.Host; using Gigya.Microdot.SharedLogic; using Ninject; -using Ninject.Syntax; -using Orleans; using Orleans.Hosting; -using Orleans.Providers; -using System.Threading.Tasks; using static Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService.CalculatorServiceHost; namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.StorageProviderTest diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/WarmupTestService/WarmupTestServiceHostWithSiloHostFake.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/WarmupTestService/WarmupTestServiceHostWithSiloHostFake.cs index ae7c5a9d..0bbf2f82 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/WarmupTestService/WarmupTestServiceHostWithSiloHostFake.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/WarmupTestService/WarmupTestServiceHostWithSiloHostFake.cs @@ -1,6 +1,4 @@ -using Gigya.Microdot.Fakes; -using Gigya.Microdot.Interfaces; -using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; +using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; using Gigya.Microdot.SharedLogic; using Ninject; diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/OrleansHostHooksTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/OrleansHostHooksTests.cs index 9a73d369..88989672 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/OrleansHostHooksTests.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/OrleansHostHooksTests.cs @@ -12,11 +12,7 @@ using NUnit.Framework; using Orleans; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Threading.Tasks; -using Gigya.Microdot.SharedLogic.Security; namespace Gigya.Microdot.Orleans.Hosting.UnitTests { @@ -58,6 +54,8 @@ public void AfterOrleansStartup_ShouldBeCalled() var tester = new ServiceTester(); Assert.IsTrue(tester.Host.AfterOrleansCalled, "AfterOrleansStartup hasn't been called."); + + //tester.Dispose(); } } } diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/OrleansToNinjectBinding/OrleansToNinjectBindingTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/OrleansToNinjectBinding/OrleansToNinjectBindingTests.cs index 81716521..476e5062 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/OrleansToNinjectBinding/OrleansToNinjectBindingTests.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/OrleansToNinjectBinding/OrleansToNinjectBindingTests.cs @@ -1,21 +1,19 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding; using Microsoft.Extensions.DependencyInjection; using Ninject; -using Ninject.Extensions.Factory; using Ninject.Syntax; using NUnit.Framework; using Orleans.Runtime; namespace Gigya.Microdot.Orleans.Hosting.UnitTests.OrleansToNinjectBinding { - [TestFixture, Parallelizable(ParallelScope.All)] + [TestFixture, Parallelizable(ParallelScope.None)] public class OrleansToNinjectBindingTests { public enum ServiceProviderType @@ -108,34 +106,6 @@ public void When_request_same_scopeDepency_on_scope_run_parallel_Should_create_o Assert.AreEqual(1, groups.Count()); } - - [Ignore("manual")] - //Convert to benchmark dot nets - [TestCase(ServiceProviderType.microdot)] - [TestCase(ServiceProviderType.microsoft)] - public void SimpleSantyForPreforamce(ServiceProviderType serviceProviderType) - { - var binding = new ServiceCollection().AddScoped(); - - var serviceProvider = CreateServiceProvider(binding, serviceProviderType); - var sw = Stopwatch.StartNew(); - Parallel.For(0, 10000, (i) => - { - var serviceScopeFactory = (IServiceScopeFactory)serviceProvider.GetService(typeof(IServiceScopeFactory)); - var serviceScope = serviceScopeFactory.CreateScope(); - ConcurrentBag dependencies = new ConcurrentBag(); - - Parallel.For(0, 5, (j) => - { - var object1 = (Dependency)serviceScope.ServiceProvider.GetService(typeof(Dependency)); - dependencies.Add(object1); - }); - - var groups = dependencies.ToArray().GroupBy(x => x); - Assert.AreEqual(1, groups.Count()); - }); - Assert.Greater(1000, sw.ElapsedMilliseconds); - } [TestCase(ServiceProviderType.microsoft)] [TestCase(ServiceProviderType.microdot)] diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Properties/AssemblyInfo.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Properties/AssemblyInfo.cs index 5663dbbe..e8479793 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Properties/AssemblyInfo.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Properties/AssemblyInfo.cs @@ -21,7 +21,6 @@ #endregion using Gigya.Microdot.Orleans.Hosting.UnitTests; -using System.Reflection; using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/SchemaEndpointTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/SchemaEndpointTests.cs index b6a3e1ff..f9c6affa 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/SchemaEndpointTests.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/SchemaEndpointTests.cs @@ -1,93 +1,109 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Linq; -using System.Threading.Tasks; -using Gigya.Common.Contracts.HttpService; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; -using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; -using Gigya.Microdot.ServiceProxy; -using Gigya.Microdot.Testing.Service; -using NUnit.Framework; - -namespace Gigya.Microdot.Orleans.Hosting.UnitTests -{ - [TestFixture,Parallelizable(ParallelScope.Fixtures)] - public class SchemaEndpointTests - { - private IServiceProxyProvider _serviceProxyProvider; - private ServiceTester _tester; - - - [OneTimeSetUp] - public void SetUp() - { - try - { - _tester = new ServiceTester(); - _serviceProxyProvider = _tester.GetServiceProxyProvider("CalculatorService"); - } - catch (Exception e) - { - Console.WriteLine(e); - throw; - } - } - - [OneTimeTearDown] - public void TearDown() - { - _tester.Dispose(); - } - - - [Test] - public async Task MethodTypeName() - { - var schema = await _serviceProxyProvider.GetSchema(); - var iface = schema.Interfaces.First(_ => _.Name == typeof(ICalculatorService).FullName); - var schemaTestMethod = iface.Methods.FirstOrDefault(_ => _.Name == nameof(ICalculatorService.Add)); - Assert.IsNotNull(schemaTestMethod, "Service schema did not return the method Add"); - Assert.AreEqual(typeof(ICalculatorService).FullName, iface.Name); - } - - - [Test] - public async Task ReturnPublicEndpointAttribute() - { - var schema = await _serviceProxyProvider.GetSchema(); - var iface = schema.Interfaces.First(_ => _.Name == typeof(ICalculatorService).FullName); - var schemaTestMethod = iface.Methods.FirstOrDefault(_ => _.Name == nameof(ICalculatorService.GetAppDomainChain)); - Assert.IsNotNull(schemaTestMethod, "Service schema did not return the method GetAppDomainChain"); - var attribute = schemaTestMethod.Attributes.Select(x => x.Attribute).OfType().Single(); - Assert.IsNotNull(attribute, "method GetAppDomainChain should include attribute of type PublicEndpoint"); - Assert.IsTrue(attribute.EndpointName != null, $"PublicEndpoint attribute of SchemaTestMethod should include '{nameof(PublicEndpointAttribute.EndpointName)}' property"); - Assert.AreEqual("test.calculator.getAppDomainChain", attribute.EndpointName); - Assert.AreEqual(false, attribute.RequireHTTPS); - Assert.AreEqual("something", attribute.PropertyNameForResponseBody); - } - - } - -} +#region Copyright +// Copyright 2017 Gigya Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +#endregion + +using System; +using System.Linq; +using System.Threading.Tasks; +using Gigya.Common.Contracts.HttpService; +using Gigya.Microdot.Hosting.HttpService.Endpoints; +using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; +using Gigya.Microdot.ServiceProxy; +using Gigya.Microdot.SharedLogic.HttpService; +using Gigya.Microdot.Testing.Service; +using NSubstitute; +using NSubstitute.ReceivedExtensions; +using NUnit.Framework; + +namespace Gigya.Microdot.Orleans.Hosting.UnitTests +{ + [TestFixture,Parallelizable(ParallelScope.Fixtures)] + public class SchemaEndpointTests + { + private IServiceProxyProvider _serviceProxyProvider; + private ServiceTester _tester; + + + [OneTimeSetUp] + public void SetUp() + { + try + { + _tester = new ServiceTester(); + + _serviceProxyProvider = _tester.GetServiceProxyProvider("CalculatorService"); + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + } + + [OneTimeTearDown] + public void TearDown() + { + _tester.Dispose(); + } + + + [Test] + public async Task MethodTypeName() + { + var schema = await _serviceProxyProvider.GetSchema(); + var iface = schema.Interfaces.First(_ => _.Name == typeof(ICalculatorService).FullName); + var schemaTestMethod = iface.Methods.FirstOrDefault(_ => _.Name == nameof(ICalculatorService.Add)); + Assert.IsNotNull(schemaTestMethod, "Service schema did not return the method Add"); + Assert.AreEqual(typeof(ICalculatorService).FullName, iface.Name); + } + + + [Test] + public async Task ReturnPublicEndpointAttribute() + { + var schema = await _serviceProxyProvider.GetSchema(); + var iface = schema.Interfaces.First(_ => _.Name == typeof(ICalculatorService).FullName); + var schemaTestMethod = iface.Methods.FirstOrDefault(_ => _.Name == nameof(ICalculatorService.GetAppDomainChain)); + Assert.IsNotNull(schemaTestMethod, "Service schema did not return the method GetAppDomainChain"); + var attribute = schemaTestMethod.Attributes.Select(x => x.Attribute).OfType().Single(); + Assert.IsNotNull(attribute, "method GetAppDomainChain should include attribute of type PublicEndpoint"); + Assert.IsTrue(attribute.EndpointName != null, $"PublicEndpoint attribute of SchemaTestMethod should include '{nameof(PublicEndpointAttribute.EndpointName)}' property"); + Assert.AreEqual("test.calculator.getAppDomainChain", attribute.EndpointName); + Assert.AreEqual(false, attribute.RequireHTTPS); + Assert.AreEqual("something", attribute.PropertyNameForResponseBody); + } + + + [Test] + public async Task SchemaEndpointUsesBinder() + { + var serviceSchemaPostProcessor = Substitute.For(); + + var schemaProvider = new ServiceSchema(new[] { typeof(ICalculatorService) }); + var serviceSchema = new SchemaEndpoint(schemaProvider, + serviceSchemaPostProcessor); + + serviceSchemaPostProcessor.Received(1).PostProcessServiceSchema(schemaProvider); + } + + } + +} diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Serialization/ExceptionSerializationTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Serialization/ExceptionSerializationTests.cs index 07c53b06..e38e37eb 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Serialization/ExceptionSerializationTests.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Serialization/ExceptionSerializationTests.cs @@ -1,51 +1,26 @@ using System; -using System.Collections.Generic; using System.Net.Http; -using System.Threading.Tasks; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Fakes; -using Gigya.Microdot.Hosting.Environment; -using Gigya.Microdot.Hosting.HttpService; -using Gigya.Microdot.Interfaces; -using Gigya.Microdot.Interfaces.Events; -using Gigya.Microdot.Interfaces.Logging; -using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.Ninject; -using Gigya.Microdot.Orleans.Hosting.Logging; -using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice; -using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; -using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.StorageProviderTest; using Gigya.Microdot.Orleans.Ninject.Host; using Gigya.Microdot.Orleans.Ninject.Host.NinjectOrleansBinding; -using Gigya.Microdot.ServiceProxy.Caching; using Gigya.Microdot.SharedLogic; -using Gigya.Microdot.SharedLogic.Configurations.Serialization; -using Gigya.Microdot.SharedLogic.HttpService; -using Gigya.Microdot.SharedLogic.Security; -using Gigya.Microdot.Testing.Service; -using Gigya.Microdot.Testing.Shared; using Gigya.Microdot.UnitTests; -using Gigya.Microdot.UnitTests.Caching.Host; using Gigya.Microdot.UnitTests.Serialization; -using Gigya.Microdot.UnitTests.ServiceProxyTests; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; using Ninject; using Ninject.Syntax; -using NSubstitute; using NUnit.Framework; using Orleans; using Orleans.Configuration; -using Orleans.Runtime; using Orleans.Serialization; using Shouldly; namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Serialization { - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + [TestFixture,Parallelizable(ParallelScope.Fixtures)] public class ExceptionSerializationTests { class MicrodotServiceProviderWithScope2 : IServiceProvider, IServiceScope, IGlobalServiceProvider diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/ServiceTesterTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/ServiceTesterTests.cs index c37b36b5..dd797a51 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/ServiceTesterTests.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/ServiceTesterTests.cs @@ -21,13 +21,7 @@ #endregion using System; -using System.Linq; -using System.Threading.Tasks; -using Gigya.Common.Contracts.HttpService; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService; -using Gigya.Microdot.ServiceProxy; using Gigya.Microdot.SharedLogic; using Gigya.Microdot.Testing.Service; using Gigya.Microdot.Testing.Shared.Service; @@ -36,20 +30,20 @@ namespace Gigya.Microdot.Orleans.Hosting.UnitTests { - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + [TestFixture, Parallelizable(ParallelScope.Fixtures)] public class ServiceTesterTests { private ServiceTester _tester; [Test] - public async Task ServiceTesterWhenServiceFailedToGracefullyShutdownShouldThrow() + public void ServiceTesterWhenServiceFailedToGracefullyShutdownShouldThrow() { // shutdownWaitTimeSec: 0 var serviceArguments = new ServiceArguments( - ServiceStartupMode.CommandLineNonInteractive, + ServiceStartupMode.CommandLineNonInteractive, ConsoleOutputMode.Disabled, - SiloClusterMode.PrimaryNode, - DisposablePort.GetPort().Port, + SiloClusterMode.PrimaryNode, + DisposablePort.GetPort().Port, onStopWaitTimeSec: 0); _tester = new ServiceTester( diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/TestContextAttribute.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/TestContextAttribute.cs index 876a3215..436a49c6 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/TestContextAttribute.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/TestContextAttribute.cs @@ -1,11 +1,6 @@ -using NUnit.Framework; -using NUnit.Framework.Interfaces; +using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Gigya.Microdot.Orleans.Hosting.UnitTests { diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Validation/ConfigObjectTypeValidatorTest.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Validation/ConfigObjectTypeValidatorTest.cs index 2249881d..5e9122d1 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Validation/ConfigObjectTypeValidatorTest.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Validation/ConfigObjectTypeValidatorTest.cs @@ -1,12 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; -using System.Runtime.InteropServices; -using System.Text; -using System.Threading.Tasks; -using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Hosting.Validators; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Configuration; diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Validation/SensitivityAttributesValidatorTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Validation/SensitivityAttributesValidatorTests.cs index c49e1a3e..a4347256 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Validation/SensitivityAttributesValidatorTests.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Validation/SensitivityAttributesValidatorTests.cs @@ -21,19 +21,12 @@ #endregion using System; -using System.Net; -using System.Threading; using System.Threading.Tasks; using Gigya.Common.Contracts.Exceptions; using Gigya.Common.Contracts.HttpService; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Fakes; -using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.Hosting.Validators; -using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.Ninject; -using Gigya.Microdot.Testing.Shared; using Gigya.Microdot.UnitTests.Caching.Host; using Gigya.ServiceContract.Attributes; using Newtonsoft.Json.Linq; @@ -43,7 +36,7 @@ namespace Gigya.Common.Application.UnitTests.Validation { - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + [TestFixture, NonParallelizable] public class SensitivityAttributesValidatorTests { diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/WarmupTests.cs b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/WarmupTests.cs index 9f322f17..d658884a 100644 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/WarmupTests.cs +++ b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/WarmupTests.cs @@ -1,8 +1,5 @@ - -using System; +using System; using System.Threading.Tasks; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.WarmupTestService; using Gigya.Microdot.Testing.Service; using NUnit.Framework; @@ -25,8 +22,14 @@ public async Task InstanceReadyBeforeCallingMethod_Warmup() Assert.Greater(beforeGrainCreated, dependencyCreateDate, "dependencyCreateDate should create before grain is created"); - tester.Dispose(); + try + { + tester.Dispose(); + } + catch (Exception e) + { + Console.WriteLine(e); + } } - } } diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/app.config b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/app.config deleted file mode 100644 index 75152f70..00000000 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/app.config +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - diff --git a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/paket.references b/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/paket.references deleted file mode 100644 index db56ad51..00000000 --- a/tests/Gigya.Microdot.Orleans.Hosting.UnitTests/paket.references +++ /dev/null @@ -1,23 +0,0 @@ -Gigya.ServiceContract -Microsoft.Extensions.DependencyInjection -Microsoft.Orleans.OrleansCodeGenerator -Microsoft.Orleans.CodeGenerator.MsBuild -Microsoft.Orleans.OrleansProviders -NSubstitute -NUnit -NUnit3TestAdapter -Ninject -Shouldly -Castle.Core -ZooKeeperNetEx -System.Threading.Tasks.Dataflow -System.ValueTuple -# Solve binding redirect issue, related to project vs nuget references. OrleansDashboard depends on. -Microsoft.AspNetCore.Hosting -Microsoft.AspNetCore.Server.Kestrel -Microsoft.CSharp -System.Net.Http -Microsoft.NET.Test.Sdk - -# Remove after the transition to netcore completed -System.ServiceProcess.ServiceController \ No newline at end of file diff --git a/tests/Gigya.Microdot.ServiceContract.UnitTests/Gigya.Microdot.ServiceContract.UnitTests.csproj b/tests/Gigya.Microdot.ServiceContract.UnitTests/Gigya.Microdot.ServiceContract.UnitTests.csproj deleted file mode 100644 index 19b12c0d..00000000 --- a/tests/Gigya.Microdot.ServiceContract.UnitTests/Gigya.Microdot.ServiceContract.UnitTests.csproj +++ /dev/null @@ -1,13 +0,0 @@ - - - - net472 - true - true - $(SolutionDir)main.ruleset - - - - - - \ No newline at end of file diff --git a/tests/Gigya.Microdot.ServiceContract.UnitTests/JsonHelperTests.cs b/tests/Gigya.Microdot.ServiceContract.UnitTests/JsonHelperTests.cs deleted file mode 100644 index 8cef32a8..00000000 --- a/tests/Gigya.Microdot.ServiceContract.UnitTests/JsonHelperTests.cs +++ /dev/null @@ -1,399 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Linq; -using System.Numerics; -using Gigya.ServiceContract.Exceptions; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using NUnit.Framework; -using Shouldly; - -namespace Gigya.Common.Contracts.UnitTests -{ - public enum MyEnum { Zero, One, Two } - public class SomeClass { public int A; public long B; public ushort? C; [JsonProperty] SomeClass Inner; } - public struct SomeStruct { public int A; public long B; public ushort? C; } - - [TestFixture,Parallelizable(ParallelScope.Fixtures)] - public class JsonHelperTests - { - [Test] - public void ConvertWeaklyTypedValue_NullTargetType_ShouldThrow() - { - Should.Throw(() => JsonHelper.ConvertWeaklyTypedValue(5, null)); - } - - - [Test] - public void ConvertWeaklyTypedValue_Null_ShouldReturnNull() - { - object actual = JsonHelper.ConvertWeaklyTypedValue(null, typeof(MyEnum)); - actual.ShouldBe(null); - } - - - [Test] - public void ConvertWeaklyTypedValue_EnumAsNumeric_ShouldConvert() - { - object actual = JsonHelper.ConvertWeaklyTypedValue((long)MyEnum.Two, typeof(MyEnum)); - actual.ShouldBe(MyEnum.Two); - } - - - [Test] - public void ConvertWeaklyTypedValue_EnumAsInvalidNumeric_ShouldConvert() - { - object actual = JsonHelper.ConvertWeaklyTypedValue((long)5, typeof(MyEnum)); - actual.ShouldBe((MyEnum)5); - } - - - [Test] - public void ConvertWeaklyTypedValue_EnumAsNullableNumeric_ShouldConvert() - { - object actual = JsonHelper.ConvertWeaklyTypedValue((long)MyEnum.Two, typeof(MyEnum?)); - actual.ShouldBe(MyEnum.Two); - } - - - [Test] - public void ConvertWeaklyTypedValue_EnumAsInvalidNullableNumeric_ShouldConvert() - { - object actual = JsonHelper.ConvertWeaklyTypedValue((long)5, typeof(MyEnum?)); - actual.ShouldBe((MyEnum)5); - } - - - [Test] - public void ConvertWeaklyTypedValue_EnumAsString_ShouldConvert() - { - object actual = JsonHelper.ConvertWeaklyTypedValue("Two", typeof(MyEnum)); - actual.ShouldBe(MyEnum.Two); - } - - - [Test] - public void ConvertWeaklyTypedValue_EnumAsInvalidString_ShouldThrow() - { - Should.Throw(() => JsonHelper.ConvertWeaklyTypedValue("INVALID", typeof(MyEnum))); - } - - - [TestCase("N"), TestCase("D"), TestCase("B"), TestCase("P")] - public void ConvertWeaklyTypedValue_GuidAsString_ShouldConvert(string format) - { - var expected = Guid.NewGuid(); - object actual = JsonHelper.ConvertWeaklyTypedValue(expected.ToString(format), typeof(Guid)); - actual.ShouldBe(expected); - } - - - [Test] - public void ConvertWeaklyTypedValue_LargeUInt64AsBigInteger_ShouldConvert() - { - object actual = JsonHelper.ConvertWeaklyTypedValue(new BigInteger(ulong.MaxValue), typeof(ulong)); - actual.ShouldBeOfType(); - actual.ShouldBe(ulong.MaxValue); - } - - - [Test] - public void ConvertWeaklyTypedValue_LocalDateTimeAsString_ShouldConvert() - { - var expected = DateTime.Now; - DateTime actual = (DateTime)JsonHelper.ConvertWeaklyTypedValue(expected.ToString("O"), typeof(DateTime)); - actual.ShouldBe(expected); - actual.Kind.ShouldBe(DateTimeKind.Local); - } - - - [Test] - public void ConvertWeaklyTypedValue_LocalDateTimeAsDateTimeOffset_ShouldConvert() - { - var expected = DateTime.Now; - DateTime actual = (DateTime)JsonHelper.ConvertWeaklyTypedValue(new DateTimeOffset(expected), typeof(DateTime)); - actual.ShouldBe(expected); - actual.Kind.ShouldBe(DateTimeKind.Local); - } - - - [Test] - public void ConvertWeaklyTypedValue_UtcDateTimeAsString_ShouldConvert() - { - var expected = DateTime.UtcNow; - DateTime actual = (DateTime)JsonHelper.ConvertWeaklyTypedValue(expected.ToString("O"), typeof(DateTime)); - actual.ShouldBe(expected); - actual.Kind.ShouldBe(DateTimeKind.Utc); - } - - - [Test] - public void ConvertWeaklyTypedValue_UtcDateTimeAsDateTimeOffset_ShouldConvert() - { - var expected = DateTime.UtcNow; - DateTime actual = (DateTime)JsonHelper.ConvertWeaklyTypedValue(new DateTimeOffset(expected), typeof(DateTime)); - actual.ShouldBe(expected); - actual.Kind.ShouldBe(DateTimeKind.Utc); - } - - - [Test] - public void ConvertWeaklyTypedValue_DateTimeAsInt_ShouldThrow() - { - Should.Throw(() => JsonHelper.ConvertWeaklyTypedValue(5, typeof(DateTime))); - } - - - [Test] - public void ConvertWeaklyTypedValue_LocalDateTimeOffsetAsString_ShouldConvert() - { - var expected = DateTimeOffset.Now; - DateTimeOffset actual = (DateTimeOffset)JsonHelper.ConvertWeaklyTypedValue(expected.ToString("O"), typeof(DateTimeOffset)); - actual.ShouldBe(expected); - actual.Offset.ShouldBe(expected.Offset); - } - - - [Test] - public void ConvertWeaklyTypedValue_LocalDateTimeOffsetAsDateTime_ShouldConvert() - { - var expected = DateTimeOffset.Now; - DateTimeOffset actual = (DateTimeOffset)JsonHelper.ConvertWeaklyTypedValue(expected.LocalDateTime, typeof(DateTimeOffset)); - actual.ShouldBe(expected); - actual.Offset.ShouldBe(expected.Offset); - } - - - [Test] - public void ConvertWeaklyTypedValue_UtcDateTimeOffsetAsString_ShouldConvert() - { - var expected = DateTimeOffset.UtcNow; - DateTimeOffset actual = (DateTimeOffset)JsonHelper.ConvertWeaklyTypedValue(expected.ToString("O"), typeof(DateTimeOffset)); - actual.ShouldBe(expected); - actual.Offset.ShouldBe(expected.Offset); - } - - - [Test] - public void ConvertWeaklyTypedValue_UtcDateTimeOffsetAsDateTime_ShouldConvert() - { - var expected = DateTimeOffset.UtcNow; - DateTimeOffset actual = (DateTimeOffset)JsonHelper.ConvertWeaklyTypedValue(expected.UtcDateTime, typeof(DateTimeOffset)); - actual.ShouldBe(expected); - actual.Offset.ShouldBe(expected.Offset); - } - - - [Test] - public void ConvertWeaklyTypedValue_ForeignDateTimeOffsetAsString_ShouldConvert() - { - var expected = new DateTimeOffset(DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Unspecified), TimeSpan.FromHours(6)); - DateTimeOffset actual = (DateTimeOffset)JsonHelper.ConvertWeaklyTypedValue(expected.ToString("O"), typeof(DateTimeOffset)); - actual.ShouldBe(expected); - actual.Offset.ShouldBe(expected.Offset); - } - - - [Test] - public void ConvertWeaklyTypedValue_DateTimeOffsetAsInt_ShouldThrow() - { - Should.Throw(() => JsonHelper.ConvertWeaklyTypedValue(5, typeof(DateTimeOffset))); - } - - - [Test] - public void ConvertWeaklyTypedValue_TimeSpanAsString_ShouldConvert() - { - var expected = new TimeSpan(11, 12, 13, 14, 15); - object actual = JsonHelper.ConvertWeaklyTypedValue(expected.ToString(), typeof(TimeSpan)); - actual.ShouldBe(expected); - } - - - [Test] - public void ConvertWeaklyTypedValue_TimeSpanAsInvalidString_ShouldConvert() - { - Should.Throw(() => JsonHelper.ConvertWeaklyTypedValue("INVALID", typeof(TimeSpan))); - } - - - [Test] - public void ConvertWeaklyTypedValue_SomeClassAsJson_ShouldConvert() - { - var expected = new SomeClass { A = 5, B = 109 }; - var actual = JsonHelper - .ConvertWeaklyTypedValue(JsonConvert.SerializeObject(expected), typeof(SomeClass)) - .ShouldBeOfType(); - actual.A.ShouldBe(expected.A); - actual.B.ShouldBe(expected.B); - actual.C.ShouldBe(expected.C); - } - - - [Test] - public void ConvertWeaklyTypedValue_SomeStructAsJson_ShouldConvert() - { - var expected = new SomeStruct { A = 5, B = 109 }; - var actual = JsonHelper - .ConvertWeaklyTypedValue(JsonConvert.SerializeObject(expected), typeof(SomeClass)) - .ShouldBeOfType(); - actual.A.ShouldBe(expected.A); - actual.B.ShouldBe(expected.B); - actual.C.ShouldBe(expected.C); - } - } - - - - [TestFixture,Parallelizable(ParallelScope.Fixtures)] - public class JsonHelperNumericTests - { - [DatapointSource] - private Type[] GetTypes() => new[] - { - typeof(byte), - typeof(sbyte), - typeof(short), - typeof(ushort), - typeof(int), - typeof(uint), - typeof(long), - typeof(ulong), - typeof(float), - typeof(double), - typeof(decimal) - }; - - - [DatapointSource] - private object[] GetValues() => GetTypes().SelectMany(t => new[] - { - Convert.ChangeType(42, t), - t.GetField("MinValue").GetValue(null), - t.GetField("MaxValue").GetValue(null), - null - }).ToArray(); - - - [Theory] - public void ConvertWeaklyTypedValue_NumericValue(object value, Type targetType) - { - if (value == null || (value is double && targetType == typeof(float))) - return; - - try - { - object actual = JsonHelper.ConvertWeaklyTypedValue(value, targetType); - actual.ShouldBeOfType(Nullable.GetUnderlyingType(targetType) ?? targetType); - actual.ShouldBe(value); - } - catch (InvalidParameterValueException) { } - } - - - [Theory] - public void ConvertWeaklyTypedValue_NullableNumericValue(object value, Type targetType) - { - if (value is double && targetType == typeof(float)) - return; - - try - { - targetType = typeof(Nullable<>).MakeGenericType(targetType); - object actual = JsonHelper.ConvertWeaklyTypedValue(value, targetType); - - if (value != null) - actual.ShouldBeOfType(Nullable.GetUnderlyingType(targetType) ?? targetType); - - actual.ShouldBe(value); - } - catch (InvalidParameterValueException) { } - } - - [Test] - public void ComplexObjectWithNullValue_ThrowException() - { - var json = JObject.Parse(@"{A:null}"); - try - { - JsonHelper.ConvertWeaklyTypedValue(json, typeof(SomeClass)); - Assert.Fail("Should throw exception because field 'A' is null"); - } - catch (InvalidParameterValueException ex) - { - ex.parameterName.ShouldBeNull(); - ex.ErrorPath.SequenceEqual(new[] {"A"}); - } - } - - [Test] - public void ComplexObjectWithWrongValue_ThrowException() - { - var json = JObject.Parse(@"{A:""abcd""}"); - try - { - JsonHelper.ConvertWeaklyTypedValue(json, typeof(SomeClass)); - Assert.Fail("Should throw exception because field 'A' has invalid value"); - } - catch (InvalidParameterValueException ex) - { - ex.parameterName.ShouldBeNull(); - ex.ErrorPath.SequenceEqual(new[] { "A" }); - } - } - - [Test] - public void ComplexObjectWithComplexObjectWithNullValue_ThrowException() - { - var json = JObject.Parse(@"{Inner: {A:null}}"); - try - { - JsonHelper.ConvertWeaklyTypedValue(json, typeof(SomeClass)); - Assert.Fail("Should throw exception because field 'Inner.A' is null"); - } - catch (InvalidParameterValueException ex) - { - ex.parameterName.ShouldBeNull(); - ex.ErrorPath.SequenceEqual(new[] { "Inner", "A" }); - } - } - - [Test] - public void ComplexObjectWithComplexObjectWithWrongValue_ThrowException() - { - var json = JObject.Parse(@"{Inner: {A:""abcd""}}"); - try - { - JsonHelper.ConvertWeaklyTypedValue(json, typeof(SomeClass)); - Assert.Fail("Should throw exception because field 'Inner.A' has invalid value"); - } - catch (InvalidParameterValueException ex) - { - ex.parameterName.ShouldBeNull(); - ex.ErrorPath.SequenceEqual(new[] { "Inner","A" }); - } - } - - } -} diff --git a/tests/Gigya.Microdot.ServiceContract.UnitTests/Properties/AssemblyInfo.cs b/tests/Gigya.Microdot.ServiceContract.UnitTests/Properties/AssemblyInfo.cs deleted file mode 100644 index f9ecbc46..00000000 --- a/tests/Gigya.Microdot.ServiceContract.UnitTests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,31 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System.Reflection; -using System.Runtime.InteropServices; - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("9fce184a-f17a-4d9b-a1dc-471d8f58685e")] diff --git a/tests/Gigya.Microdot.ServiceContract.UnitTests/ServiceSchemaTests.cs b/tests/Gigya.Microdot.ServiceContract.UnitTests/ServiceSchemaTests.cs deleted file mode 100644 index 003b0efb..00000000 --- a/tests/Gigya.Microdot.ServiceContract.UnitTests/ServiceSchemaTests.cs +++ /dev/null @@ -1,161 +0,0 @@ -#region Copyright -// Copyright 2017 Gigya Inc. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -#endregion - -using System; -using System.Threading.Tasks; -using Gigya.Common.Contracts.HttpService; -using Newtonsoft.Json; -using NUnit.Framework; -#pragma warning disable 169 - -namespace Gigya.Common.Contracts.UnitTests -{ - class DataParamBase - { - [Sensitive] - public int BaseField; - } - class Data: DataParamBase - { - public string s; - public Nested n; - } - - class Nested - { - public DateTime time; - } - - class ResponseData - { - public string a; - public int b; - } - - public class SensitiveAttribute : Attribute {} - - [HttpService(100)] - internal interface ITestInterface - { - [PublicEndpoint("demo.doSomething")] - Task DoSomething(int i, double? nd, string s, [Sensitive] Data data); - } - - [TestFixture,Parallelizable(ParallelScope.Fixtures)] - public class ServiceSchemaTests - { - - [Test] - public void TestSerialization() - { - ServiceSchema schema = new ServiceSchema(new[] { typeof(ITestInterface) }); - string serialized = JsonConvert.SerializeObject(schema, new JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore }); - schema = JsonConvert.DeserializeObject(serialized); - - Assert.IsTrue(schema.Interfaces.Length == 1); - Assert.IsTrue(schema.Interfaces[0].Name == typeof(ITestInterface).FullName); - Assert.IsTrue(schema.Interfaces[0].Attributes.Length == 1); - Assert.IsTrue(schema.Interfaces[0].Attributes[0].Attribute is HttpServiceAttribute); - Assert.IsTrue(schema.Interfaces[0].Attributes[0].TypeName == typeof(HttpServiceAttribute).AssemblyQualifiedName); - Assert.IsTrue((schema.Interfaces[0].Attributes[0].Attribute as HttpServiceAttribute).BasePort == 100); - Assert.IsTrue(schema.Interfaces[0].Methods.Length == 1); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Name == nameof(ITestInterface.DoSomething)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Attributes.Length == 1); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Attributes[0].Attribute is PublicEndpointAttribute); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Attributes[0].TypeName == typeof(PublicEndpointAttribute).AssemblyQualifiedName); - Assert.IsTrue((schema.Interfaces[0].Methods[0].Attributes[0].Attribute as PublicEndpointAttribute).EndpointName == "demo.doSomething"); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters.Length == 4); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[0].Attributes.Length == 0); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[0].Name == "i"); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[0].Type == typeof(int)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[0].TypeName == typeof(int).AssemblyQualifiedName); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[1].Name == "nd"); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[1].Type == typeof(double?)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[2].Name == "s"); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Attributes.Length == 1); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Attributes[0].Attribute is SensitiveAttribute); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[2].Name == nameof(DataParamBase.BaseField)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[2].Attributes[0].Attribute is SensitiveAttribute); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[2].Type == typeof(int)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[1].Name == nameof(Data.n)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[1].Type == typeof(Nested)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[0].Name == nameof(Data.s)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Parameters[3].Fields[0].Type == typeof(string)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Response.Type == typeof(ResponseData)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Response.Fields[0].Name == nameof(ResponseData.a)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Response.Fields[0].Type == typeof(string)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Response.Fields[1].Name == nameof(ResponseData.b)); - Assert.IsTrue(schema.Interfaces[0].Methods[0].Response.Fields[1].Type == typeof(int)); - } - - - [Test] - public void TestUnknownAttribute() - { - var typeFullName = typeof(SensitiveAttribute).AssemblyQualifiedName; - string json = @" - { - ""TypeName"": """ + typeFullName + @""", - ""Data"": { - ""TypeId"": """ + typeFullName + @""" - } - }"; - AttributeSchema attr = JsonConvert.DeserializeObject(json); - Assert.IsNotNull(attr.Attribute); - - json = @" - { - ""TypeName"": ""Gigya.Microdot.ServiceContract.UnitTests.HttpService.SensitiveAttribute2, Gigya.Microdot.ServiceContract.UnitTests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"", - ""Data"": { - ""TypeId"": """ + typeFullName + @""" - } - }"; - attr = JsonConvert.DeserializeObject(json); - Assert.IsNull(attr.Attribute); - Assert.IsTrue(attr.TypeName == "Gigya.Microdot.ServiceContract.UnitTests.HttpService.SensitiveAttribute2, Gigya.Microdot.ServiceContract.UnitTests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"); - } - - - [Test] - public void TestUnknownParamType() - { - string json = @" - { - ""Name"": ""i"", - ""TypeName"": ""System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"", - ""Attributes"": [] - }"; - ParameterSchema param = JsonConvert.DeserializeObject(json); - Assert.IsNotNull(param.Type); - - json = @" - { - ""Name"": ""i"", - ""TypeName"": ""System.Int33, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"", - ""Attributes"": [] - }"; - param = JsonConvert.DeserializeObject(json); - Assert.IsNull(param.Type); - Assert.IsTrue(param.TypeName == "System.Int33, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); - } - } -} diff --git a/tests/Gigya.Microdot.ServiceContract.UnitTests/app.config b/tests/Gigya.Microdot.ServiceContract.UnitTests/app.config deleted file mode 100644 index 535fdb59..00000000 --- a/tests/Gigya.Microdot.ServiceContract.UnitTests/app.config +++ /dev/null @@ -1,9 +0,0 @@ - - - - - True - - - - diff --git a/tests/Gigya.Microdot.ServiceContract.UnitTests/paket.references b/tests/Gigya.Microdot.ServiceContract.UnitTests/paket.references deleted file mode 100644 index 0f2c45d9..00000000 --- a/tests/Gigya.Microdot.ServiceContract.UnitTests/paket.references +++ /dev/null @@ -1,7 +0,0 @@ -Gigya.ServiceContract -Newtonsoft.Json -NUnit -NUnit3TestAdapter -Shouldly -System.ComponentModel.Annotations -Microsoft.NET.Test.Sdk \ No newline at end of file diff --git a/tests/Gigya.Microdot.UnitTests/AdditionalDataSerializationTests.cs b/tests/Gigya.Microdot.UnitTests/AdditionalDataSerializationTests.cs index e893e21b..d13a88a5 100644 --- a/tests/Gigya.Microdot.UnitTests/AdditionalDataSerializationTests.cs +++ b/tests/Gigya.Microdot.UnitTests/AdditionalDataSerializationTests.cs @@ -1,10 +1,10 @@ -using System.Linq; -using Gigya.Microdot.SharedLogic.Events; +using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.HttpService; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using Shouldly; +using System.Linq; namespace Gigya.Microdot.UnitTests { diff --git a/tests/Gigya.Microdot.UnitTests/AssemblyInitialize.cs b/tests/Gigya.Microdot.UnitTests/AssemblyInitialize.cs index 46e57fba..f2e8c3b3 100644 --- a/tests/Gigya.Microdot.UnitTests/AssemblyInitialize.cs +++ b/tests/Gigya.Microdot.UnitTests/AssemblyInitialize.cs @@ -20,8 +20,8 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; using NUnit.Framework; +using System; [SetUpFixture] [NonParallelizable] diff --git a/tests/Gigya.Microdot.UnitTests/Caching/AsyncMemoizerRevokesTests.cs b/tests/Gigya.Microdot.UnitTests/Caching/AsyncMemoizerRevokesTests.cs index 5115eef5..02cdac89 100644 --- a/tests/Gigya.Microdot.UnitTests/Caching/AsyncMemoizerRevokesTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Caching/AsyncMemoizerRevokesTests.cs @@ -1,11 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Runtime.Caching; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; -using Gigya.Common.Contracts.Attributes; +using Gigya.Common.Contracts.Attributes; using Gigya.Microdot.Fakes; using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.ServiceProxy.Caching; @@ -16,11 +9,17 @@ using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; // ReSharper disable ConsiderUsingConfigureAwait (not relevant for tests) namespace Gigya.Microdot.UnitTests.Caching { - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + [TestFixture,Parallelizable(ParallelScope.None)] public class AsyncMemoizerRevokesTests { private const string cacheContextName = "AsyncCache"; @@ -47,8 +46,7 @@ private IMethodCachingSettings GetCachingSettings(double ttlSeconds = 60 * 60 * double refreshTimeSeconds = 60, RevokedResponseBehavior revokedResponseBehavior = RevokedResponseBehavior.FetchNewValueNextTime, ResponseKinds responseKindsToCache = ResponseKinds.NonNullResponse | ResponseKinds.NullResponse, - ResponseKinds responseKindsToIgnore = ResponseKinds.EnvironmentException | ResponseKinds.OtherExceptions | ResponseKinds.RequestException | ResponseKinds.TimeoutException, - RefreshBehavior refreshBehavior = RefreshBehavior.UseOldAndFetchNewValueInBackground) => + ResponseKinds responseKindsToIgnore = ResponseKinds.EnvironmentException | ResponseKinds.OtherExceptions | ResponseKinds.RequestException | ResponseKinds.TimeoutException) => new MethodCachingPolicyConfig { ExpirationTime = TimeSpan.FromSeconds(ttlSeconds), @@ -59,7 +57,7 @@ private IMethodCachingSettings GetCachingSettings(double ttlSeconds = 60 * 60 * ResponseKindsToCache = responseKindsToCache, ResponseKindsToIgnore = responseKindsToIgnore, RequestGroupingBehavior = RequestGroupingBehavior.Enabled, - RefreshBehavior = refreshBehavior, + RefreshBehavior = RefreshBehavior.UseOldAndFetchNewValueInBackground, RevokedResponseBehavior = revokedResponseBehavior, CacheResponsesWhenSupressedBehavior = CacheResponsesWhenSupressedBehavior.Enabled, RefreshMode = RefreshMode.UseRefreshes, @@ -67,7 +65,7 @@ private IMethodCachingSettings GetCachingSettings(double ttlSeconds = 60 * 60 * NotIgnoredResponseBehavior = NotIgnoredResponseBehavior.KeepCachedResponse }; - private MethodInfo ThingifyTaskRevokabkle { get; } = typeof(IThingFrobber).GetMethod(nameof(IThingFrobber.ThingifyTaskRevokable)); + private MethodInfo ThingifyTaskRevokable { get; } = typeof(IThingFrobber).GetMethod(nameof(IThingFrobber.ThingifyTaskRevokable)); private IThingFrobber CreateRevokableDataSource(string[] revokeKeys, params object[] results) { @@ -106,6 +104,7 @@ public void SetUp() } [Test] + [Retry(5)] //Sometime fails on build server because of timing issues public async Task MemoizeAsync_RevokeBeforeRetrivalTaskCompletedCaused_NoIssues() { var completionSource = new TaskCompletionSource>(); @@ -115,7 +114,7 @@ public async Task MemoizeAsync_RevokeBeforeRetrivalTaskCompletedCaused_NoIssues( var memoizer = CreateMemoizer(cache); string firstValue = "first Value"; //Call method to get results - var resultTask = (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + var resultTask = (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); //Post revoke message while results had not arrived revokesSource.PostMessageSynced("revokeKey"); @@ -130,7 +129,7 @@ public async Task MemoizeAsync_RevokeBeforeRetrivalTaskCompletedCaused_NoIssues( }); //Wait before sending results - await Task.Delay(100); + await Task.Delay(200); completionSource.SetResult(new Revocable { Value = new Thing { Id = firstValue }, RevokeKeys = new[] { "revokeKey" } }); //Results should arive now @@ -152,17 +151,17 @@ public async Task MemoizeAsync_ExistingItemWasRefreshedByTtlAndReciviedRevoke_Af var cache = CreateCache(revokesSource); var memoizer = CreateMemoizer(cache); //To cause refresh in next call - await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings(refreshTimeSeconds:0)); + await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(refreshTimeSeconds:0)); dataSource.Received(1).ThingifyTaskRevokable("someString"); //New item - fetch from datasource - await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); dataSource.Received(2).ThingifyTaskRevokable("someString"); //Refresh task - fetch from datasource //Post revoke message revokesSource.PostMessageSynced("revokeKey"); //We want to test that item was removed from cache after revoke and that new item is fetched from datasource - await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); dataSource.Received(3).ThingifyTaskRevokable("someString"); //Revoke received and item removed from cache - fetch from datasource } @@ -175,7 +174,7 @@ public async Task MemoizeAsync_ExistingItemReceivedRevokeAndSettingIsKeepUsingRe var cache = CreateCache(revokesSource); var memoizer = CreateMemoizer(cache); - var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); result.Value.Id.ShouldBe(firstResult); dataSource.Received(1).ThingifyTaskRevokable("someString"); //New item - fetch from datasource @@ -183,7 +182,7 @@ public async Task MemoizeAsync_ExistingItemReceivedRevokeAndSettingIsKeepUsingRe revokesSource.PostMessageSynced("revokeKey"); //We want to test that revoked item is still in cache and returned - result = await(Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, + result = await(Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(revokedResponseBehavior: RevokedResponseBehavior.KeepUsingRevokedResponse)); result.Value.Id.ShouldBe(firstResult); dataSource.Received(1).ThingifyTaskRevokable("someString"); //Revoke received and item was not removed from cache - do not fetch from datasource @@ -199,7 +198,7 @@ public async Task MemoizeAsync_ExistingItemReceivedRevokeAndSettingIsTryFetchNew var cache = CreateCache(revokesSource); var memoizer = CreateMemoizer(cache); - var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); result.Value.Id.ShouldBe(firstResult); dataSource.Received(1).ThingifyTaskRevokable("someString"); //New item - fetch from datasource @@ -207,7 +206,7 @@ public async Task MemoizeAsync_ExistingItemReceivedRevokeAndSettingIsTryFetchNew revokesSource.PostMessageSynced("revokeKey"); //We want to test that revoked item is ignored and we fetch a new item from data source - result = await(Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, + result = await(Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(revokedResponseBehavior: RevokedResponseBehavior.TryFetchNewValueNextTimeOrUseOld)); result.Value.Id.ShouldBe(secondResult); dataSource.Received(2).ThingifyTaskRevokable("someString"); @@ -223,7 +222,7 @@ public async Task MemoizeAsync_ExistingItemReceivedRevokeAndCallAfterRevokeRetur var cache = CreateCache(revokesSource); var memoizer = CreateMemoizer(cache); - var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); result.Value.Id.ShouldBe(firstResult); dataSource.Received(1).ThingifyTaskRevokable("someString"); //New item - fetch from datasource @@ -231,7 +230,7 @@ public async Task MemoizeAsync_ExistingItemReceivedRevokeAndCallAfterRevokeRetur revokesSource.PostMessageSynced("revokeKey"); //We want to test that revoked item is returned (because data source response should be ignored) - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(revokedResponseBehavior: RevokedResponseBehavior.TryFetchNewValueNextTimeOrUseOld, responseKindsToCache: ResponseKinds.NonNullResponse, responseKindsToIgnore: ResponseKinds.NullResponse)); @@ -239,7 +238,7 @@ public async Task MemoizeAsync_ExistingItemReceivedRevokeAndCallAfterRevokeRetur dataSource.Received(2).ThingifyTaskRevokable("someString"); //tried to fetch from data source (and ignored) //Cached item is still revoked, so we do another call to data source and get a new valid response - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(revokedResponseBehavior: RevokedResponseBehavior.TryFetchNewValueNextTimeOrUseOld)); result.Value.Id.ShouldBe(secondResult); //get new value dataSource.Received(3).ThingifyTaskRevokable("someString"); @@ -255,7 +254,7 @@ public async Task MemoizeAsync_ExistingItemReceivedRevokeAndSettingIsTryFetchNew var cache = CreateCache(revokesSource); var memoizer = CreateMemoizer(cache); - var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); result.Value.Id.ShouldBe(firstResult); dataSource.Received(1).ThingifyTaskRevokable("someString"); //New item - fetch from datasource @@ -263,13 +262,13 @@ public async Task MemoizeAsync_ExistingItemReceivedRevokeAndSettingIsTryFetchNew revokesSource.PostMessageSynced("revokeKey"); //We want to test that revoked item is used and we fetch a new item from data source in the backround - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(revokedResponseBehavior: RevokedResponseBehavior.TryFetchNewValueInBackgroundNextTime)); result.Value.Id.ShouldBe(firstResult); //Use old cached value dataSource.Received(2).ThingifyTaskRevokable("someString"); //A backround call to the data source is made //After backround call is done, we should get new result - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(revokedResponseBehavior: RevokedResponseBehavior.TryFetchNewValueInBackgroundNextTime)); result.Value.Id.ShouldBe(secondResult); dataSource.Received(2).ThingifyTaskRevokable("someString"); //No additional data source call @@ -285,7 +284,7 @@ public async Task MemoizeAsync_ExistingItemReceivedRevokeAndCallAfterRevokeRetur var cache = CreateCache(revokesSource); var memoizer = CreateMemoizer(cache); - var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); result.Value.Id.ShouldBe(firstResult); dataSource.Received(1).ThingifyTaskRevokable("someString"); //New item - fetch from datasource @@ -293,7 +292,7 @@ public async Task MemoizeAsync_ExistingItemReceivedRevokeAndCallAfterRevokeRetur revokesSource.PostMessageSynced("revokeKey"); //We want to test that revoked item is used and we fetch a new item from data source in the backround - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(revokedResponseBehavior: RevokedResponseBehavior.TryFetchNewValueInBackgroundNextTime, responseKindsToCache: ResponseKinds.NonNullResponse, responseKindsToIgnore: ResponseKinds.NullResponse)); @@ -301,13 +300,13 @@ public async Task MemoizeAsync_ExistingItemReceivedRevokeAndCallAfterRevokeRetur dataSource.Received(2).ThingifyTaskRevokable("someString"); //A backround call to the data source is made //Backround call returned an ignored response, so we should get old cached value an issue another data source call (old item is still revoked) - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(revokedResponseBehavior: RevokedResponseBehavior.TryFetchNewValueInBackgroundNextTime)); result.Value.Id.ShouldBe(firstResult); dataSource.Received(3).ThingifyTaskRevokable("someString"); //Second backround call //Second backround call returned a new valid response and cached it. We should get cached value - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(revokedResponseBehavior: RevokedResponseBehavior.TryFetchNewValueInBackgroundNextTime)); result.Value.Id.ShouldBe(secondResult); dataSource.Received(3).ThingifyTaskRevokable("someString"); //No additional data source call @@ -383,11 +382,11 @@ public async Task MemoizeAsync_AfterRefreshRevokeKeysAreAddedToReverseIndexCorre var result2 = new Revocable { Value = new Thing { Id = "result2" }, RevokeKeys = new List{"x", "y"} }; dataSource.ThingifyTaskRevokable("someString").Returns(result1, result2); - await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings(refreshTimeSeconds: 0));//refresh in next call + await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(refreshTimeSeconds: 0));//refresh in next call cache.RevokeKeysCount.ShouldBe(1); cache.CacheKeyCount.ShouldBe(1); - await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); cache.CacheKeyCount.ShouldBe(2); cache.RevokeKeysCount.ShouldBe(2); } @@ -404,11 +403,11 @@ public async Task MemoizeAsync_AfterRefreshRevokeKeysAreRemovedFromReverseIndexC var result2 = new Revocable { Value = new Thing { Id = "result2" }, RevokeKeys = new List { "x" } }; dataSource.ThingifyTaskRevokable("someString").Returns(result1, result2); - await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings(refreshTimeSeconds: 0));//refresh in next call + await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(refreshTimeSeconds: 0));//refresh in next call cache.RevokeKeysCount.ShouldBe(2); cache.CacheKeyCount.ShouldBe(2); - await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); cache.CacheKeyCount.ShouldBe(1); cache.RevokeKeysCount.ShouldBe(1); } @@ -425,11 +424,11 @@ public async Task MemoizeAsync_AfterRefreshRevokeKeysArePreservedInReverseIndexC var result2 = new Revocable { Value = new Thing { Id = "result2" }, RevokeKeys = new List { "x", "y" } }; dataSource.ThingifyTaskRevokable("someString").Returns(result1, result2); - await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings(refreshTimeSeconds: 0));//refresh in next call + await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(refreshTimeSeconds: 0));//refresh in next call cache.RevokeKeysCount.ShouldBe(2); cache.CacheKeyCount.ShouldBe(2); - await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); cache.CacheKeyCount.ShouldBe(2); cache.RevokeKeysCount.ShouldBe(2); } @@ -447,10 +446,10 @@ public async Task MemoizeAsync_NotCachedCallWithoutRevokeShouldCacheDataSourceVa RecentlyRevokesCache.TryGetRecentlyRevokedTime(Arg.Any(), Arg.Any()).Returns((DateTime?)null); - var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); result.Value.Id.ShouldBe(dataSourceResult1.Value.Id); //call data source and get first value - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); result.Value.Id.ShouldBe(dataSourceResult1.Value.Id); //get cached value } @@ -469,19 +468,20 @@ public async Task MemoizeAsync_NotCachedCallWithIntefiringRevokeShouldMarkCacheV //first call to data source will receive a revoke!!! RecentlyRevokesCache.TryGetRecentlyRevokedTime(Arg.Any(), Arg.Any()).Returns(TimeFake.UtcNow, (DateTime?)null); - var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); result.Value.Id.ShouldBe(dataSourceResult1.Value.Id); //call data source and get first value //revoke received while in first call to data source - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); result.Value.Id.ShouldBe(dataSourceResult2.Value.Id); //call trigger a call to data source because value is stale and a new data source value is returned - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); result.Value.Id.ShouldBe(dataSourceResult2.Value.Id); //cached value is returned } [Test] + [Retry(5)] //Sometime fails on build server because of timing issues public async Task MemoizeAsync_RefreshWithoutRevokeShouldCacheNewValue() { var revokesSource = new OneTimeSynchronousSourceBlock(); @@ -495,19 +495,20 @@ public async Task MemoizeAsync_RefreshWithoutRevokeShouldCacheNewValue() RecentlyRevokesCache.TryGetRecentlyRevokedTime(Arg.Any(), Arg.Any()).Returns((DateTime?)null); - var refreshBehavior = RefreshBehavior.TryFetchNewValueOrUseOld; - //refresh in next call - var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings(refreshTimeSeconds: 0, refreshBehavior: refreshBehavior)); + var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(refreshTimeSeconds: 0));//refresh in next call result.Value.Id.ShouldBe(dataSourceResult1.Value.Id); //call data source and get first value - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings(refreshBehavior: refreshBehavior)); - result.Value.Id.ShouldBe(dataSourceResult2.Value.Id); //refresh triggered, get second value from data source and cache + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); + result.Value.Id.ShouldBe(dataSourceResult1.Value.Id); //refresh triggered in the backround, but cached (old) value is returned + + await Task.Delay(dataSourceDelay + 200); //wait for refresh to finish - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings(refreshBehavior: refreshBehavior)); - result.Value.Id.ShouldBe(dataSourceResult2.Value.Id); //return refreshed cached value + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); + result.Value.Id.ShouldBe(dataSourceResult2.Value.Id); //second data source value returned (refreshed) } [Test] + [Retry(5)] //Sometime fails on build server because of timing issues public async Task MemoizeAsync_RefreshWithIntefiringRevokeShouldMarkCacheValueAsStaleAndTriggerACallToDataSource() { var cache = CreateCache(new OneTimeSynchronousSourceBlock()); @@ -522,26 +523,26 @@ public async Task MemoizeAsync_RefreshWithIntefiringRevokeShouldMarkCacheValueAs //second call to data source will receive a revoke!!! RecentlyRevokesCache.TryGetRecentlyRevokedTime(Arg.Any(), Arg.Any()).Returns((DateTime?)null, TimeFake.UtcNow, (DateTime?)null); - var refreshBehavior = RefreshBehavior.TryFetchNewValueOrUseOld; - //refresh in next call - var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings(refreshTimeSeconds: 0, refreshBehavior: refreshBehavior)); + var result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings(refreshTimeSeconds: 0));//refresh in next call result.Value.Id.ShouldBe(dataSourceResult1.Value.Id); //call data source and get first value - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings(refreshBehavior: refreshBehavior)); - result.Value.Id.ShouldBe(dataSourceResult2.Value.Id); //refresh triggered, get second value + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); + result.Value.Id.ShouldBe(dataSourceResult1.Value.Id); //refresh triggered in the backround, but cached (old) value is returned + + //the backround refresh receives revoke while in call to remote service - //previous refresh received revoke while in call to remote service and marked item as stale + await Task.Delay(dataSourceDelay + 200); //wait for refresh to finish - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings(refreshBehavior: refreshBehavior)); + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); result.Value.Id.ShouldBe(dataSourceResult3.Value.Id); //because cached value is stale, another call to data source is triggered and its value is returned - result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings(refreshBehavior: refreshBehavior)); + result = await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); result.Value.Id.ShouldBe(dataSourceResult3.Value.Id); //latest refresh value was cached and returned } private async Task> CallWithMemoize(IMemoizer memoizer, IThingFrobber dataSource) { - return await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokabkle, new object[] { "someString" }, GetCachingSettings()); + return await (Task>)memoizer.Memoize(dataSource, ThingifyTaskRevokable, new object[] { "someString" }, GetCachingSettings()); } private static MetricsData GetMetricsData(string subContext) diff --git a/tests/Gigya.Microdot.UnitTests/Caching/AsyncMemoizerTests.cs b/tests/Gigya.Microdot.UnitTests/Caching/AsyncMemoizerTests.cs index 7d8129ad..5b79fc94 100644 --- a/tests/Gigya.Microdot.UnitTests/Caching/AsyncMemoizerTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Caching/AsyncMemoizerTests.cs @@ -1,12 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Reflection; -using System.Reflection.Emit; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; -using Gigya.Common.Contracts.Attributes; +using Gigya.Common.Contracts.Attributes; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Fakes; using Gigya.Microdot.ServiceDiscovery.Config; @@ -14,12 +6,15 @@ using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.SystemWrappers; using Metrics; - using NSubstitute; -using NSubstitute.ExceptionExtensions; using NUnit.Framework; - using Shouldly; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; // ReSharper disable ConsiderUsingConfigureAwait (not relevant for tests) namespace Gigya.Microdot.UnitTests.Caching @@ -27,7 +22,7 @@ namespace Gigya.Microdot.UnitTests.Caching // Calls to NSubstitute's .Received() method on async methods generate this warning. - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + [TestFixture,Parallelizable(ParallelScope.Default)] public class AsyncMemoizerTests { private MethodInfo ThingifyInt { get; } = typeof(IThingFrobber).GetMethod(nameof(IThingFrobber.ThingifyInt)); @@ -538,7 +533,19 @@ public async Task MemoizeAsync_MultipleFailingCallsWithSuppressCaching_ThrowExce for (int i = 0; i < 10; i++) //10 calls to data source { var task = (Task)memoizer.Memoize(dataSource, ThingifyTaskThing, new object[] { "someString" }, GetCachingSettings()); - task.ShouldThrow(); + + Exception thrownException = null; + + try + { + await task; + } + catch (Exception ex) + { + thrownException = ex; + } + + Assert.NotNull(thrownException); } } @@ -847,24 +854,27 @@ public async Task MemoizeAsync_BackgroundRefreshFails_TTLNotExtended() IMemoizer memoizer = new AsyncMemoizer(new AsyncCache(new ConsoleLog(), Metric.Context("AsyncCache"), new DateTimeImpl(), new EmptyRevokeListener(), revokeCache), new MetadataProvider(), Metric.Context("Tests")); // T = 0s. No data in cache, should retrieve value from source (870). - (await (Task)memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetCachingSettings(5, 1, 100))).Id.ShouldBe(firstValue); + const int ExpirationTime = 10; + const int watiTime = 4; - await Task.Delay(TimeSpan.FromSeconds(2)); + (await (Task)memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetCachingSettings(ExpirationTime, 1, 100))).Id.ShouldBe(firstValue); + + await Task.Delay(TimeSpan.FromSeconds(watiTime)); // T = 2s. Past refresh time (1s), this triggers refresh in background (that will fail), should get existing value (870) - (await (Task)memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetCachingSettings(5, 1, 100))).Id.ShouldBe(firstValue); + (await (Task)memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetCachingSettings(ExpirationTime, 1, 100))).Id.ShouldBe(firstValue); - await Task.Delay(TimeSpan.FromSeconds(2)); + await Task.Delay(TimeSpan.FromSeconds(watiTime)); // T = 4s. Background refresh failed, but TTL (5s) not expired yet. Should still give old value (870) but won't // trigger additional background refresh because of very long FailedRefreshDelay that was spcified (100s). - (await (Task)memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetCachingSettings(5, 1, 100))).Id.ShouldBe(firstValue); + (await (Task)memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetCachingSettings(ExpirationTime, 1, 100))).Id.ShouldBe(firstValue); - await Task.Delay(TimeSpan.FromSeconds(2)); + await Task.Delay(TimeSpan.FromSeconds(watiTime)); // T = 6s. We're past the original TTL (5s), and refresh task failed. Items should have been evicted from cache by now // according to 5s expiery from T=0s, not from T=2s of the failed refresh. New item (1002) should come in. - (await (Task)memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetCachingSettings(5, 1))).Id.ShouldBe(secondValue); + (await (Task)memoizer.Memoize(dataSource, ThingifyTaskThing, args, GetCachingSettings(ExpirationTime, 1))).Id.ShouldBe(secondValue); dataSource.Received(3).ThingifyTaskThing(Arg.Any()); } diff --git a/tests/Gigya.Microdot.UnitTests/Caching/CachingProxyTests.cs b/tests/Gigya.Microdot.UnitTests/Caching/CachingProxyTests.cs index 336c6002..49926c70 100644 --- a/tests/Gigya.Microdot.UnitTests/Caching/CachingProxyTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Caching/CachingProxyTests.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; +using Gigya.Common.Contracts.Attributes; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces; @@ -16,11 +13,15 @@ using NSubstitute; using NUnit.Framework; using Shouldly; -using Gigya.Common.Contracts.Attributes; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.UnitTests.Caching { - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + [TestFixture,NonParallelizable] public class CachingProxyTests { public const int AttRefreshTimeInMinutes = 2; @@ -169,66 +170,59 @@ public async Task CallWhileRefreshShouldReturnOldValueAndAfterRefreshTheNewValue [Test] public async Task DoNotExtendExpirationWhenReadFromCache_CallAfterCacheItemIsExpiredShouldTriggerACallToTheService() { - try - { - TimeSpan expectedExpirationTime = TimeSpan.FromSeconds(1); - await SetCachingPolicyConfig(new[] { "ExpirationTime", expectedExpirationTime.ToString() }, - new[] { "ExpirationBehavior", "DoNotExtendExpirationWhenReadFromCache" }); + TimeSpan expectedExpirationTime = TimeSpan.FromSeconds(1); + await SetCachingPolicyConfig(new[] { "ExpirationTime", expectedExpirationTime.ToString() }, + new[] { "ExpirationBehavior", "DoNotExtendExpirationWhenReadFromCache" }); - //First call to service - value is cached - var result = await _proxy.CallService(); - result.ShouldBe(FirstResult); + //First call to service - value is cached + var result = await _proxy.CallService(); + result.ShouldBe(FirstResult); - _serviceResult = SecondResult; + _serviceResult = SecondResult; - //No service call - cached value is used - result = await _proxy.CallService(); - result.ShouldBe(FirstResult); + //No service call - cached value is used + result = await _proxy.CallService(); + result.ShouldBe(FirstResult); - //Wait for item to be expired - await Task.Delay(1500); + //Wait for item to be expired + await Task.Delay(2500); - //Prev item is expired - make a call to the service - result = await _proxy.CallService(); - result.ShouldBe(SecondResult); - } - catch (Exception e) - { - Assert.Inconclusive("Test sometimes fail in build server because of timing issues. Please run locally"); - } + //Prev item is expired - make a call to the service + result = await _proxy.CallService(); + result.ShouldBe(SecondResult); } - [Test] + [Test,Retry(5)] public async Task ExtendExpirationWhenReadFromCache_CallAfterCacheItemIsExpiredAndExtendedShouldNotTriggerACallToTheService() { - try - { - TimeSpan expectedExpirationTime = TimeSpan.FromSeconds(3); - await SetCachingPolicyConfig(new[] { "ExpirationTime", expectedExpirationTime.ToString() }, - new[] { "ExpirationBehavior", "ExtendExpirationWhenReadFromCache" }); + TimeSpan expectedExpirationTime = TimeSpan.FromSeconds(3); + await SetCachingPolicyConfig(new[] { "ExpirationTime", expectedExpirationTime.ToString() }, + new[] { "ExpirationBehavior", "ExtendExpirationWhenReadFromCache" }); - //First call to service - value is cached - var result = await _proxy.CallService(); - result.ShouldBe(FirstResult); + //First call to service - value is cached + var result = await _proxy.CallService(); + result.ShouldBe(FirstResult); - _serviceResult = SecondResult; + _serviceResult = SecondResult; - //Time has passed, but expiration has not reached - await Task.Delay(1000); + //Time has passed, but expiration has not reached + await Task.Delay(1000); - //No service call - cached value is used and expiration is extended - result = await _proxy.CallService(); - result.ShouldBe(FirstResult); + //No service call - cached value is used and expiration is extended + result = await _proxy.CallService(); + result.ShouldBe(FirstResult); - //Additional time has passed (beyond the expectedExpirationTime) - await Task.Delay(2100); + //Additional time has passed (beyond the expectedExpirationTime) + await Task.Delay(2100); - //Prev item is not expired (expiration was extended) - no service call - result = await _proxy.CallService(); + //Prev item is not expired (expiration was extended) - no service call + result = await _proxy.CallService(); + try + { result.ShouldBe(FirstResult); } - catch (ShouldAssertException e) + catch (Exception e) { Assert.Inconclusive("Test sometimes fail in build server because of timing issues. Please run locally"); } @@ -446,10 +440,12 @@ public async Task CachedDataShouldBeRevoked() await ResultlRevocableServiceShouldBe(FirstResult, key); _serviceResult = SecondResult; await ResultlRevocableServiceShouldBe(FirstResult, key, "Result should have been cached"); + var eventReceivedResult = _revokeListener.RevokeSource.WhenEventReceived(TimeSpan.FromMinutes(1)); await _cacheRevoker.Revoke(key); - _revokeListener.RevokeSource.WhenEventReceived(TimeSpan.FromMinutes(1)); + await eventReceivedResult; + Console.WriteLine($"event received result :" + eventReceivedResult.Result); await Task.Delay(100); - await ResultlRevocableServiceShouldBe(SecondResult, key, "Result shouldn't have been cached"); + await ResultlRevocableServiceShouldBe(SecondResult, key, "Result shouldn't have been cached", retry:3); } [Test] @@ -551,10 +547,29 @@ private async Task ResultShouldBe(string expectedResult, string message = null, result.ShouldBe(expectedResult, message); } - private async Task ResultlRevocableServiceShouldBe(string expectedResult,string key ,string message = null) + private async Task ResultlRevocableServiceShouldBe(string expectedResult,string key ,string message = null, int retry=1) { - var result = await _proxy.CallRevocableService(key); - result.Value.ShouldBe(expectedResult, message); + while (retry-- > 0) + { + var result = await _proxy.CallRevocableService(key); + + try + { + result.Value.ShouldBe(expectedResult, message); + return; + } + catch + { + if (retry == 0) + { + Debugger.Break(); + throw; + } + await Task.Delay(100); + + } + + } } } diff --git a/tests/Gigya.Microdot.UnitTests/Caching/Host/CachingProxyTests.cs b/tests/Gigya.Microdot.UnitTests/Caching/Host/CachingProxyTests.cs index 9284624e..46557d27 100644 --- a/tests/Gigya.Microdot.UnitTests/Caching/Host/CachingProxyTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Caching/Host/CachingProxyTests.cs @@ -1,5 +1,6 @@ using Gigya.Microdot.Common.Tests; using Gigya.Microdot.SharedLogic; +using Gigya.Microdot.SharedLogic.HttpService; using Gigya.Microdot.Testing.Shared.Service; using NUnit.Framework; using Shouldly; @@ -7,9 +8,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.SharedLogic.HttpService; -using Gigya.Microdot.Hosting.Environment; namespace Gigya.Microdot.UnitTests.Caching.Host { diff --git a/tests/Gigya.Microdot.UnitTests/Caching/Host/ISlowService.cs b/tests/Gigya.Microdot.UnitTests/Caching/Host/ISlowService.cs index b9ddbdc3..482fb434 100644 --- a/tests/Gigya.Microdot.UnitTests/Caching/Host/ISlowService.cs +++ b/tests/Gigya.Microdot.UnitTests/Caching/Host/ISlowService.cs @@ -1,8 +1,8 @@ -using System; +using Gigya.Common.Contracts.Attributes; +using Gigya.Common.Contracts.HttpService; +using System; using System.Collections.Generic; using System.Threading.Tasks; -using Gigya.Common.Contracts.Attributes; -using Gigya.Common.Contracts.HttpService; namespace Gigya.Microdot.UnitTests.Caching.Host { diff --git a/tests/Gigya.Microdot.UnitTests/Caching/IThingFrobber.cs b/tests/Gigya.Microdot.UnitTests/Caching/IThingFrobber.cs index 1ee9ac11..83aa7bb6 100644 --- a/tests/Gigya.Microdot.UnitTests/Caching/IThingFrobber.cs +++ b/tests/Gigya.Microdot.UnitTests/Caching/IThingFrobber.cs @@ -1,10 +1,9 @@ -using System.Collections.Generic; +using Gigya.Common.Contracts.Attributes; +using Gigya.ServiceContract.HttpService; +using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Threading.Tasks; -using Gigya.Common.Contracts.Attributes; -using Gigya.ServiceContract.HttpService; - namespace Gigya.Microdot.UnitTests.Caching { public interface IThingFrobber diff --git a/tests/Gigya.Microdot.UnitTests/Caching/RecentlyRevokesCacheTests.cs b/tests/Gigya.Microdot.UnitTests/Caching/RecentlyRevokesCacheTests.cs index b686f38d..86bec42f 100644 --- a/tests/Gigya.Microdot.UnitTests/Caching/RecentlyRevokesCacheTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Caching/RecentlyRevokesCacheTests.cs @@ -1,14 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Gigya.Microdot.Interfaces.Logging; +using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.ServiceProxy.Caching; using Metrics; -using NUnit.Framework; using NSubstitute; +using NUnit.Framework; +using System; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Caching { diff --git a/tests/Gigya.Microdot.UnitTests/Configuration/Benchmark/ConfigBenchmarkTest.cs b/tests/Gigya.Microdot.UnitTests/Configuration/Benchmark/ConfigBenchmarkTest.cs index f0358074..270d741a 100644 --- a/tests/Gigya.Microdot.UnitTests/Configuration/Benchmark/ConfigBenchmarkTest.cs +++ b/tests/Gigya.Microdot.UnitTests/Configuration/Benchmark/ConfigBenchmarkTest.cs @@ -1,14 +1,10 @@ -using System; -using System.Diagnostics; -using System.Net; -using System.Threading.Tasks; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; -using Gigya.Microdot.Interfaces.Configuration; -using Gigya.Microdot.Logging.NLog; +using Gigya.Microdot.Logging.NLog; using Gigya.Microdot.Ninject; using Ninject; using NUnit.Framework; +using System; +using System.Diagnostics; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Configuration.Benchmark { @@ -20,8 +16,6 @@ public class ConfigBenchmarkTest [OneTimeSetUp] public void SetUp() { - - MicrodotInitializer microdotInitializer = new MicrodotInitializer( "", new NLogModule(), kernel => @@ -30,7 +24,7 @@ public void SetUp() _testingKernel = microdotInitializer.Kernel; } - [TearDown] + [OneTimeTearDown] public void Teardown() { _testingKernel.Dispose(); @@ -42,11 +36,13 @@ public void ConfigCreatorFuncObjectEvaluationBenchmark() int magicNumber = 2000000; int maxTimeInSec = 1; - ParallelOptions pOptions = new ParallelOptions(); - pOptions.MaxDegreeOfParallelism = 4; + ParallelOptions pOptions = new ParallelOptions + { + MaxDegreeOfParallelism = 4 + }; ConfigCreatorFuncObject configFunc = _testingKernel.Get(); - configFunc.GetConfig()(); + configFunc.GetConfig(); EvaluateFunc(configFunc.GetConfig(), magicNumber, pOptions, maxTimeInSec); } diff --git a/tests/Gigya.Microdot.UnitTests/Configuration/Benchmark/ConfigCreator.cs b/tests/Gigya.Microdot.UnitTests/Configuration/Benchmark/ConfigCreator.cs index 468e970a..9466b89e 100644 --- a/tests/Gigya.Microdot.UnitTests/Configuration/Benchmark/ConfigCreator.cs +++ b/tests/Gigya.Microdot.UnitTests/Configuration/Benchmark/ConfigCreator.cs @@ -1,6 +1,6 @@ -using System; +using Gigya.Microdot.ServiceDiscovery.Config; +using System; using System.Threading.Tasks.Dataflow; -using Gigya.Microdot.ServiceDiscovery.Config; namespace Gigya.Microdot.UnitTests.Configuration.Benchmark { diff --git a/tests/Gigya.Microdot.UnitTests/Configuration/BusSettings.cs b/tests/Gigya.Microdot.UnitTests/Configuration/BusSettings.cs index c36ce1ed..d92eaf4e 100644 --- a/tests/Gigya.Microdot.UnitTests/Configuration/BusSettings.cs +++ b/tests/Gigya.Microdot.UnitTests/Configuration/BusSettings.cs @@ -1,10 +1,8 @@ -using System; +using Gigya.Microdot.Interfaces.Configuration; +using System; using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; - -using Gigya.Microdot.Interfaces.Configuration; - namespace Gigya.Microdot.UnitTests.Configuration { public enum MessageFormat diff --git a/tests/Gigya.Microdot.UnitTests/Configuration/ConfigCollectionProperties.cs b/tests/Gigya.Microdot.UnitTests/Configuration/ConfigCollectionProperties.cs index c95d8366..9941d76c 100644 --- a/tests/Gigya.Microdot.UnitTests/Configuration/ConfigCollectionProperties.cs +++ b/tests/Gigya.Microdot.UnitTests/Configuration/ConfigCollectionProperties.cs @@ -1,14 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Gigya.Microdot.Interfaces; -using Gigya.Microdot.Interfaces.Configuration; +using Gigya.Microdot.Interfaces; using Gigya.Microdot.SharedLogic.Exceptions; using Ninject; using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Linq; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Configuration { diff --git a/tests/Gigya.Microdot.UnitTests/Configuration/ConfigListProperties.cs b/tests/Gigya.Microdot.UnitTests/Configuration/ConfigListProperties.cs index 61dc02e6..ef3e527e 100644 --- a/tests/Gigya.Microdot.UnitTests/Configuration/ConfigListProperties.cs +++ b/tests/Gigya.Microdot.UnitTests/Configuration/ConfigListProperties.cs @@ -1,14 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Gigya.Microdot.Interfaces; -using Gigya.Microdot.Interfaces.Configuration; +using Gigya.Microdot.Interfaces; using Gigya.Microdot.SharedLogic.Exceptions; using Ninject; using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Linq; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Configuration { diff --git a/tests/Gigya.Microdot.UnitTests/Configuration/ConfigTestBase.cs b/tests/Gigya.Microdot.UnitTests/Configuration/ConfigTestBase.cs index 9e733b21..dea00eb0 100644 --- a/tests/Gigya.Microdot.UnitTests/Configuration/ConfigTestBase.cs +++ b/tests/Gigya.Microdot.UnitTests/Configuration/ConfigTestBase.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; +using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.Interfaces.SystemWrappers; @@ -13,6 +7,7 @@ using Gigya.Microdot.UnitTests.Caching.Host; using Ninject; using NSubstitute; +using System.Collections.Generic; namespace Gigya.Microdot.UnitTests.Configuration { diff --git a/tests/Gigya.Microdot.UnitTests/Configuration/HostConfigurationSources.cs b/tests/Gigya.Microdot.UnitTests/Configuration/HostConfigurationSources.cs index f108720c..a09a0229 100644 --- a/tests/Gigya.Microdot.UnitTests/Configuration/HostConfigurationSources.cs +++ b/tests/Gigya.Microdot.UnitTests/Configuration/HostConfigurationSources.cs @@ -1,7 +1,6 @@ using Gigya.Microdot.Hosting.Environment; using NUnit.Framework; using System; -using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; diff --git a/tests/Gigya.Microdot.UnitTests/Configuration/IConfigObjectRebindTest.cs b/tests/Gigya.Microdot.UnitTests/Configuration/IConfigObjectRebindTest.cs index 756e64cc..707ff294 100644 --- a/tests/Gigya.Microdot.UnitTests/Configuration/IConfigObjectRebindTest.cs +++ b/tests/Gigya.Microdot.UnitTests/Configuration/IConfigObjectRebindTest.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks.Dataflow; -using Gigya.Microdot.Configuration.Objects; +using Gigya.Microdot.Configuration.Objects; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Ninject; @@ -8,6 +6,8 @@ using Ninject; using NSubstitute; using NUnit.Framework; +using System; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.UnitTests.Configuration { diff --git a/tests/Gigya.Microdot.UnitTests/Configuration/MasterConfigParserTests.cs b/tests/Gigya.Microdot.UnitTests/Configuration/MasterConfigParserTests.cs index 91243d2f..3d325f5a 100644 --- a/tests/Gigya.Microdot.UnitTests/Configuration/MasterConfigParserTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Configuration/MasterConfigParserTests.cs @@ -1,19 +1,15 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.Common.Tests; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Configuration; using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic; using NSubstitute; - using NUnit.Framework; - using Shouldly; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; namespace Gigya.Microdot.UnitTests.Configuration { @@ -71,17 +67,6 @@ public void AllPathExists_AllEnvironmentVariablesExists_EnvironmentExceptionExpe }, expected); } - - [Test] - [Ignore("Test this in new config system.")] - public void AllPathExists_NoEnvironmentVariablesExists_EnvironmentExceptionExpected() - { - Action act = () => BaseTest(new Dictionary { { "ENV", null }, { "ZONE", null } }, new ConfigFileDeclaration[0]); - - act.ShouldThrow() - .Message.ShouldContain("Some environment variables are not defined, please add them"); - } - [Test] [TestCase("Not a JSON", TestName = "Not a JSON file")] [TestCase(@"[{Pattern: './*.config', Priority: 1 }", TestName = "Missing ]")] diff --git a/tests/Gigya.Microdot.UnitTests/Configuration/TypedConfigTest.cs b/tests/Gigya.Microdot.UnitTests/Configuration/TypedConfigTest.cs index b394a599..8c2e11c6 100644 --- a/tests/Gigya.Microdot.UnitTests/Configuration/TypedConfigTest.cs +++ b/tests/Gigya.Microdot.UnitTests/Configuration/TypedConfigTest.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; -using Gigya.Microdot.Configuration; +using Gigya.Microdot.Configuration; using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.SharedLogic.Exceptions; @@ -11,8 +6,12 @@ using Gigya.Microdot.Testing.Shared; using Ninject; using NUnit.Framework; - using Shouldly; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.UnitTests.Configuration { @@ -94,14 +93,14 @@ public async Task OnlyValueCausesNotification() configFromNotification = null; configItems.SetValue("BusSettings.MessageFormatNullable", "Invalid"); eventSource.RaiseChangeEvent(); - await Task.Delay(100); + await Task.Delay(200); // Since the config is invalid, the config object isn't updated and the event wasn't triggered configFromNotification.ShouldBeNull(); configFromNotification = null; configItems.SetValue("BusSettings.MessageFormatNullable", "Json"); eventSource.RaiseChangeEvent(); - await Task.Delay(100); + await Task.Delay(200); // Since the config is valid AND a property changed (Avro --> Json), the config object was updated and an event was triggered configFromNotification.ShouldNotBeNull(); } @@ -137,7 +136,7 @@ public async Task NotificationChange() var eventSource = infraKernel.Get(); configItems.SetValue("BusSettings.TopicName", "Changed"); eventSource.RaiseChangeEvent(); - await Task.Delay(100); + await Task.Delay(200); configFromNotification.ShouldNotBeNull(); configFromNotification.TopicName.ShouldBe("Changed"); infraKernel.Dispose(); @@ -168,7 +167,7 @@ public async Task ObjectValuesChangedAfterUpdate() configItems.SetValue("BusSettings.TopicName","NewValue"); eventSource.RaiseChangeEvent(); - await Task.Delay(100); + await Task.Delay(200); busSettings = extractor(); busSettings.TopicName.ShouldBe("NewValue"); @@ -261,7 +260,7 @@ public async Task ChangeToBrokenConfiguration() configItems.SetValue("BusSettings.RequestTimeoutInMs", "NotNumber"); eventSource.RaiseChangeEvent(); - await Task.Delay(100); + await Task.Delay(200); //Make sure last good configuration is returned. busSettings = extractor(); diff --git a/tests/Gigya.Microdot.UnitTests/Configuration/Verificator/VerificatorTests.cs b/tests/Gigya.Microdot.UnitTests/Configuration/Verificator/VerificatorTests.cs index 974a5a8d..3698cc3a 100644 --- a/tests/Gigya.Microdot.UnitTests/Configuration/Verificator/VerificatorTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Configuration/Verificator/VerificatorTests.cs @@ -1,19 +1,12 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Configuration; +using Gigya.Microdot.Configuration; using Gigya.Microdot.Interfaces; -using Gigya.Microdot.Interfaces.Configuration; -using Gigya.Microdot.Interfaces.SystemWrappers; -using Gigya.Microdot.Ninject; -using Gigya.Microdot.SharedLogic; -using Gigya.Microdot.UnitTests.Caching.Host; - using Ninject; using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Linq; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Configuration.Verificator { @@ -73,12 +66,6 @@ public void WhenConfigIsNotValidXmlShouldAddFailure() Console.WriteLine(result); } - [Test] - [Ignore("just to be able to search in tests tree")] - public void VerificatorTest() - { - } - [Test] [Description("check we recognize a violation of annotated property in config object")] public void WhenDataAnnotationViolatedShouldAddFailure() diff --git a/tests/Gigya.Microdot.UnitTests/Configuration/Verificator/VerifiedConfigs.cs b/tests/Gigya.Microdot.UnitTests/Configuration/Verificator/VerifiedConfigs.cs index c8147e22..ccc93acd 100644 --- a/tests/Gigya.Microdot.UnitTests/Configuration/Verificator/VerifiedConfigs.cs +++ b/tests/Gigya.Microdot.UnitTests/Configuration/Verificator/VerifiedConfigs.cs @@ -1,9 +1,9 @@ -using System.ComponentModel.DataAnnotations; -using Gigya.Microdot.Interfaces.Configuration; +using Gigya.Microdot.Interfaces.Configuration; +using System.ComponentModel.DataAnnotations; namespace Gigya.Microdot.UnitTests.Configuration.Verificator { - [ConfigurationRoot("VerifiedConfig1", RootStrategy.ReplaceClassNameWithPath)] + [ConfigurationRoot("VerifiedConfig1", RootStrategy.ReplaceClassNameWithPath)] public class VerifiedConfig1 : IConfigObject { /// diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/ConfigNodeSourceTests.cs b/tests/Gigya.Microdot.UnitTests/Discovery/ConfigNodeSourceTests.cs index c3e018d8..fe4ed2a7 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/ConfigNodeSourceTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/ConfigNodeSourceTests.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery; @@ -14,6 +11,9 @@ using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Discovery diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/ConsulClientMock.cs b/tests/Gigya.Microdot.UnitTests/Discovery/ConsulClientMock.cs index 962453bb..6df468ef 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/ConsulClientMock.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/ConsulClientMock.cs @@ -1,20 +1,22 @@ +using Gigya.Microdot.ServiceDiscovery; using System; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; -using Gigya.Microdot.ServiceDiscovery; namespace Gigya.Microdot.UnitTests.Discovery { public sealed class ConsulClientMock: IConsulClient { - private readonly BufferBlock _resultChanged = new BufferBlock(); + private readonly BroadcastBlock _resultChanged = new BroadcastBlock(null); private EndPointsResult _lastResult; private bool _initialized = false; private bool _disposed = false; private readonly object _lastResultLocker = new object(); private Timer _resultsTimer; + public TaskCompletionSource InitFinished { get; } = new TaskCompletionSource(); + public void SetResult(EndPointsResult result) { lock (_lastResultLocker) @@ -45,12 +47,16 @@ public async Task Init() if (_lastResult != null) _resultChanged.Post(_lastResult); - _resultsTimer = new Timer(_ => + if (_resultsTimer == null) { + _resultsTimer = new Timer(_ => + { _resultChanged.Post(_lastResult); - }, null, 100, Timeout.Infinite); + }, null, 100, 100); + } } + InitFinished.SetResult(true); } public EndPointsResult Result { get; set; } = new EndPointsResult(); diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/ConsulClientTests.cs b/tests/Gigya.Microdot.UnitTests/Discovery/ConsulClientTests.cs index b7a5bdda..9cbd9fd3 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/ConsulClientTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/ConsulClientTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery; using Gigya.Microdot.ServiceDiscovery.Config; @@ -12,6 +10,8 @@ using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Discovery { diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/ConsulDiscoveryMasterFallBackTest.cs b/tests/Gigya.Microdot.UnitTests/Discovery/ConsulDiscoveryMasterFallBackTest.cs index d410634a..8a688268 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/ConsulDiscoveryMasterFallBackTest.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/ConsulDiscoveryMasterFallBackTest.cs @@ -1,9 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; @@ -16,16 +10,21 @@ using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.UnitTests.Discovery { - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + [TestFixture,NonParallelizable] public class ConsulDiscoveryMasterFallBackTest { private const string ServiceVersion = "1.2.30.1234"; - private string _serviceName; - private const string MASTER_ENVIRONMENT = "prod"; - private const string ORIGINATING_ENVIRONMENT = "fake_env"; + private const string MasterEnvironment = "prod"; + private const string OriginatingEnvironment = "fake_env"; private readonly TimeSpan _timeOut = TimeSpan.FromSeconds(5); private Dictionary _configDic; private TestingKernel _unitTestingKernel; @@ -33,18 +32,16 @@ public class ConsulDiscoveryMasterFallBackTest private IEnvironment _environment; private ManualConfigurationEvents _configRefresh; private IDateTime _dateTimeMock; - private int id; private const int Repeat = 1; [SetUp] public void SetUp() { - - _serviceName = $"ServiceName{++id}"; + _environment = Substitute.For(); _environment.Zone.Returns("il3"); - _environment.DeploymentEnvironment.Returns(ORIGINATING_ENVIRONMENT); + _environment.DeploymentEnvironment.Returns(OriginatingEnvironment); _configDic = new Dictionary {{"Discovery.EnvironmentFallbackEnabled", "true"}}; _unitTestingKernel = new TestingKernel(k => @@ -56,7 +53,7 @@ public void SetUp() k.Rebind>().ToMethod(_ => (s => _consulClient[s])); _dateTimeMock = Substitute.For(); - _dateTimeMock.Delay(Arg.Any()).Returns(c => Task.Delay(TimeSpan.FromMilliseconds(100))); + _dateTimeMock.Delay(Arg.Any()).Returns(async c => await Task.Delay(c.Arg())); k.Rebind().ToConstant(_dateTimeMock); }, _configDic); _configRefresh = _unitTestingKernel.Get(); @@ -80,8 +77,8 @@ private void SetupConsulClientMocks() { _consulClient = new Dictionary(); - CreateConsulMock(MasterService); - CreateConsulMock(OriginatingService); + CreateConsulMock(MasterService(TestContext.CurrentContext.Test.Name)); + CreateConsulMock(OriginatingService(TestContext.CurrentContext.Test.Name)); } @@ -111,76 +108,144 @@ public void TearDown() [Repeat(Repeat)] public async Task QueryNotDefinedShouldFallBackToMaster() { - SetMockToReturnHost(MasterService); - SetMockToReturnServiceNotDefined(OriginatingService); - var nextHost = GetServiceDiscovey().GetNextHost(); - nextHost.Result.HostName.ShouldBe(MasterService); + SetMockToReturnHost(MasterService()); + SetMockToReturnServiceNotDefined(OriginatingService()); + + var discovery = GetServiceDiscovery(); + await discovery.GetAllEndPoints(); + + var timeout = Task.Delay(TimeSpan.FromSeconds(10)); + var initsFinished = Task.WhenAny(_consulClient[MasterService()].InitFinished.Task, + _consulClient[OriginatingService()].InitFinished.Task); + + Assert.AreNotEqual(timeout, await Task.WhenAny(timeout, initsFinished)); + + SetMockToReturnHost(MasterService()); + SetMockToReturnServiceNotDefined(OriginatingService()); + + var nextHost = await GetServiceDiscovery().GetNextHost(); + nextHost.HostName.ShouldBe(MasterService()); } [Test] [Repeat(Repeat)] public async Task FallBackToMasterShouldNotHaveOriginatingServiceHealth() { - SetMockToReturnHost(MasterService); - SetMockToReturnServiceNotDefined(OriginatingService); - var nextHost = await GetServiceDiscovey().GetNextHost(); - HealthChecks.GetStatus().Results.Single(_ => _.Name == MasterService).Check.IsHealthy.ShouldBeTrue(); - HealthChecks.GetStatus().Results.ShouldNotContain(_ => _.Name == OriginatingService); + var serviceName = GetServiceName(); + + SetMockToReturnHost(MasterService()); + SetMockToReturnServiceNotDefined(OriginatingService()); + + var discovery = GetServiceDiscovery(); + await discovery.GetAllEndPoints(); + + var timeout = Task.Delay(TimeSpan.FromSeconds(10)); + var initsFinished = Task.WhenAny(_consulClient[MasterService()].InitFinished.Task, + _consulClient[OriginatingService()].InitFinished.Task); + + Assert.AreNotEqual(timeout, await Task.WhenAny(timeout, initsFinished)); + + SetMockToReturnHost(MasterService()); + SetMockToReturnServiceNotDefined(OriginatingService()); + + await GetServiceDiscovery().GetNextHost(); + HealthChecks.GetStatus().Results.Single(_ => _.Name == MasterService()).Check.IsHealthy.ShouldBeTrue(); + HealthChecks.GetStatus().Results.ShouldNotContain(_ => _.Name == OriginatingService(serviceName)); } [Test] [Repeat(Repeat)] public async Task NoFallBackShouldNotHavMasterServiceHealth() { - SetMockToReturnServiceNotDefined(MasterService); - SetMockToReturnHost(OriginatingService); - var nextHost = await GetServiceDiscovey().GetNextHost(); - HealthChecks.GetStatus().Results.Single(_ => _.Name == OriginatingService).Check.IsHealthy.ShouldBeTrue(); - HealthChecks.GetStatus().Results.ShouldNotContain(_ => _.Name == MasterService); + var serviceName = GetServiceName(); + + SetMockToReturnServiceNotDefined(MasterService()); + SetMockToReturnHost(OriginatingService()); + + var discovery = GetServiceDiscovery(); + await discovery.GetAllEndPoints(); + + var timeout = Task.Delay(TimeSpan.FromSeconds(10)); + var initsFinished = Task.WhenAny(_consulClient[MasterService()].InitFinished.Task, + _consulClient[OriginatingService()].InitFinished.Task); + + Assert.AreNotEqual(timeout, await Task.WhenAny(timeout, initsFinished)); + + SetMockToReturnServiceNotDefined(MasterService()); + SetMockToReturnHost(OriginatingService()); + + await GetServiceDiscovery().GetNextHost(); + HealthChecks.GetStatus().Results.Single(_ => _.Name == OriginatingService()).Check.IsHealthy.ShouldBeTrue(); + HealthChecks.GetStatus().Results.ShouldNotContain(_ => _.Name == MasterService(serviceName)); } [Test] [Repeat(Repeat)] - public async Task CreateServiceDiscoveyWithoutGetNextHostNoServiceHealthShouldAppear() + public void CreateServiceDiscoveryWithoutGetNextHostNoServiceHealthShouldAppear() { - SetMockToReturnHost(MasterService); - SetMockToReturnServiceNotDefined(OriginatingService); - var serviceDiscovey = GetServiceDiscovey(); - HealthChecks.GetStatus().Results.ShouldNotContain(_ => _.Name == MasterService); - HealthChecks.GetStatus().Results.ShouldNotContain(_ => _.Name == OriginatingService); + var serviceName = GetServiceName(); + + SetMockToReturnHost(MasterService()); + SetMockToReturnServiceNotDefined(OriginatingService()); + GetServiceDiscovery(); + HealthChecks.GetStatus().Results.ShouldNotContain(_ => _.Name == MasterService(serviceName)); + HealthChecks.GetStatus().Results.ShouldNotContain(_ => _.Name == OriginatingService(serviceName)); } [Test] [Repeat(Repeat)] public async Task ScopeZoneShouldUseServiceNameAsConsoleQuery() { - _unitTestingKernel.Get>()().Services[_serviceName].Scope = ServiceScope.Zone; - SetMockToReturnHost(_serviceName); - var nextHost = GetServiceDiscovey().GetNextHost(); - (await nextHost).HostName.ShouldBe(_serviceName); + var serviceName = GetServiceName(); + + _unitTestingKernel.Get>()().Services[serviceName].Scope = ServiceScope.Zone; + SetMockToReturnHost(serviceName); + + var discovery = GetServiceDiscovery(); + await discovery.GetAllEndPoints(); + + var timeout = Task.Delay(TimeSpan.FromSeconds(10)); + var initsFinished = Task.WhenAny(_consulClient[serviceName].InitFinished.Task); + + Assert.AreNotEqual(timeout, await Task.WhenAny(timeout, initsFinished)); + + SetMockToReturnHost(serviceName); + + var nextHost = await GetServiceDiscovery().GetNextHost(); + nextHost.HostName.ShouldBe(serviceName); } [Test] - [Repeat(Repeat)] + [Retry(5)] public async Task WhenQueryDeleteShouldFallBackToMaster() { var reloadInterval = TimeSpan.FromMilliseconds(5); - _configDic[$"Discovery.Services.{_serviceName}.ReloadInterval"] = reloadInterval.ToString(); + var serviceName = GetServiceName(); - SetMockToReturnHost(MasterService); - SetMockToReturnHost(OriginatingService); + _configDic[$"Discovery.Services.{serviceName}.ReloadInterval"] = reloadInterval.ToString(); - var discovey = GetServiceDiscovey(); - var waitForEvents = discovey.EndPointsChanged.WhenEventReceived(_timeOut); + SetMockToReturnHost(MasterService()); + SetMockToReturnHost(OriginatingService()); + + var discovery = GetServiceDiscovery(); + + + var timeout = Task.Delay(TimeSpan.FromSeconds(10)); + var initsFinished = Task.WhenAny(_consulClient[MasterService()].InitFinished.Task, + _consulClient[OriginatingService()].InitFinished.Task); + + Assert.AreNotEqual(timeout, await Task.WhenAny(timeout, initsFinished)); + + var waitForEvents = discovery.EndPointsChanged.WhenEventReceived(_timeOut); - var nextHost = discovey.GetNextHost(); - (await nextHost).HostName.ShouldBe(OriginatingService); + var nextHost = await discovery.GetNextHost(); + nextHost.HostName.ShouldBe(OriginatingService()); - SetMockToReturnServiceNotDefined(OriginatingService); + SetMockToReturnServiceNotDefined(OriginatingService()); await waitForEvents; - nextHost = discovey.GetNextHost(); - (await nextHost).HostName.ShouldBe(MasterService); + nextHost = await discovery.GetNextHost(); + nextHost.HostName.ShouldBe(MasterService()); } [Test] @@ -188,35 +253,47 @@ public async Task WhenQueryDeleteShouldFallBackToMaster() public async Task WhenQueryAddShouldNotFallBackToMaster() { var reloadInterval = TimeSpan.FromMilliseconds(5); - _configDic[$"Discovery.Services.{_serviceName}.ReloadInterval"] = reloadInterval.ToString(); + var serviceName = GetServiceName(); + _configDic[$"Discovery.Services.{serviceName}.ReloadInterval"] = reloadInterval.ToString(); + + SetMockToReturnHost(MasterService()); + SetMockToReturnServiceNotDefined(OriginatingService()); + + var discovery = GetServiceDiscovery(); - SetMockToReturnHost(MasterService); - SetMockToReturnServiceNotDefined(OriginatingService); + await discovery.GetAllEndPoints(); - var discovey = GetServiceDiscovey(); + var timeout = Task.Delay(TimeSpan.FromSeconds(10)); + var initsFinished = Task.WhenAny(_consulClient[MasterService()].InitFinished.Task, + _consulClient[OriginatingService()].InitFinished.Task); + + Assert.AreNotEqual(timeout, await Task.WhenAny(timeout, initsFinished)); + + SetMockToReturnHost(MasterService()); + SetMockToReturnServiceNotDefined(OriginatingService()); - var nextHost = discovey.GetNextHost(); - (await nextHost).HostName.ShouldBe(MasterService); + var nextHost = await discovery.GetNextHost(); + nextHost.HostName.ShouldBe(MasterService()); - var waitForEvents = discovey.EndPointsChanged.WhenEventReceived(_timeOut); - SetMockToReturnHost(OriginatingService); + var waitForEvents = discovery.EndPointsChanged.WhenEventReceived(_timeOut); + SetMockToReturnHost(OriginatingService()); await waitForEvents; - nextHost = GetServiceDiscovey().GetNextHost(); - nextHost.Result.HostName.ShouldBe(OriginatingService); + nextHost = await discovery.GetNextHost(); + nextHost.HostName.ShouldBe(OriginatingService()); } [Test] - [Repeat(Repeat)] - public async Task ShouldNotFallBackToMasterOnConsulError() + [Retry(5)] + public void ShouldNotFallBackToMasterOnConsulError() { - SetMockToReturnHost(MasterService); - SetMockToReturnError(OriginatingService); - var exception = Should.Throw(() => GetServiceDiscovey().GetNextHost()); + SetMockToReturnHost(MasterService()); + SetMockToReturnError(OriginatingService()); + var exception = Should.Throw(async () => await GetServiceDiscovery().GetNextHost()); exception.UnencryptedTags["responseLog"].ShouldBe("Error response log"); exception.UnencryptedTags["queryDefined"].ShouldBe("True"); exception.UnencryptedTags["consulError"].ShouldNotBeNullOrEmpty(); - exception.UnencryptedTags["requestedService"].ShouldBe(OriginatingService); + exception.UnencryptedTags["requestedService"].ShouldBe(OriginatingService()); } @@ -224,11 +301,24 @@ public async Task ShouldNotFallBackToMasterOnConsulError() [Repeat(Repeat)] public async Task QueryDefinedShouldNotFallBackToMaster() { - SetMockToReturnHost(MasterService); - SetMockToReturnHost(OriginatingService); + SetMockToReturnHost(MasterService()); + SetMockToReturnHost(OriginatingService()); + + var discovery = GetServiceDiscovery(); + + await discovery.GetAllEndPoints(); + + var timeout = Task.Delay(TimeSpan.FromSeconds(10)); + var initsFinished = Task.WhenAny(_consulClient[MasterService()].InitFinished.Task, + _consulClient[OriginatingService()].InitFinished.Task); + + Assert.AreNotEqual(timeout, await Task.WhenAny(timeout, initsFinished)); - var nextHost = GetServiceDiscovey().GetNextHost(); - (await nextHost).HostName.ShouldBe(OriginatingService); + SetMockToReturnHost(MasterService()); + SetMockToReturnHost(OriginatingService()); + + var nextHost = await GetServiceDiscovery().GetNextHost(); + nextHost.HostName.ShouldBe(OriginatingService()); } [Test] @@ -237,82 +327,116 @@ public void MasterShouldNotFallBack() { _environment = Substitute.For(); _environment.Zone.Returns("il3"); - _environment.DeploymentEnvironment.Returns(MASTER_ENVIRONMENT); + _environment.DeploymentEnvironment.Returns(MasterEnvironment); _unitTestingKernel.Rebind().ToConstant(_environment); - SetMockToReturnServiceNotDefined(MasterService); + SetMockToReturnServiceNotDefined(MasterService()); - Should.Throw(() => GetServiceDiscovey().GetNextHost()); + Should.Throw(async () => await GetServiceDiscovery().GetNextHost()); } [Test] [Repeat(Repeat)] public async Task EndPointsChangedShouldNotFireWhenNothingChange() { + var serviceName = GetServiceName(); + TimeSpan reloadInterval = TimeSpan.FromMilliseconds(5); - _configDic[$"Discovery.Services.{_serviceName}.ReloadInterval"] = reloadInterval.ToString(); + _configDic[$"Discovery.Services.{serviceName}.ReloadInterval"] = reloadInterval.ToString(); int numOfEvent = 0; - SetMockToReturnHost(MasterService); - SetMockToReturnHost(OriginatingService); + SetMockToReturnHost(MasterService()); + SetMockToReturnHost(OriginatingService()); //in the first time can fire one or two event - var discovey = GetServiceDiscovey(); - discovey.GetNextHost(); - discovey.EndPointsChanged.LinkTo(new ActionBlock(x => numOfEvent++)); - Thread.Sleep(200); - numOfEvent = 0; + var discovery = GetServiceDiscovery(); + + await discovery.GetAllEndPoints(); + + var timeout = Task.Delay(TimeSpan.FromSeconds(10)); + var initsFinished = Task.WhenAny(_consulClient[MasterService()].InitFinished.Task, + _consulClient[OriginatingService()].InitFinished.Task); + + Assert.AreNotEqual(timeout, await Task.WhenAny(timeout, initsFinished)); + + SetMockToReturnHost(MasterService()); + SetMockToReturnHost(OriginatingService()); + + await discovery.GetNextHost(); + int events = numOfEvent; + discovery.EndPointsChanged.LinkTo(new ActionBlock(x => events++)); + for (int i = 0; i < 5; i++) { - discovey.GetNextHost(); - Thread.Sleep((int) reloadInterval.TotalMilliseconds * 10); + await discovery.GetNextHost(); } - numOfEvent.ShouldBe(0); + events.ShouldBe(0); } [Test] - [Repeat(Repeat)] + [Retry(5)] public async Task EndPointsChangedShouldFireConfigChange() { - SetMockToReturnHost(MasterService); - SetMockToReturnHost(OriginatingService); + var serviceName = GetServiceName(); + + SetMockToReturnHost(MasterService(serviceName)); + SetMockToReturnHost(OriginatingService(serviceName)); //in the first time can fire one or two event - var discovey = GetServiceDiscovey(); - var waitForEvents = discovey.EndPointsChanged.StartCountingEvents(); + var discovery = GetServiceDiscovery(serviceName); + + + await discovery.GetAllEndPoints(); + + var timeout = Task.Delay(TimeSpan.FromSeconds(10)); + var initsFinished = Task.WhenAny(_consulClient[MasterService(serviceName)].InitFinished.Task, + _consulClient[OriginatingService()].InitFinished.Task); + + Assert.AreNotEqual(timeout, await Task.WhenAny(timeout, initsFinished)); + + SetMockToReturnHost(MasterService()); + SetMockToReturnHost(OriginatingService()); + + var waitForEvents = discovery.EndPointsChanged.StartCountingEvents(); - await discovey.GetNextHost(); + await discovery.GetNextHost(); - _configDic[$"Discovery.Services.{_serviceName}.Hosts"] = "localhost"; - _configDic[$"Discovery.Services.{_serviceName}.Source"] = "Config"; + _configDic[$"Discovery.Services.{serviceName}.Hosts"] = "localhost"; + _configDic[$"Discovery.Services.{serviceName}.Source"] = "Config"; Task waitForChangeEvent = waitForEvents.WhenNextEventReceived(); await _configRefresh.ApplyChanges(); await waitForChangeEvent; - var host = await discovey.GetNextHost(); + var host = await discovery.GetNextHost(); host.HostName.ShouldBe("localhost"); waitForEvents.ReceivedEvents.Count.ShouldBe(1); - } + public string GetServiceName([CallerMemberName] string caller = null) + { + return caller; + } + [Test] - [Repeat(Repeat)] + [Retry(5)] public async Task GetAllEndPointsChangedShouldFireConfigChange() { - SetMockToReturnHost(MasterService); - SetMockToReturnHost(OriginatingService); + var serviceName = GetServiceName(); + + SetMockToReturnHost(MasterService(serviceName)); + SetMockToReturnHost(OriginatingService(serviceName)); //in the first time can fire one or two event - var discovey = GetServiceDiscovey(); + var discovery = GetServiceDiscovery(serviceName); - //wait for discovey to be initialize!! - var endPoints = await discovey.GetAllEndPoints(); - endPoints.Single().HostName.ShouldBe(OriginatingService); + //wait for discovery to be initialize!! + var endPoints = await discovery.GetAllEndPoints(); + endPoints.Single().HostName.ShouldBe(OriginatingService(serviceName)); - var waitForEvents = discovey.EndPointsChanged.StartCountingEvents(); + var waitForEvents = discovery.EndPointsChanged.StartCountingEvents(); - _configDic[$"Discovery.Services.{_serviceName}.Source"] = "Config"; - _configDic[$"Discovery.Services.{_serviceName}.Hosts"] = "localhost"; + _configDic[$"Discovery.Services.{serviceName}.Source"] = "Config"; + _configDic[$"Discovery.Services.{serviceName}.Hosts"] = "localhost"; Console.WriteLine("RaiseChangeEvent"); Task waitForChangeEvent = waitForEvents.WhenNextEventReceived(); @@ -321,41 +445,49 @@ public async Task GetAllEndPointsChangedShouldFireConfigChange() waitForEvents.ReceivedEvents.Count.ShouldBe(1); - endPoints = await discovey.GetAllEndPoints(); + endPoints = await discovery.GetAllEndPoints(); endPoints.Single().HostName.ShouldBe("localhost"); waitForEvents.ReceivedEvents.Count.ShouldBe(1); } [Test] - [Repeat(Repeat)] + [Retry(5)] public async Task EndPointsChangedShouldFireWhenHostChange() { var reloadInterval = TimeSpan.FromMilliseconds(5); - _configDic[$"Discovery.Services.{_serviceName}.ReloadInterval"] = reloadInterval.ToString(); - SetMockToReturnHost(MasterService); - SetMockToReturnHost(OriginatingService); - var discovey = GetServiceDiscovey(); - await discovey.GetAllEndPoints(); + var serviceName = GetServiceName(); + _configDic[$"Discovery.Services.{serviceName}.ReloadInterval"] = reloadInterval.ToString(); + SetMockToReturnHost(MasterService(serviceName)); + SetMockToReturnHost(OriginatingService(serviceName)); + var discovery = GetServiceDiscovery(serviceName); + await discovery.GetAllEndPoints(); + + var timeout = Task.Delay(TimeSpan.FromSeconds(10)); + var initsFinished = Task.WhenAny(_consulClient[MasterService(serviceName)].InitFinished.Task, + _consulClient[OriginatingService(serviceName)].InitFinished.Task); + + Assert.AreNotEqual(timeout, await Task.WhenAny(timeout, initsFinished)); + - var wait = discovey.EndPointsChanged.StartCountingEvents(); + var wait = discovery.EndPointsChanged.StartCountingEvents(); bool UseOriginatingService(int i) => i % 2 == 0; for (int i = 1; i < 6; i++) { var waitForNextEvent = wait.WhenNextEventReceived(); //act if (UseOriginatingService(i)) - SetMockToReturnHost(OriginatingService); + SetMockToReturnHost(OriginatingService(serviceName)); else - SetMockToReturnServiceNotDefined(OriginatingService); + SetMockToReturnServiceNotDefined(OriginatingService(serviceName)); await waitForNextEvent; //assert wait.ReceivedEvents.Count.ShouldBe(i); - var nextHost = (await discovey.GetNextHost()).HostName; + var nextHost = (await discovery.GetNextHost()).HostName; if (UseOriginatingService(i)) - nextHost.ShouldBe(OriginatingService); + nextHost.ShouldBe(OriginatingService(serviceName)); else - nextHost.ShouldBe(MasterService); + nextHost.ShouldBe(MasterService(serviceName)); } } @@ -377,11 +509,17 @@ private void SetMockToReturnHost(string serviceName) private void SetMockToReturnServiceNotDefined(string serviceName) { + if (!_consulClient.ContainsKey(serviceName)) + CreateConsulMock(serviceName); + _consulClient[serviceName].SetResult(new EndPointsResult {IsQueryDefined = false}); } private void SetMockToReturnError(string serviceName) { + if (!_consulClient.ContainsKey(serviceName)) + CreateConsulMock(serviceName); + _consulClient[serviceName].SetResult( new EndPointsResult { @@ -392,17 +530,18 @@ private void SetMockToReturnError(string serviceName) } [Test] - public void ServiceDiscoveySameNameShouldBeTheSame() + public void ServiceDiscoverySameNameShouldBeTheSame() { - Assert.AreEqual(GetServiceDiscovey(), GetServiceDiscovey()); + var serviceName = GetServiceName(); + Assert.AreEqual(GetServiceDiscovery(serviceName), GetServiceDiscovery(serviceName)); } private readonly ReachabilityChecker _reachabilityChecker = x => Task.FromResult(true); - private IServiceDiscovery GetServiceDiscovey() + private IServiceDiscovery GetServiceDiscovery([CallerMemberName]string serviceName = null) { var discovery = - _unitTestingKernel.Get>()(_serviceName, + _unitTestingKernel.Get>()(serviceName, _reachabilityChecker); Task.Delay(200).GetAwaiter() .GetResult(); // let ConsulClient return the expected result before getting the dicovery object @@ -410,8 +549,8 @@ private IServiceDiscovery GetServiceDiscovey() } - private string MasterService => ConsulServiceName(_serviceName, MASTER_ENVIRONMENT); - private string OriginatingService => ConsulServiceName(_serviceName, ORIGINATING_ENVIRONMENT); + private string MasterService([CallerMemberName]string serviceName= null) => ConsulServiceName(serviceName, MasterEnvironment); + private string OriginatingService([CallerMemberName]string serviceName = null) => ConsulServiceName(serviceName, OriginatingEnvironment); private static string ConsulServiceName(string serviceName, string deploymentEnvironment) => $"{serviceName}-{deploymentEnvironment}"; diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/ConsulDiscoverySourceTest.cs b/tests/Gigya.Microdot.UnitTests/Discovery/ConsulDiscoverySourceTest.cs index c8135207..b4157c68 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/ConsulDiscoverySourceTest.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/ConsulDiscoverySourceTest.cs @@ -1,21 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; - -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery; using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.Testing.Shared; using Gigya.Microdot.Testing.Shared.Utils; using Ninject; - using NSubstitute; - using NUnit.Framework; using Shouldly; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.UnitTests.Discovery { diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/ConsulSimulator.cs b/tests/Gigya.Microdot.UnitTests/Discovery/ConsulSimulator.cs index fc56ed0e..a097182d 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/ConsulSimulator.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/ConsulSimulator.cs @@ -1,4 +1,8 @@ -using System; +using Gigya.Microdot.LanguageExtensions; +using Gigya.Microdot.ServiceDiscovery; +using Gigya.Microdot.SharedLogic; +using Newtonsoft.Json.Linq; +using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; @@ -7,9 +11,6 @@ using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; -using Gigya.Microdot.ServiceDiscovery; -using Gigya.Microdot.SharedLogic; -using Newtonsoft.Json.Linq; namespace Gigya.Microdot.UnitTests.Discovery { @@ -292,7 +293,8 @@ await SetResponse(context, "",0, (_,__) => Task.FromResult(new ConsulResponse private async Task SetResponse(HttpListenerContext context, string serviceName, ulong? index, Func> getResponseByService) { - using (context.Response) + + try { Exception exception = null; ConsulResponse response = null; @@ -304,6 +306,7 @@ private async Task SetResponse(HttpListenerContext context, string serviceName, { exception = ex; } + exception = exception ?? _httpErrorFake; if (exception != null) response = new ConsulResponse @@ -312,17 +315,25 @@ private async Task SetResponse(HttpListenerContext context, string serviceName, StatusCode = HttpStatusCode.InternalServerError }; - context.Response.StatusCode = (int)response.StatusCode; - if (response.ModifyIndex!=null) + context.Response.StatusCode = (int) response.StatusCode; + if (response.ModifyIndex != null) context.Response.AddHeader("x-consul-index", response.ModifyIndex.Value.ToString()); - await context.Response.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(response.Content), 0, response.Content.Length); + await context.Response.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(response.Content), 0, + response.Content.Length); + } + catch (ObjectDisposedException) + { + + } + finally + { + context.Response.TryDispose(); } } public void Dispose() { _consulListener.Close(); - ((IDisposable)_consulListener)?.Dispose(); _waitForKeyValueIndexModification.TrySetResult(false); _waitForHealthIndexModification.TrySetResult(false); } diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/DiscoveryConfigTests.cs b/tests/Gigya.Microdot.UnitTests/Discovery/DiscoveryConfigTests.cs index 09a6f2a4..d55eb09a 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/DiscoveryConfigTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/DiscoveryConfigTests.cs @@ -1,14 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.Threading.Tasks; -using Gigya.Microdot.ServiceDiscovery; +using Gigya.Microdot.ServiceDiscovery; using Gigya.Microdot.ServiceDiscovery.Config; using Ninject; - using NUnit.Framework; - using Shouldly; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Discovery { diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/LocalNodeSourceTests.cs b/tests/Gigya.Microdot.UnitTests/Discovery/LocalNodeSourceTests.cs index 354d2ed7..531ec18e 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/LocalNodeSourceTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/LocalNodeSourceTests.cs @@ -1,7 +1,4 @@ -using System; -using System.Linq; -using System.Net; -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery; using Gigya.Microdot.ServiceDiscovery.Rewrite; @@ -10,6 +7,9 @@ using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Linq; +using System.Net; namespace Gigya.Microdot.UnitTests.Discovery { diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/RemoteHostPoolTests.cs b/tests/Gigya.Microdot.UnitTests/Discovery/RemoteHostPoolTests.cs index 5778220c..0e94672b 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/RemoteHostPoolTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/RemoteHostPoolTests.cs @@ -1,12 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using System.Threading.Tasks.Dataflow; - -using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; @@ -16,16 +8,21 @@ using Gigya.Microdot.Testing.Shared; using Gigya.Microdot.Testing.Shared.Utils; using Metrics; - using Ninject; using NSubstitute; using NUnit.Framework; - using Shouldly; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.UnitTests.Discovery { - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + [TestFixture, Parallelizable(ParallelScope.Fixtures)] public class RemoteHostPoolTests { private const string SERVICE_NAME = "ServiceName"; @@ -52,17 +49,17 @@ private void CreatePool(string endPoints, ReachabilityChecker isReachableChecker Log = (LogSpy)unitTesting.Get(); var factory = unitTesting.Get(); _discoverySourceMock = new DiscoverySourceMock(serviceContext, endPoints); - + Pool = factory.Create( - new DeploymentIdentifier(SERVICE_NAME, "prod", Substitute.For()), - _discoverySourceMock, + new DeploymentIdentifier(SERVICE_NAME, "prod", Substitute.For()), + _discoverySourceMock, isReachableChecker ?? (rh => Task.FromResult(false))); } - private void ChangeConfig(string endPoints) + private async Task ChangeConfig(string endPoints) { - _discoverySourceMock.SetEndPoints(endPoints); + await _discoverySourceMock.SetEndPoints(endPoints); } private HealthCheckResult GetHealthResult() @@ -110,14 +107,39 @@ public void ThreeHosts_ShouldBeHealthy() } [Test] - public void GetNextHost_HostsThatChange_ReturnsNewHosts() + public async Task GetNextHost_HostsThatChange_ReturnsNewHosts() { CreatePool("host1, host2, host3"); - ChangeConfig("host4, host5, host6"); + await ChangeConfig("host4, host5, host6"); - var res = Get100HostNames(); - res.Distinct() - .ShouldBe(new[] { "host4", "host5", "host6" }, true); + await RetryGet(); + } + + + private async Task RetryGet() + { + bool isSuccess = false; + for (int i = 0; i < 10; i++) + { + var res = Get100HostNames(); + try + { + res.Distinct().ShouldBe(new[] { "host4", "host5", "host6" }, true); + isSuccess = true; + break; + } + catch + { + await Task.Delay(100); + } + + } + + if (!isSuccess) + { + var res = Get100HostNames(); + res.Distinct().ShouldBe(new[] { "host4", "host5", "host6" }, true); + } } @@ -145,19 +167,19 @@ public void GetNextHost_LocalhostFallbackOff_NoEndpoints_Throws() } [Test] - public void GetNextHost_LocalhostFallbackOff_AfterRefreshNoEndpoints_Throws() + public async Task GetNextHost_LocalhostFallbackOff_AfterRefreshNoEndpoints_Throws() { CreatePool("host1, host2, host3"); - ChangeConfig(""); + await ChangeConfig(""); Should.Throw(() => Pool.GetNextHost()); } [Test] - public void GetNextHost_LocalhostFallbackOff_AfterRefreshNoEndpoints_ShouldNotBeHealthy() + public async Task GetNextHost_LocalhostFallbackOff_AfterRefreshNoEndpoints_ShouldNotBeHealthy() { CreatePool("host1, host2, host3"); Pool.GetNextHost(); - ChangeConfig(""); + await ChangeConfig(""); Should.Throw(() => Pool.GetNextHost()); var healthResult = GetHealthResult(); healthResult.IsHealthy.ShouldBeFalse(); @@ -198,7 +220,7 @@ public void ReportFailure_OnlyOneHostFails_ShouldStillBeHealthy() { CreatePool("host1, host2, host3"); - Run100times(host => + Run100Times(host => { if (host.HostName == "host2") host.ReportFailure(); @@ -209,7 +231,7 @@ public void ReportFailure_OnlyOneHostFails_ShouldStillBeHealthy() } - private void Run100times(Action act) + private void Run100Times(Action act) { for (int i = 0; i < 100; i++) { @@ -225,14 +247,14 @@ public async Task ReportFailure_HostFailsThenReturnsInBackground_WillBeReturned_ CreatePool("host2", host => Task.FromResult(isReachable)); var wait = Pool.ReachabilitySource.WhenEventReceived(); - - for (int i = 0; i < 2; i++) - { - var host = Pool.GetNextHost(); - if (host.HostName == "host2") - host.ReportFailure(); - } + for (int i = 0; i < 2; i++) + { + var host = Pool.GetNextHost(); + + if (host.HostName == "host2") + host.ReportFailure(); + } (await wait).IsReachable.ShouldBeFalse(); (await Pool.ReachabilitySource.ShouldRaiseMessage(() => @@ -270,7 +292,7 @@ public void ReportFailure_AllHostFails_Throws() Should.Throw(() => Pool.GetNextHost()); } - [Test] + [Test] public void ReportFailure_AllHostFails_ShouldNotBeHealthy() { CreatePool("host1, host2, host3"); @@ -343,20 +365,22 @@ internal class DiscoverySourceMock : ServiceDiscoverySourceBase public DiscoverySourceMock(string deployment, string initialEndPoints) : base(deployment) { - Result = new EndPointsResult {EndPoints = GetEndPointsInitialValue(initialEndPoints)}; + Result = new EndPointsResult { EndPoints = GetEndPointsInitialValue(initialEndPoints) }; } - public void SetEndPoints(string endPoints) + public async Task SetEndPoints(string endPoints) { - Result = new EndPointsResult {EndPoints = new EndPoint[0]}; + Result = new EndPointsResult { EndPoints = new EndPoint[0] }; if (!string.IsNullOrWhiteSpace(endPoints)) - Result = new EndPointsResult {EndPoints= endPoints.Split(',').Select(_ => _.Trim()) + Result = new EndPointsResult + { + EndPoints = endPoints.Split(',').Select(_ => _.Trim()) .Where(a => !string.IsNullOrWhiteSpace(a)) .Select(_ => new EndPoint { HostName = _ }) - .ToArray()}; - + .ToArray() + }; EndpointsChangedBroadcast.Post(Result); - Task.Delay(100).Wait(); + await Task.Delay(100); } private EndPoint[] GetEndPointsInitialValue(string initialEndPoints) @@ -370,7 +394,7 @@ private EndPoint[] GetEndPointsInitialValue(string initialEndPoints) return new EndPoint[0]; } - public bool AlwaysThrowException=false; + public bool AlwaysThrowException = false; public override bool IsServiceDeploymentDefined => true; public override string SourceName => "Mock"; diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/ConsulNodeSourceFactoryTests.cs b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/ConsulNodeSourceFactoryTests.cs index 7911d165..901888c5 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/ConsulNodeSourceFactoryTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/ConsulNodeSourceFactoryTests.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery; @@ -15,6 +12,9 @@ using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Discovery.Rewrite { diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/ConsulNodeSourceTests.cs b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/ConsulNodeSourceTests.cs index 62cc5b7b..7465424a 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/ConsulNodeSourceTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/ConsulNodeSourceTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Threading.Tasks; -using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery; @@ -15,10 +13,12 @@ using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Discovery.Rewrite { - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + [TestFixture,NonParallelizable] public class ConsulNodeSourceTests { private int ConsulPort = DisposablePort.GetPort().Port; diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/DiscoveryTests.cs b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/DiscoveryTests.cs index 25068a18..33ab85df 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/DiscoveryTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/DiscoveryTests.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery; using Gigya.Microdot.ServiceDiscovery.Config; @@ -12,6 +8,10 @@ using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Discovery.Rewrite { diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/LoadBalancerTests.cs b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/LoadBalancerTests.cs index f5db3d72..a7d44744 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/LoadBalancerTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/LoadBalancerTests.cs @@ -20,9 +20,6 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Linq; -using System.Threading.Tasks; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.Logging; @@ -33,13 +30,13 @@ using Gigya.Microdot.SharedLogic.Rewrite; using Gigya.Microdot.Testing.Shared; using Metrics; - using Ninject; using NSubstitute; -using NSubstitute.Core; using NUnit.Framework; - using Shouldly; +using System; +using System.Linq; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Discovery.Rewrite { @@ -90,7 +87,7 @@ public void Setup() _environment = Substitute.For(); } - private void CreateLoadBalancer(TrafficRoutingStrategy trafficRoutingStrategy = TrafficRoutingStrategy.RandomByRequestID) + private void CreateLoadBalancer(TrafficRoutingStrategy trafficRoutingStrategy = TrafficRoutingStrategy.RoundRobin) { var createLoadBalancer = _kernel.Get>(); _loadBalancer = createLoadBalancer( @@ -258,7 +255,7 @@ private async Task GetDifferentNode(Node nodeToCompare) [Repeat(Repeat)] public async Task GetNode_NodeIsReachableAgain_NodeWillBeReturned() { - CreateLoadBalancer(); + CreateLoadBalancer(TrafficRoutingStrategy.RoundRobin); SetupDefaultNodes(); var selectedNode = await _loadBalancer.TryGetNode(); @@ -354,7 +351,7 @@ public async Task GetNode_AllNodesUnreachable_ThrowsException() [Repeat(Repeat)] public async Task GetNode_AllNodesUnreachableThenAllNodesReachable_ReturnsAllNodes() { - CreateLoadBalancer(); + CreateLoadBalancer(TrafficRoutingStrategy.RoundRobin); SetupSourceNodes(_node1, _node2, _node3); await Run20Times(node => _loadBalancer.ReportUnreachable(node)); @@ -375,7 +372,7 @@ public async Task GetNode_AllNodesUnreachableThenAllNodesReachable_ReturnsAllNod [Repeat(Repeat)] public async Task GetNode_NodesUnreachableButReachabilityCheckThrows_ErrorIsLogged() { - CreateLoadBalancer(); + CreateLoadBalancer(TrafficRoutingStrategy.RoundRobin); SetupDefaultNodes(); var reachabilityException = new Exception("Simulated error while running reachability check"); diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/MultiEnvironmentConsulDiscoveryMasterFallBackTest.cs b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/MultiEnvironmentConsulDiscoveryMasterFallBackTest.cs index 840473e1..ddc4132a 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/MultiEnvironmentConsulDiscoveryMasterFallBackTest.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/MultiEnvironmentConsulDiscoveryMasterFallBackTest.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; @@ -12,6 +9,9 @@ using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Discovery.Rewrite { diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/MultiEnvironmentServiceDiscoveryConfigChangeTest.cs b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/MultiEnvironmentServiceDiscoveryConfigChangeTest.cs index 9c9f3890..ed4604f5 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/MultiEnvironmentServiceDiscoveryConfigChangeTest.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/MultiEnvironmentServiceDiscoveryConfigChangeTest.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery; @@ -13,6 +9,9 @@ using Ninject; using NUnit.Framework; using Shouldly; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; using IConsulClient = Gigya.Microdot.ServiceDiscovery.IConsulClient; namespace Gigya.Microdot.UnitTests.Discovery.Rewrite diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/MultiEnvironmentServiceDiscoveryPreferredEnvironmentTests.cs b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/MultiEnvironmentServiceDiscoveryPreferredEnvironmentTests.cs index 4b3c1a5e..7ddda6db 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/MultiEnvironmentServiceDiscoveryPreferredEnvironmentTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/Rewrite/MultiEnvironmentServiceDiscoveryPreferredEnvironmentTests.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery; using Gigya.Microdot.ServiceDiscovery.Config; @@ -16,6 +13,9 @@ using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Discovery.Rewrite { diff --git a/tests/Gigya.Microdot.UnitTests/Discovery/ServiceDiscoveryConfigChangeTest.cs b/tests/Gigya.Microdot.UnitTests/Discovery/ServiceDiscoveryConfigChangeTest.cs index c0e63db2..4cbfc4fd 100644 --- a/tests/Gigya.Microdot.UnitTests/Discovery/ServiceDiscoveryConfigChangeTest.cs +++ b/tests/Gigya.Microdot.UnitTests/Discovery/ServiceDiscoveryConfigChangeTest.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery; @@ -10,11 +6,11 @@ using Gigya.Microdot.Testing.Shared; using Gigya.Microdot.Testing.Shared.Utils; using Ninject; - - using NUnit.Framework; - using Shouldly; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Discovery { diff --git a/tests/Gigya.Microdot.UnitTests/Events/EventSerializationTests.cs b/tests/Gigya.Microdot.UnitTests/Events/EventSerializationTests.cs index b6507cf8..0a2a1409 100644 --- a/tests/Gigya.Microdot.UnitTests/Events/EventSerializationTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Events/EventSerializationTests.cs @@ -1,22 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Net; -using System.Text.RegularExpressions; -using System.Threading.Tasks; using Gigya.Microdot.Hosting.Events; using Gigya.Microdot.Interfaces.Events; -using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic; -using Gigya.Microdot.SharedLogic.Configurations; using Gigya.Microdot.SharedLogic.Configurations.Serialization; using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.Exceptions; using Gigya.Microdot.SharedLogic.Security; using NUnit.Framework; using Shouldly; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Text.RegularExpressions; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Events { diff --git a/tests/Gigya.Microdot.UnitTests/Gigya.Microdot.UnitTests.csproj b/tests/Gigya.Microdot.UnitTests/Gigya.Microdot.UnitTests.csproj index 16095973..30a373fa 100644 --- a/tests/Gigya.Microdot.UnitTests/Gigya.Microdot.UnitTests.csproj +++ b/tests/Gigya.Microdot.UnitTests/Gigya.Microdot.UnitTests.csproj @@ -1,38 +1,36 @@  - - net472 - true - true - Gigya.Microdot.UnitTests - Gigya.Microdot.UnitTests - Copyright © 2017 - $(SolutionDir)main.ruleset - - - - PreserveNewest - - - - - - - - - - - - - - - - - - - - - - - + + Gigya.Microdot.UnitTests + false + net472;net5.0;net6.0 + + + + PreserveNewest + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Gigya.Microdot.UnitTests/HttpServiceRequestTests.cs b/tests/Gigya.Microdot.UnitTests/HttpServiceRequestTests.cs index f899d45c..4b959d91 100644 --- a/tests/Gigya.Microdot.UnitTests/HttpServiceRequestTests.cs +++ b/tests/Gigya.Microdot.UnitTests/HttpServiceRequestTests.cs @@ -1,16 +1,14 @@ -using System.IO; -using System.Reflection; -using Gigya.Microdot.SharedLogic.Configurations.Serialization; -using Gigya.Microdot.SharedLogic.Events; +using Gigya.Microdot.SharedLogic.Configurations.Serialization; using Gigya.Microdot.SharedLogic.Exceptions; using Gigya.Microdot.SharedLogic.HttpService; using Gigya.Microdot.SharedLogic.Security; using Newtonsoft.Json; - using NUnit.Framework; -using Shouldly; +using System.IO; +using System.Reflection; -namespace Gigya.Microdot.UnitTests { +namespace Gigya.Microdot.UnitTests +{ public class HttpServiceRequestTests { private MethodInfo methodInfo; diff --git a/tests/Gigya.Microdot.UnitTests/IDemoService.cs b/tests/Gigya.Microdot.UnitTests/IDemoService.cs index 76b727e6..d93e9ab2 100644 --- a/tests/Gigya.Microdot.UnitTests/IDemoService.cs +++ b/tests/Gigya.Microdot.UnitTests/IDemoService.cs @@ -1,6 +1,5 @@ -using System.Threading.Tasks; - using Gigya.Common.Contracts.HttpService; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests { diff --git a/tests/Gigya.Microdot.UnitTests/MetricsDataEquatable.cs b/tests/Gigya.Microdot.UnitTests/MetricsDataEquatable.cs index 9b965cc7..f8620e1b 100644 --- a/tests/Gigya.Microdot.UnitTests/MetricsDataEquatable.cs +++ b/tests/Gigya.Microdot.UnitTests/MetricsDataEquatable.cs @@ -1,6 +1,5 @@ -using System.Collections.Generic; - using Metrics; +using System.Collections.Generic; namespace Gigya.Microdot.UnitTests { diff --git a/tests/Gigya.Microdot.UnitTests/MetricsDataExtenstion.cs b/tests/Gigya.Microdot.UnitTests/MetricsDataExtenstion.cs index d1db4ef8..58eb9793 100644 --- a/tests/Gigya.Microdot.UnitTests/MetricsDataExtenstion.cs +++ b/tests/Gigya.Microdot.UnitTests/MetricsDataExtenstion.cs @@ -1,10 +1,7 @@ -using System.Linq; - using Metrics.MetricData; - using NUnit.Framework; - using Shouldly; +using System.Linq; namespace Gigya.Microdot.UnitTests { diff --git a/tests/Gigya.Microdot.UnitTests/Monitor/HealthMonitorTest.cs b/tests/Gigya.Microdot.UnitTests/Monitor/HealthMonitorTest.cs index 6a819d3b..08c6dc97 100644 --- a/tests/Gigya.Microdot.UnitTests/Monitor/HealthMonitorTest.cs +++ b/tests/Gigya.Microdot.UnitTests/Monitor/HealthMonitorTest.cs @@ -1,13 +1,9 @@ -using System.Collections.Generic; -using System.Linq; - -using Gigya.Microdot.SharedLogic.Monitor; - +using Gigya.Microdot.SharedLogic.Monitor; using Metrics; - using NUnit.Framework; - using Shouldly; +using System.Collections.Generic; +using System.Linq; namespace Gigya.Microdot.UnitTests.Monitor { diff --git a/tests/Gigya.Microdot.UnitTests/Monitor/HealthStatusTests.cs b/tests/Gigya.Microdot.UnitTests/Monitor/HealthStatusTests.cs index 429d8347..7c216117 100644 --- a/tests/Gigya.Microdot.UnitTests/Monitor/HealthStatusTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Monitor/HealthStatusTests.cs @@ -1,13 +1,10 @@ -using System.Threading.Tasks; - -using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.Exceptions; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.Hosting.HttpService.Endpoints; - using NUnit.Framework; - using Shouldly; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests { diff --git a/tests/Gigya.Microdot.UnitTests/Monitor/MetricsStatisticsPublisherTests.cs b/tests/Gigya.Microdot.UnitTests/Monitor/MetricsStatisticsPublisherTests.cs index ef086115..6a2c4b8e 100644 --- a/tests/Gigya.Microdot.UnitTests/Monitor/MetricsStatisticsPublisherTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Monitor/MetricsStatisticsPublisherTests.cs @@ -1,8 +1,8 @@ -using System.Linq; -using Gigya.Microdot.Orleans.Hosting; +using Gigya.Microdot.Orleans.Hosting; using Metrics.MetricData; using NUnit.Framework; using Shouldly; +using System.Linq; using Metric = Metrics.Metric; diff --git a/tests/Gigya.Microdot.UnitTests/Monitor/PassiveAggregatingHealthCheckTest.cs b/tests/Gigya.Microdot.UnitTests/Monitor/PassiveAggregatingHealthCheckTest.cs index e2b0a4d4..0b700ac2 100644 --- a/tests/Gigya.Microdot.UnitTests/Monitor/PassiveAggregatingHealthCheckTest.cs +++ b/tests/Gigya.Microdot.UnitTests/Monitor/PassiveAggregatingHealthCheckTest.cs @@ -1,11 +1,11 @@ -using System; -using System.Collections.Generic; -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; using Gigya.Microdot.SharedLogic.Monitor; using Metrics; using NSubstitute; using NUnit.Framework; using Shouldly; +using System; +using System.Collections.Generic; namespace Gigya.Microdot.UnitTests.Monitor { diff --git a/tests/Gigya.Microdot.UnitTests/Monitor/WorkloadMetricsTests.cs b/tests/Gigya.Microdot.UnitTests/Monitor/WorkloadMetricsTests.cs index 00921fe8..6896481b 100644 --- a/tests/Gigya.Microdot.UnitTests/Monitor/WorkloadMetricsTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Monitor/WorkloadMetricsTests.cs @@ -1,8 +1,4 @@ -using System; -using System.Diagnostics; -using System.Linq; -using System.Threading.Tasks; -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.Measurement.Workload; @@ -14,25 +10,27 @@ using Ninject; using NUnit.Framework; using Shouldly; +using System; +using System.Diagnostics; +using System.Linq; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.Monitor { - [TestFixture,Parallelizable(ParallelScope.None)] + [TestFixture, Parallelizable(ParallelScope.None)] public class WorkloadMetricsTests { private const string Cpu = "CPU"; + private const string ThreadPool = "ThreadPool"; private const string Memory = "Memory"; private const string Gc = "GC"; - private const string DotNetLogicalThreadCount = "DotNet logical thread count"; private const string CpuUsage = "CPU usage"; - private const string CpuTotal = "CPU total"; + private const string CpuTotal = "Machine Cpu Usage"; private const string GcGen2Collections = "Gen-2 collections"; private const string TimeInGc = "Time in GC"; - private const string MemoryPrivate = "Private"; - private const string MemoryVirtual = "Virtual"; private const string MemoryWorkingSet = "Working set"; - private const string ThreadCount = "Thread count"; + private const string ThreadCount = "Thread Count"; private IKernel _kernel; private ServiceArguments _serviceArguments; @@ -56,6 +54,12 @@ public void Setup() k.Rebind().To(); k.Rebind().ToMethod(c => _serviceArguments); k.Rebind().ToMethod(c => _dateTimeFake); +#if NET5_0_OR_GREATER + k.Rebind().To().InSingletonScope(); +#else + k.Rebind().To().InSingletonScope(); +#endif + k.Bind().To().InSingletonScope(); }); _kernel.Get().Init(); @@ -81,45 +85,38 @@ private void SetupOrleansQueueLength() } - private const int Repet = 1; + private const int Repeat = 1; [Test] - [Repeat(Repet)] + [Repeat(Repeat)] public async Task AddWorkloadGaugesToMetrics() { Init(); - AssertMetricIsPositive(Cpu, DotNetLogicalThreadCount); AssertMetricIsPositive(Cpu, CpuUsage); AssertMetricIsPositive(Cpu, CpuTotal); AssertMetricIsPositive(Gc, GcGen2Collections); AssertMetricIsPositive(Gc, TimeInGc); - AssertMetricIsPositive(Memory, MemoryPrivate); - AssertMetricIsPositive(Memory, MemoryVirtual); AssertMetricIsPositive(Memory, MemoryWorkingSet); - AssertMetricIsPositive(Cpu, ThreadCount); + AssertMetricIsPositive(ThreadPool, ThreadCount); } [Test] - [Repeat(Repet)] + [Repeat(Repeat)] public async Task MetricsShouldBeZeroIfConfiguredNotToReadPerformanceCounters() { _config.ReadPerformanceCounters = false; Init(); - AssertMetricIsZero(Cpu, DotNetLogicalThreadCount); AssertMetricIsZero(Cpu, CpuUsage); - AssertMetricIsZero(Cpu, CpuTotal); AssertMetricIsZero(Gc, GcGen2Collections); AssertMetricIsZero(Gc, TimeInGc); - AssertMetricIsZero(Memory, MemoryPrivate); - AssertMetricIsZero(Memory, MemoryVirtual); AssertMetricIsZero(Memory, MemoryWorkingSet); - AssertMetricIsZero(Cpu, ThreadCount); + AssertMetricIsZero(ThreadPool, ThreadCount); } [Test] - [Repeat(Repet)] + [Repeat(Repeat)] public async Task AddWorkloadHealthCheck() { Init(); @@ -127,27 +124,38 @@ public async Task AddWorkloadHealthCheck() } [Test] - [Repeat(Repet)] + [Retry(5)] public async Task BeUnhealthyAfterThreadsCountIsTooHighForMoreThanSpecifiedDuration() { _config.MaxHealthyThreadsCount = 1; Init(); + await Task.Delay(1000); _dateTimeFake.UtcNow += MinUnhealthyDuration + TimeSpan.FromSeconds(1); GetHealthCheck().IsHealthy.ShouldBe(false); } [Test] - [Repeat(Repet)] + [Repeat(Repeat)] public async Task BeUnhealthyAfterCPUUsageIsTooHighForMoreThanSpecifiedDuration() { _config.MaxHealthyCpuUsage = 0.01; Init(); - _dateTimeFake.UtcNow += MinUnhealthyDuration + TimeSpan.FromSeconds(1); - GetHealthCheck().IsHealthy.ShouldBe(false); + + Task.Run(async () => + { + var random = new Random(); + while (true) + { + random.Next(10000000); + } + }); + await Task.Delay(2000); + _dateTimeFake.UtcNow += MinUnhealthyDuration + TimeSpan.FromSeconds(0.1); + GetHealthCheck().IsHealthy.ShouldBe(false); } [Test] - [Repeat(Repet)] + [Repeat(Repeat)] public async Task BeUnhealthyAfterOrleansQueueIsTooHighForMoreThanSpecifiedDuration() { _config.MaxHealthyOrleansQueueLength = 1; @@ -158,7 +166,7 @@ public async Task BeUnhealthyAfterOrleansQueueIsTooHighForMoreThanSpecifiedDurat } [Test] - [Repeat(Repet)] + [Repeat(Repeat)] public async Task BeHealthyIfProblemDetectedForLessThanSpecifiedDuration() { _config.MaxHealthyThreadsCount = 1; @@ -168,7 +176,7 @@ public async Task BeHealthyIfProblemDetectedForLessThanSpecifiedDuration() } [Test] - [Repeat(Repet)] + [Repeat(Repeat)] public async Task BeHealthyIfProblemWasSolvedDuringSpecifiedDuration() { _config.MaxHealthyThreadsCount = 1; @@ -205,7 +213,7 @@ public void AffinityCoresIteration() private GaugeValueSource MetricShouldExist(string context, string gaugeName) { - var gauge = GetGaute(context, gaugeName); + var gauge = GetGauge(context, gaugeName); gauge.ShouldNotBeNull($"Gauge '{gaugeName}' does not exist"); return gauge; } @@ -234,7 +242,7 @@ public void Init() } - private static GaugeValueSource GetGaute(string context, string gaugeName) + private static GaugeValueSource GetGauge(string context, string gaugeName) { return Metric.Context("Workload").Context(context).DataProvider. CurrentMetricsData.Gauges.FirstOrDefault(x => x.Name == gaugeName); diff --git a/tests/Gigya.Microdot.UnitTests/NinjectExtensionsTests.cs b/tests/Gigya.Microdot.UnitTests/NinjectExtensionsTests.cs index 6d24325f..f6e3f0e0 100644 --- a/tests/Gigya.Microdot.UnitTests/NinjectExtensionsTests.cs +++ b/tests/Gigya.Microdot.UnitTests/NinjectExtensionsTests.cs @@ -1,13 +1,9 @@ -using System; -using System.Linq; - -using Gigya.Microdot.Ninject; - +using Gigya.Microdot.Ninject; using Ninject; - using NUnit.Framework; - using Shouldly; +using System; +using System.Linq; namespace Gigya.Microdot.UnitTests { diff --git a/tests/Gigya.Microdot.UnitTests/NullEnvironment.cs b/tests/Gigya.Microdot.UnitTests/NullEnvironment.cs index 3cc56dae..16416c3d 100644 --- a/tests/Gigya.Microdot.UnitTests/NullEnvironment.cs +++ b/tests/Gigya.Microdot.UnitTests/NullEnvironment.cs @@ -1,11 +1,7 @@ using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic; using System; -using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests { @@ -17,6 +13,8 @@ internal class NullEnvironment : IEnvironment public string Region => nameof(Region); public string DeploymentEnvironment => nameof(DeploymentEnvironment); public string ConsulAddress => nameof(ConsulAddress); + public string HostIPAddress => nameof(HostIPAddress); + public string ContainerName => nameof(ContainerName); public string InstanceName => nameof(InstanceName); public DirectoryInfo ConfigRoot => new DirectoryInfo(Directory.GetCurrentDirectory()); public FileInfo LoadPathsFile => new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), "loadPaths.json")); diff --git a/tests/Gigya.Microdot.UnitTests/Properties/AssemblyInfo.cs b/tests/Gigya.Microdot.UnitTests/Properties/AssemblyInfo.cs index 5d66b7f0..e480e063 100644 --- a/tests/Gigya.Microdot.UnitTests/Properties/AssemblyInfo.cs +++ b/tests/Gigya.Microdot.UnitTests/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ -using System.Reflection; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from diff --git a/tests/Gigya.Microdot.UnitTests/RequestOverridesTests.cs b/tests/Gigya.Microdot.UnitTests/RequestOverridesTests.cs index 415c07d0..2487b053 100644 --- a/tests/Gigya.Microdot.UnitTests/RequestOverridesTests.cs +++ b/tests/Gigya.Microdot.UnitTests/RequestOverridesTests.cs @@ -1,8 +1,8 @@ -using System.Collections.Generic; -using System.Linq; -using Gigya.Microdot.SharedLogic.Events; +using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.HttpService; using NUnit.Framework; +using System.Collections.Generic; +using System.Linq; namespace Gigya.Microdot.UnitTests { diff --git a/tests/Gigya.Microdot.UnitTests/Serialization/BusinessEntity.cs b/tests/Gigya.Microdot.UnitTests/Serialization/BusinessEntity.cs index 1be8c581..f59f14dc 100644 --- a/tests/Gigya.Microdot.UnitTests/Serialization/BusinessEntity.cs +++ b/tests/Gigya.Microdot.UnitTests/Serialization/BusinessEntity.cs @@ -2,7 +2,7 @@ namespace Gigya.Microdot.UnitTests.Serialization { - public interface IBusinessEntity + public interface IBusinessEntity { string Name { get; set; } int Number { get; set; } diff --git a/tests/Gigya.Microdot.UnitTests/Serialization/ExceptionSerializationTests.cs b/tests/Gigya.Microdot.UnitTests/Serialization/ExceptionSerializationTests.cs index b7ea38b3..971b49c3 100644 --- a/tests/Gigya.Microdot.UnitTests/Serialization/ExceptionSerializationTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Serialization/ExceptionSerializationTests.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Ninject; using Gigya.Microdot.SharedLogic.Configurations.Serialization; using Gigya.Microdot.SharedLogic.Exceptions; @@ -9,11 +6,13 @@ using Newtonsoft.Json; using Ninject; using NUnit.Framework; +using System; +using System.Collections.Generic; namespace Gigya.Microdot.UnitTests.Serialization { - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + [TestFixture,Parallelizable(ParallelScope.Fixtures)] public class ExceptionSerializationTests { private MyServiceException MyServiceException { get; set; } diff --git a/tests/Gigya.Microdot.UnitTests/Serialization/GigyaTypePolicySerializationBinderTests.cs b/tests/Gigya.Microdot.UnitTests/Serialization/GigyaTypePolicySerializationBinderTests.cs index ef261576..1947c05e 100644 --- a/tests/Gigya.Microdot.UnitTests/Serialization/GigyaTypePolicySerializationBinderTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Serialization/GigyaTypePolicySerializationBinderTests.cs @@ -1,12 +1,10 @@ -using System; -using System.Net.Http; -using Gigya.Microdot.SharedLogic.Configurations.Serialization; +using Gigya.Microdot.SharedLogic.Configurations.Serialization; using Gigya.Microdot.SharedLogic.Security; -using Gigya.Microdot.UnitTests.ServiceProxyTests; using NSubstitute; -using NSubstitute.ExceptionExtensions; using NUnit.Framework; using Shouldly; +using System; +using System.Net.Http; namespace Gigya.Microdot.UnitTests.Serialization { diff --git a/tests/Gigya.Microdot.UnitTests/Serialization/MicrodotSerializationConstraintsTests.cs b/tests/Gigya.Microdot.UnitTests/Serialization/MicrodotSerializationConstraintsTests.cs index 5fc72aab..5e72c65f 100644 --- a/tests/Gigya.Microdot.UnitTests/Serialization/MicrodotSerializationConstraintsTests.cs +++ b/tests/Gigya.Microdot.UnitTests/Serialization/MicrodotSerializationConstraintsTests.cs @@ -1,8 +1,8 @@ -using System; +using Gigya.Microdot.SharedLogic.Configurations.Serialization; +using NUnit.Framework; +using System; using System.Collections.Generic; using System.Linq; -using Gigya.Microdot.SharedLogic.Configurations.Serialization; -using NUnit.Framework; namespace Gigya.Microdot.UnitTests.Serialization { diff --git a/tests/Gigya.Microdot.UnitTests/Serialization/MyServiceException.cs b/tests/Gigya.Microdot.UnitTests/Serialization/MyServiceException.cs index 98ceab9f..9de7f67b 100644 --- a/tests/Gigya.Microdot.UnitTests/Serialization/MyServiceException.cs +++ b/tests/Gigya.Microdot.UnitTests/Serialization/MyServiceException.cs @@ -1,11 +1,10 @@ +using Gigya.Common.Contracts.Exceptions; using System; using System.Runtime.Serialization; -using Gigya.Common.Contracts.Exceptions; - namespace Gigya.Microdot.UnitTests.Serialization { - [Serializable] + [Serializable] public class MyServiceException : RequestException { public IBusinessEntity Entity { get; private set; } diff --git a/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/GCEndpointTests.cs b/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/GCEndpointTests.cs new file mode 100644 index 00000000..8d48082f --- /dev/null +++ b/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/GCEndpointTests.cs @@ -0,0 +1,122 @@ +using System; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Gigya.Microdot.Common.Tests; +using Gigya.Microdot.Fakes; +using Gigya.Microdot.Hosting.HttpService.Endpoints.GCEndpoint; +using Gigya.Microdot.Testing.Shared.Service; +using Gigya.Microdot.UnitTests.ServiceProxyTests; +using Newtonsoft.Json; +using NUnit.Framework; + +namespace Gigya.Microdot.UnitTests.ServiceListenerTests +{ + [TestFixture, Parallelizable(ParallelScope.None)] + public class GcEndpointTets:AbstractServiceProxyTest + { + private NonOrleansServiceTester> _testinghost; + private SpyEventPublisher _flumeQueue; + private LogSpy _logSpy; + + [SetUp] + public void OneTimeSetUp() + { + _testinghost = new NonOrleansServiceTester>(); + _flumeQueue = _testinghost.Host.SpyEventPublisher; + _logSpy = _testinghost.Host.LogSpy; + } + + [TearDown] + public override void TearDown() + { + try + { + _testinghost.Dispose(); + } + catch + { + //should not fail tests + } + } + + [Test] + public async Task TestRunGCWhenConfigEnabled() + { + var client = _testinghost.GetServiceProxyProvider("DemoService"); + _testinghost.Host.MicrodotHostingConfigMock.GCEndpointEnabled = true; + _testinghost.Host.LogSpy.ClearLog(); + + + var httpClient = new HttpClient(); + + var uri = $"http://localhost:{_testinghost.BasePort}/force-traffic-affecting-gc?getToken="; + + var response = await httpClient.GetAsync(uri); + Assert.NotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var responseString = await response.Content.ReadAsStringAsync(); + var gcHandlingResult = JsonConvert.DeserializeObject(responseString); + + Assert.AreEqual("GC token generated", gcHandlingResult.Message); + + + Assert.AreEqual(1, _logSpy.LogEntries.Count(), string.Join(Environment.NewLine, _logSpy.LogEntries.Select(x=>x.Message)) ); + var logEntry = _logSpy.LogEntries.Single(); + Assert.AreEqual("GC getToken was called, see result in Token tag", logEntry.Message); + var tokenTag = logEntry.UnencryptedTags["tags.Token"].ToUpper(); + + uri = $"http://localhost:{_testinghost.BasePort}/force-traffic-affecting-gc?gcType=Gen0&token={tokenTag.Replace("\"","")}"; + + response = await httpClient.GetAsync(uri); + Assert.NotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + responseString = await response.Content.ReadAsStringAsync(); + gcHandlingResult = JsonConvert.DeserializeObject(responseString); + + Assert.AreEqual("GC ran successfully", gcHandlingResult.Message); + + Assert.AreEqual(0, _flumeQueue.Events.Count); + } + + [Test] + public async Task TestCantRunGCWithoutValidToken() + { + var client = _testinghost.GetServiceProxyProvider("DemoService"); + _testinghost.Host.MicrodotHostingConfigMock.GCEndpointEnabled = true; + _testinghost.Host.LogSpy.ClearLog(); + + + var httpClient = new HttpClient(); + + var uri = $"http://localhost:{_testinghost.BasePort}/force-traffic-affecting-gc?gcType=Gen0&token={Guid.NewGuid()}"; + + var response = await httpClient.GetAsync(uri); + Assert.NotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + var responseString = await response.Content.ReadAsStringAsync(); + var gcHandlingResult = JsonConvert.DeserializeObject(responseString); + + Assert.AreEqual("Illegal request", gcHandlingResult.Message); + + Assert.AreEqual(0, _flumeQueue.Events.Count); + } + + [Test] + public async Task TestDontRunGCWhenConfigDisabled() + { + var client = _testinghost.GetServiceProxyProvider("DemoService"); + _testinghost.Host.MicrodotHostingConfigMock.GCEndpointEnabled = false; + + var httpClient = new HttpClient(); + + var uri = $"http://localhost:{_testinghost.BasePort}/force-traffic-affecting-gc?gcType=Gen0"; + + var response = await httpClient.GetAsync(uri); + + Assert.NotNull(response); + Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); + } + } +} diff --git a/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/HttpServiceListenerTests.cs b/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/HttpServiceListenerTests.cs index e7e394ce..1c04b912 100644 --- a/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/HttpServiceListenerTests.cs +++ b/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/HttpServiceListenerTests.cs @@ -1,19 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; -using System.Text; -using System.Threading.Tasks; -using FluentAssertions; - +using FluentAssertions; using Gigya.Common.Application.HttpService.Client; using Gigya.Common.Contracts.Exceptions; using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.Common.Tests; using Gigya.Microdot.Fakes; using Gigya.Microdot.Fakes.KernelUtils; +using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.Hosting.HttpService.Endpoints; +using Gigya.Microdot.Hosting.Service; using Gigya.Microdot.Interfaces.Logging; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.Ninject; @@ -21,9 +16,11 @@ using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.Configurations; +using Gigya.Microdot.SharedLogic.Configurations.Serialization; using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.Exceptions; using Gigya.Microdot.SharedLogic.HttpService; +using Gigya.Microdot.SharedLogic.Security; using Gigya.Microdot.Testing.Shared; using Gigya.Microdot.Testing.Shared.Service; using Gigya.Microdot.UnitTests.Caching.Host; @@ -34,14 +31,14 @@ using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; - using RichardSzalay.MockHttp; - using Shouldly; -using Gigya.Microdot.Hosting.Environment; -using Gigya.Microdot.Hosting.Service; -using Gigya.Microdot.SharedLogic.Configurations.Serialization; -using Gigya.Microdot.SharedLogic.Security; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.ServiceListenerTests { @@ -168,37 +165,7 @@ public async Task SendRequestWithNullParameter() await _testinghost.Host.Kernel.Get().Received().ToUpper(null); } - [Test] - [Ignore("should refactor to be simple ")] - public async Task SendRequestWithInvalidParameterValue() - { - - // var methodName = nameof(IDemoService.ToUpper); - // var expectedParamName = typeof(IDemoService).GetMethod(methodName).GetParameters().First().Name; - - //_testinghost.Host._overrideServiceMethod = invocationTarget => - // { - // // Cause HttpServiceListener to think it is a weakly-typed request, - // // and get the parameters list from the mocked ServiceMethod, and not from the original invocation target - // invocationTarget.ParameterTypes = null; - - // // return a ServiceMethod which expects only int values - // return new ServiceMethod(typeof(IDemoServiceSupportOnlyIntValues), - // typeof(IDemoServiceSupportOnlyIntValues).GetMethod(methodName)); - // }; - - // try - // { - // await _insecureClient.ToUpper("Non-Int value"); - // Assert.Fail("Host was expected to throw an exception"); - // } - // catch (InvalidParameterValueException ex) - // { - // ex.parameterName.ShouldBe(expectedParamName); - // } - } - - + [Test] public async Task SendRequestWithNoParameters() { diff --git a/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/MetricsTests.cs b/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/MetricsTests.cs index eff277f7..2f21f7cc 100644 --- a/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/MetricsTests.cs +++ b/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/MetricsTests.cs @@ -1,23 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Threading; - -using FluentAssertions; - +using FluentAssertions; using Gigya.Common.Application.HttpService.Client; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; -using Gigya.Microdot.Logging.NLog; -using Gigya.Microdot.Ninject; -using Gigya.Microdot.SharedLogic; -using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.Testing.Shared.Service; using Metrics; using Metrics.MetricData; using Ninject; using NSubstitute; - using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Threading; namespace Gigya.Microdot.UnitTests.ServiceListenerTests { @@ -65,8 +56,10 @@ public void TestMetricsOnSuccess() res.Should().Be(1); testinghost.Host.Kernel.Get().Received().Increment(0); - Thread.Sleep(100); - GetMetricsData(testinghost.Host.ServiceName).AssertEquals(DefaultExpected()); + + + Thread.Sleep(200); + GetMetricsData(testinghost.Host.ServiceName).AssertEquals(DefaultExpected("Success")); } } @@ -78,15 +71,10 @@ public void TestMetricsOnFailure() testinghost.Host.Kernel.Get().When(a => a.DoSomething()).Do(x => { throw new Exception("Do exception"); }); Assert.Throws(() => testinghost.GetServiceProxy().DoSomething().GetAwaiter().GetResult()); + - var metricsExpected = DefaultExpected(); - - metricsExpected.Counters = new List - { - new MetricDataEquatable {Name = "Failed", Unit = Unit.Calls} - }; - - GetMetricsData(testinghost.Host.ServiceName).AssertEquals(metricsExpected); + Thread.Sleep(200); + GetMetricsData(testinghost.Host.ServiceName).AssertEquals(DefaultExpected("Failed")); } } @@ -100,13 +88,13 @@ private MetricsData GetMetricsData(string hostName) } - private static MetricsDataEquatable DefaultExpected() + private static MetricsDataEquatable DefaultExpected(string name) { return new MetricsDataEquatable { Counters = new List { - new MetricDataEquatable {Name = "Success", Unit = Unit.Calls} + new MetricDataEquatable {Name = name, Unit = Unit.Calls} }, Timers = new List { diff --git a/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/PortsAllocationTests.cs b/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/PortsAllocationTests.cs index 7d8aaa3c..e3c80edb 100644 --- a/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/PortsAllocationTests.cs +++ b/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/PortsAllocationTests.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using System.Threading.Tasks; - -using FluentAssertions; - +using FluentAssertions; using Gigya.Microdot.Fakes; using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.Interfaces; @@ -15,14 +9,14 @@ using Gigya.Microdot.SharedLogic.HttpService; using Gigya.Microdot.Testing.Shared; using Gigya.Microdot.UnitTests.ServiceProxyTests; - using Ninject; - using NUnit.Framework; - using RichardSzalay.MockHttp; - using Shouldly; +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.ServiceListenerTests { diff --git a/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/StatusEndpointsTets.cs b/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/StatusEndpointsTets.cs new file mode 100644 index 00000000..a59fa25b --- /dev/null +++ b/tests/Gigya.Microdot.UnitTests/ServiceListenerTests/StatusEndpointsTets.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Gigya.Microdot.Hosting.Service; +using Gigya.Microdot.Common.Tests; +using Gigya.Microdot.Fakes; +using Gigya.Microdot.Interfaces.Events; +using Gigya.Microdot.Interfaces.Logging; +using Gigya.Microdot.SharedLogic; +using Gigya.Microdot.SharedLogic.Events; +using Gigya.Microdot.Testing.Shared.Service; +using Gigya.Microdot.UnitTests.ServiceProxyTests; +using Ninject; +using NUnit.Framework; + +namespace Gigya.Microdot.UnitTests.ServiceListenerTests +{ + public class ConfigurableHost:TestingHost where T:class + { + public readonly MicrodotHostingConfig MicrodotHostingConfigMock; + public readonly LogSpy LogSpy; + public readonly SpyEventPublisher SpyEventPublisher; + + public ConfigurableHost() + { + MicrodotHostingConfigMock = new MicrodotHostingConfig(); + LogSpy = new LogSpy(); + SpyEventPublisher = new SpyEventPublisher(); + } + + protected override void Configure(IKernel kernel, BaseCommonConfig commonConfig) + { + base.Configure(kernel,commonConfig); + kernel.Rebind>().ToMethod(_ => ()=> MicrodotHostingConfigMock); + kernel.Rebind().ToConstant(LogSpy); + kernel.Rebind().ToConstant(SpyEventPublisher); + } + } + + [TestFixture, Parallelizable(ParallelScope.None)] + public class StatusEndpointsTets:AbstractServiceProxyTest + { + private NonOrleansServiceTester> _testinghost; + + [SetUp] + public override void SetUp() + { + _testinghost = new NonOrleansServiceTester>(); + + TracingContext.SetRequestID("1"); + } + + [TearDown] + public override void TearDown() + { + try + { + _testinghost.Dispose(); + } + catch + { + //should not fail tests + } + } + + [Test] + public async Task TestGetStatus() + { + var client = _testinghost.GetServiceProxyProvider("DemoService"); + + _testinghost.Host.MicrodotHostingConfigMock.StatusEndpoints = + new List(new []{"/myStatus"}); + _testinghost.Host.MicrodotHostingConfigMock.ShouldLogStatusEndpoint = true; + + var httpClient = new HttpClient(); + + var uri = $"http://localhost:{_testinghost.BasePort}/myStatus"; + + var response = await httpClient.GetAsync(uri); + Assert.NotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + } + + [Test] + public async Task TestGetStatusShouldNotWorkIfEndpointDontMatch() + { + var client = _testinghost.GetServiceProxyProvider("DemoService"); + + _testinghost.Host.MicrodotHostingConfigMock.StatusEndpoints = + new List(new []{"/status"}); + _testinghost.Host.MicrodotHostingConfigMock.ShouldLogStatusEndpoint = false; + + var httpClient = new HttpClient(); + + var uri = $"http://localhost:{_testinghost.BasePort}/myStatus"; + + var response = await httpClient.GetAsync(uri); + Assert.NotNull(response); + Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); + } + + [Test] + public async Task TestGetStatusWorkWithMultipleConfigValues() + { + var client = _testinghost.GetServiceProxyProvider("DemoService"); + + _testinghost.Host.MicrodotHostingConfigMock.StatusEndpoints = + new List(new []{"/status", "/myStatus", "/someStatus"}); + + _testinghost.Host.MicrodotHostingConfigMock.ShouldLogStatusEndpoint = false; + + var httpClient = new HttpClient(); + + var uri = $"http://localhost:{_testinghost.BasePort}/myStatus"; + + var response = await httpClient.GetAsync(uri); + Assert.NotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + } + + [Test] + public async Task TestGetStatusShouldNotWorkForSuffix() + { + var client = _testinghost.GetServiceProxyProvider("DemoService"); + + _testinghost.Host.MicrodotHostingConfigMock.StatusEndpoints = + new List(new []{"/status"}); + + _testinghost.Host.MicrodotHostingConfigMock.ShouldLogStatusEndpoint = false; + + var httpClient = new HttpClient(); + + var uri = $"http://localhost:{_testinghost.BasePort}/status"; + + var response = await httpClient.GetAsync(uri); + Assert.NotNull(response); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + + uri = $"http://localhost:{_testinghost.BasePort}/some/status"; + + response = await httpClient.GetAsync(uri); + Assert.NotNull(response); + Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); + } + } +} diff --git a/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/AbstractServiceProxyTest.cs b/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/AbstractServiceProxyTest.cs index 18d3513c..baaefdff 100644 --- a/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/AbstractServiceProxyTest.cs +++ b/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/AbstractServiceProxyTest.cs @@ -1,22 +1,17 @@ -using System; -using System.Collections.Generic; -using System.Net.Http; -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; using Gigya.Microdot.ServiceProxy; -using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.Exceptions; using Gigya.Microdot.Testing.Shared; using Metrics; - using Ninject; -using Ninject.Parameters; - using NUnit.Framework; +using System; +using System.Collections.Generic; namespace Gigya.Microdot.UnitTests.ServiceProxyTests { - - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + + [TestFixture,Parallelizable(ParallelScope.None)] public abstract class AbstractServiceProxyTest { protected TestingKernel unitTesting; diff --git a/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/BehaviorTests.cs b/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/BehaviorTests.cs index e4a859c7..8674068d 100644 --- a/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/BehaviorTests.cs +++ b/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/BehaviorTests.cs @@ -1,978 +1,1060 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Sockets; -using System.Runtime.Remoting.Messaging; -using System.Threading.Tasks; -using FluentAssertions; - -using Gigya.Common.Application.HttpService.Client; -using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Fakes; -using Gigya.Microdot.Fakes.KernelUtils; -using Gigya.Microdot.ServiceDiscovery.Config; -using Gigya.Microdot.ServiceDiscovery.HostManagement; -using Gigya.Microdot.ServiceDiscovery.Rewrite; -using Gigya.Microdot.ServiceProxy; -using Gigya.Microdot.SharedLogic.Events; -using Gigya.Microdot.SharedLogic.Exceptions; -using Gigya.Microdot.SharedLogic.HttpService; -using Gigya.Microdot.Testing.Shared; -using Gigya.Microdot.Testing.Shared.Service; -using Newtonsoft.Json; -using Ninject; -using NSubstitute; -using NSubstitute.ExceptionExtensions; -using NSubstitute.Exceptions; -using NUnit.Framework; - -using RichardSzalay.MockHttp; - -using Shouldly; - -namespace Gigya.Microdot.UnitTests.ServiceProxyTests -{ - - public class BehaviorTests : AbstractServiceProxyTest - { - [OneTimeSetUp] - public void startClean() - { - TracingContext.ClearContext(); - } - - [SetUp] - public override void SetUp() - { - base.SetUp(); - unitTesting.Rebind().To().InSingletonScope(); - } - - [Test] - public async Task AllRequestsForSameCallID_SameHostSelected() - { - var port = DisposablePort.GetPort().Port; - var dict = new Dictionary { - {"Discovery.Services.DemoService.Source", "Config"}, - {"Discovery.Services.DemoService.Hosts", "host1,host2"}, - {"Discovery.Services.DemoService.DefaultPort", port.ToString()} - }; - - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler - .When("*") - .Respond(req => HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}'")); - return messageHandler; - }; - - using (var kernel = - new TestingKernel( - k => - { - k.Rebind().To().InSingletonScope(); - k.Rebind>().ToMethod(c => messageHandlerFactory); - }, - dict)) - { - - var providerFactory = kernel.Get>(); - var serviceProxy = providerFactory("DemoService"); - serviceProxy.DefaultPort = port; - - //If we set Request Id we would like always to select same Host - TracingContext.SetRequestID("dumyId1"); - var request = new HttpServiceRequest("testMethod", null, new Dictionary()); - var hostOfFirstReq = (string)await serviceProxy.Invoke(request, typeof(string)); - string host; - for (int i = 0; i < 50; i++) - { - host = (string)await serviceProxy.Invoke(request, typeof(string)); - host.ShouldBe(hostOfFirstReq); - } - - TracingContext.SetRequestID("dumyId2"); - host = (string)await serviceProxy.Invoke(request, typeof(string)); - host.ShouldNotBe(hostOfFirstReq); - } - } - - [Test] - public async Task ServiceProxyRpcMessageShouldRemainSame() - { - const string serviceName = "DemoService"; - int defaultPort = DisposablePort.GetPort().Port; - var dict = new Dictionary - { - {$"Discovery.Services.{serviceName}.Source", "Config"}, - {$"Discovery.Services.{serviceName}.Hosts", "host1"}, - {$"Discovery.Services.{serviceName}.DefaultPort", defaultPort.ToString()} - }; - - Uri uri = null; - string requestMessage = null; - - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler - .When("*").Respond(async req => - { - requestMessage = await req.Content.ReadAsStringAsync(); - uri = req.RequestUri; - return HttpResponseFactory.GetResponse(HttpStatusCode.Accepted); - }); - return messageHandler; - }; - - using (var kernel = new TestingKernel(k => - { - - k.Rebind().To().InSingletonScope(); - k.Rebind>().ToMethod(c => messageHandlerFactory); - }, dict)) - { - - var providerFactory = kernel.Get>(); - - TracingContext.SetRequestID("g"); - - var serviceProxy = providerFactory(serviceName); - - string expectedHost = "override-host"; - int expectedPort = DisposablePort.GetPort().Port; - - TracingContext.SetHostOverride(serviceName, expectedHost, expectedPort); - - var request = new HttpServiceRequest("testMethod", null, new Dictionary()); - using (TracingContext.Tags.SetUnencryptedTag("test", 1)) - using (TracingContext.SuppressCaching(CacheSuppress.RecursiveAllDownstreamServices)) - await serviceProxy.Invoke(request, typeof(string)); - - var body = requestMessage; - Console.WriteLine($"error: {body}"); - - JsonConvert.DeserializeObject(body, new JsonSerializerSettings() { MissingMemberHandling = MissingMemberHandling.Error }); - - uri.Host.ShouldBe(expectedHost); - uri.Port.ShouldBe(expectedPort); - } +using FluentAssertions; +using Gigya.Common.Application.HttpService.Client; +using Gigya.Common.Contracts.Exceptions; +using Gigya.Microdot.Common.Tests; +using Gigya.Microdot.Fakes; +using Gigya.Microdot.ServiceDiscovery.Config; +using Gigya.Microdot.ServiceDiscovery.HostManagement; +using Gigya.Microdot.ServiceDiscovery.Rewrite; +using Gigya.Microdot.ServiceProxy; +using Gigya.Microdot.SharedLogic.Events; +using Gigya.Microdot.SharedLogic.Exceptions; +using Gigya.Microdot.SharedLogic.HttpService; +using Gigya.Microdot.Testing.Shared; +using Gigya.Microdot.Testing.Shared.Service; +using Newtonsoft.Json; +using Ninject; +using NSubstitute; +using NUnit.Framework; +using RichardSzalay.MockHttp; +using Shouldly; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Threading.Tasks; + +namespace Gigya.Microdot.UnitTests.ServiceProxyTests +{ + + public class BehaviorTests : AbstractServiceProxyTest + { + [OneTimeSetUp] + public void OneTimeSetUp() + { + TracingContext.ClearContext(); + } + + [SetUp] + public override void SetUp() + { + base.SetUp(); + unitTesting.Rebind().To().InSingletonScope(); } - - public class Arguments - { - } - - // Don't change structure, unless the original class is changing on purpose. - // It used to ensure, the public protocol isn't broken or changed by mistake. - public class TracingData - { - [JsonRequired] - public string RequestID { get; set; } - - [JsonRequired] - public string HostName { get; set; } - - [JsonRequired] - public string ServiceName { get; set; } - - [JsonRequired] - public string SpanID { get; set; } - - [JsonRequired] + +#if NETFRAMEWORK //hash algorithm was changed in .net core + [Test] + public async Task AllRequestsForSameCallID_SameHostSelected() + { + var port = DisposablePort.GetPort().Port; + var dict = new Dictionary { + {"Discovery.Services.DemoService.Source", "Config"}, + {"Discovery.Services.DemoService.Hosts", "host1,host2,host3,host4,host5,host6,host7"}, + {"Discovery.Services.DemoService.DefaultPort", port.ToString()} + }; + + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler + .When("*") + .Respond(req => HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}'")); + return messageHandler; + }; + + using (var kernel = + new TestingKernel( + k => + { + k.Rebind().To().InSingletonScope(); + k.Rebind>().ToMethod(c => messageHandlerFactory); + }, + dict)) + { + + var providerFactory = kernel.Get>(); + var serviceProxy = providerFactory("DemoService"); + serviceProxy.DefaultPort = port; + + //If we set Request Id we would like always to select same Host + TracingContext.SetRequestID("dumyId1"); + var request = new HttpServiceRequest("testMethod", null, new Dictionary()); + var hostOfFirstReq = (string)await serviceProxy.Invoke(request, typeof(string)); + string host; + for (int i = 0; i < 50; i++) + { + host = (string)await serviceProxy.Invoke(request, typeof(string)); + host.ShouldBe(hostOfFirstReq); + } + + TracingContext.SetRequestID("dumyId2"); + host = (string)await serviceProxy.Invoke(request, typeof(string)); + host.ShouldNotBe(hostOfFirstReq); + } + } +#endif + + [Test] + public async Task ServiceProxyRpcMessageShouldRemainSame() + { + const string serviceName = "DemoService"; + int defaultPort = DisposablePort.GetPort().Port; + var dict = new Dictionary + { + {$"Discovery.Services.{serviceName}.Source", "Config"}, + {$"Discovery.Services.{serviceName}.Hosts", "host1"}, + {$"Discovery.Services.{serviceName}.DefaultPort", defaultPort.ToString()} + }; + + Uri uri = null; + string requestMessage = null; + + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler + .When("*").Respond(async req => + { + requestMessage = await req.Content.ReadAsStringAsync(); + uri = req.RequestUri; + return HttpResponseFactory.GetResponse(HttpStatusCode.Accepted); + }); + return messageHandler; + }; + + using (var kernel = new TestingKernel(k => + { + + k.Rebind().To().InSingletonScope(); + k.Rebind>().ToMethod(c => messageHandlerFactory); + }, dict)) + { + + var providerFactory = kernel.Get>(); + + TracingContext.SetRequestID("g"); + + var serviceProxy = providerFactory(serviceName); + + string expectedHost = "override-host"; + int expectedPort = DisposablePort.GetPort().Port; + + TracingContext.SetHostOverride(serviceName, expectedHost, expectedPort); + + var request = new HttpServiceRequest("testMethod", null, new Dictionary()); + using (TracingContext.Tags.SetUnencryptedTag("test", 1)) + using (TracingContext.SuppressCaching(CacheSuppress.RecursiveAllDownstreamServices)) + await serviceProxy.Invoke(request, typeof(string)); + + var body = requestMessage; + Console.WriteLine($"error: {body}"); + + JsonConvert.DeserializeObject(body, new JsonSerializerSettings() { MissingMemberHandling = MissingMemberHandling.Error }); + + uri.Host.ShouldBe(expectedHost); + uri.Port.ShouldBe(expectedPort); + } + } + + public class Arguments + { + } + + // Don't change structure, unless the original class is changing on purpose. + // It used to ensure, the public protocol isn't broken or changed by mistake. + public class TracingData + { + [JsonRequired] + public string RequestID { get; set; } + + [JsonRequired] + public string HostName { get; set; } + + [JsonRequired] + public string ServiceName { get; set; } + + [JsonRequired] + public string SpanID { get; set; } + + [JsonRequired] public DateTime SpanStartTime { get; set; } [JsonRequired] - public Dictionary Tags { get; set; } - } - - public class Host1 - { - [JsonRequired] - public string ServiceName { get; set; } - - [JsonRequired] - public string Host { get; set; } - - [JsonRequired] - public int Port { get; set; } - } - - public class Overrides - { - [JsonRequired] - public List Hosts { get; set; } - - [JsonRequired] - public string PreferredEnvironment { get; set; } - - [JsonProperty] - public CacheSuppress? SuppressCaching { get; set; } - } - - public class Target - { - [JsonRequired] - public string MethodName { get; set; } - } - - public class GigyaRequestProtocol - { - [JsonRequired] - public Arguments Arguments { get; set; } - - [JsonRequired] - public TracingData TracingData { get; set; } - - [JsonRequired] - public Overrides Overrides { get; set; } - - [JsonRequired] - public Target Target { get; set; } - } - - - [Test] - public async Task RequestContextShouldOverrideHostOnly() - { - const string serviceName = "DemoService"; - int defaultPort = DisposablePort.GetPort().Port; - - var dict = new Dictionary { - {$"Discovery.Services.{serviceName}.Source", "Config"}, - {$"Discovery.Services.{serviceName}.Hosts", "host1"}, - {$"Discovery.Services.{serviceName}.DefaultPort", defaultPort.ToString()} - }; - - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler - .When("*") - .Respond(req => - { - if (req.Method == HttpMethod.Get && req.RequestUri.Scheme == "https") - throw new HttpRequestException(); - - return HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}:{req.RequestUri.Port}'"); - }); - return messageHandler; - }; - - var kernel = new TestingKernel(k => - { - k.Rebind().To().InSingletonScope(); - k.Rebind>().ToMethod(c => messageHandlerFactory); - }, dict); - var providerFactory = kernel.Get>(); - var serviceProxy = providerFactory(serviceName); - - string overrideHost = "override-host"; - - - TracingContext.SetHostOverride(serviceName, overrideHost); - - var request = new HttpServiceRequest("testMethod", null, new Dictionary()); - for (int i = 0; i < 50; i++) - { - var host = (string)await serviceProxy.Invoke(request, typeof(string)); - host.ShouldBe($"{overrideHost}:{defaultPort}"); - } - - } - - - [Test] - public async Task AllHostsAreHavingNetworkErrorsShouldTryEachOnce() - { - var port = DisposablePort.GetPort().Port; - var dict = new Dictionary { - {"Discovery.Services.DemoService.Source", "Config"}, - {"Discovery.Services.DemoService.Hosts", "host1,host2"}, - {"Discovery.Services.DemoService.DefaultPort", port.ToString()} - }; - - int counter = 0; - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler - .When("*") - .Respond(req => - { - bool disableReachabilityChecker = req.Content == null; - if (disableReachabilityChecker) throw new HttpRequestException(); - - counter++; - throw new HttpRequestException(); - }); - - return messageHandler; - }; - - using (var kernel = - new TestingKernel( - k => - { - k.Rebind().To().InSingletonScope(); - k.Rebind>().ToMethod(c => messageHandlerFactory); - }, dict) - ) - { - - var providerFactory = kernel.Get>(); - var serviceProxy = providerFactory("DemoService"); - serviceProxy.DefaultPort = port; - - var request = new HttpServiceRequest("testMethod", null, new Dictionary()); - - Func act = () => serviceProxy.Invoke(request, typeof(string)); - await act.ShouldThrowAsync(); - counter.ShouldBe(2); - } - } - - - [Test] - public async Task OneHostHasNetworkErrorShouldMoveToNextHost() - { - var port = DisposablePort.GetPort().Port; - var dict = new Dictionary - { - {"Discovery.Services.DemoService.Source", "Config"}, - {"Discovery.Services.DemoService.Hosts", "host1,host2"}, - {"Discovery.Services.DemoService.DefaultPort", port.ToString()} - }; - - int counter = 0; - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler - .When("*") - .Respond(req => - { - - if (req.Method == HttpMethod.Get && req.RequestUri.Scheme == "https") - throw new HttpRequestException(); - - counter++; - - if (req.RequestUri.Host == "host1") throw new HttpRequestException(); - return HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}'"); - }); - return messageHandler; - }; - - using (var kernel = - new TestingKernel( - k => - { - k.Rebind().To().InSingletonScope(); - k.Rebind>().ToMethod(c => messageHandlerFactory); - }, dict) - ) - { - - var providerFactory = kernel.Get>(); - var serviceProxy = providerFactory("DemoService"); - serviceProxy.DefaultPort = port; - TracingContext.SetRequestID("1"); - - var request = new HttpServiceRequest("testMethod", null, new Dictionary()); - - for (int i = 0; i < 3; i++) - { - var server = await serviceProxy.Invoke(request, typeof(string)); - server.ShouldBe("host2"); - } - - counter.ShouldBe(3); - } - } - - - [Test] - public async Task RequestContextOverrideShouldFailOnFirstAttempt() - { - var port = DisposablePort.GetPort().Port; - var dict = new Dictionary - { - {"Discovery.Services.DemoService.Source", "Config"}, - {"Discovery.Services.DemoService.Hosts", "notImpotent"}, - {"Discovery.Services.DemoService.DefaultPort", port.ToString()} - }; - - int counter = 0; - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler - .When("*") - .Respond(req => - { - if (req.Method == HttpMethod.Get && req.RequestUri.Scheme == "https") - throw new HttpRequestException(); - - counter++; - - throw new HttpRequestException(); - }); - return messageHandler; - }; - - using (var kernel = - new TestingKernel( - k => - { - k.Rebind().To().InSingletonScope(); - k.Rebind>().ToMethod(c => messageHandlerFactory); - }, dict) - ) - { - var providerFactory = kernel.Get>(); - var serviceProxy = providerFactory("DemoService"); - serviceProxy.DefaultPort = port; - - //Disable TracingContext.SetRequestID("1"); - - CallContext.FreeNamedDataSlot("#ORL_RC"); - - string overrideHost = "override-host"; - int overridePort = 5318; - TracingContext.SetHostOverride("DemoService", overrideHost, overridePort); - - var request = new HttpServiceRequest("testMethod", null, new Dictionary()); - - for (int i = 0; i < 3; i++) - { - Func act = () => serviceProxy.Invoke(request, typeof(string)); - - await act.ShouldThrowAsync(); - } - counter.ShouldBe(3); - } - } - - - [Test] - public async Task FailedHostShouldBeRemovedFromHostList() - { - var port = DisposablePort.GetPort().Port; - var dict = new Dictionary - { - {"Discovery.Services.DemoService.Source", "local"}, - {"Discovery.Services.DemoService.DefaultPort", port.ToString()} - }; - - int counter = 0; - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler - .When("*") - .Respond(req => - { - bool disableReachabilityChecker = req.Content == null; - if (disableReachabilityChecker) throw new HttpRequestException(); - counter++; - - throw new HttpRequestException(); - }); - return messageHandler; - }; - - using (var kernel = - new TestingKernel( - k => - { - k.Rebind().To().InSingletonScope(); - k.Rebind>().ToMethod(c => messageHandlerFactory); - }, dict) - ) - { - - var providerFactory = kernel.Get>(); - var serviceProxy = providerFactory("DemoService"); - serviceProxy.DefaultPort = port; - - //Disable TracingContext.SetRequestID("1"); - - CallContext.FreeNamedDataSlot("#ORL_RC"); - - var request = new HttpServiceRequest("testMethod", null, new Dictionary()); - - for (int i = 0; i < 10; i++) - { - Func act = () => serviceProxy.Invoke(request, typeof(string)); - - await act.ShouldThrowAsync(); - } - counter.ShouldBe(1); - } - } - - - - - [Test] - public async Task ToUpper_MethodCallSucceeds_ResultIsCorrect() - { - var expected = "AAAA"; - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler.When("*").Respond(HttpResponseFactory.GetResponse(content: $"'{expected}'")); - - return messageHandler; - }; - - unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); - - var actual = await CreateClient().ToUpper("aaaa"); - - actual.ShouldBe(expected); - } - - [Test] - public async Task ToUpper_MethodCallFailsWithRequestException_CorrectExceptionIsThrown() - { - var expected = new RequestException("You request is invalid.").ThrowAndCatch(); - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler.When("*").Respond(HttpResponseFactory.GetResponseWithException(unitTesting.Get(), expected)); - - return messageHandler; - }; - - unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); - - Func action = async () => await CreateClient().ToUpper("aaaa"); - - action.ShouldThrow().Message.Should().Be(expected.Message); - } - - [Test] - public async Task ToUpper_MethodCallFailsWithCustomerFacingException_CorrectExceptionIsThrown() - { - var expected = new RequestException("You action is invalid, Mr. Customer.", 30000).ThrowAndCatch(); - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler.When("*").Respond(req => - { - return HttpResponseFactory.GetResponseWithException(ExceptionSerializer, expected); - }); - - return messageHandler; - }; - unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); - var actual = CreateClient().ToUpper("aaaa").ShouldThrow(); - - actual.Message.ShouldBe(expected.Message); - actual.ErrorCode.ShouldBe(expected.ErrorCode); - } - - [Test] - public async Task ToUpper_MethodCallFailsWithEnvironmentException_CorrectExceptionIsThrown() - { - var expected = new EnvironmentException("You environment is invalid.").ThrowAndCatch(); - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler.When("*").Respond(HttpResponseFactory.GetResponseWithException(ExceptionSerializer, expected)); - - return messageHandler; - }; - unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); - - var actual = CreateClient().ToUpper("aaaa").ShouldThrow(); - - actual.Message.ShouldBe(expected.Message); - } - - - - - [Test] - public async Task ToUpper_MethodCallFailsWithRemoteServiceException_CorrectExceptionIsThrown() - { - var expected = new RemoteServiceException("A service is invalid.", "someUri").ThrowAndCatch(); - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler.When("*").Respond(HttpResponseFactory.GetResponseWithException(ExceptionSerializer, expected)); - - return messageHandler; - }; - - unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); - - var actual = CreateClient().ToUpper("aaaa").ShouldThrow(); - - actual.Message.ShouldBe(expected.Message); - actual.RequestedUri.ShouldBe(expected.RequestedUri); - actual.InnerException.ShouldBeNull(); - } - - [Test] - public async Task ToUpper_MethodCallFailsWithProgrammaticException_CorrectExceptionIsThrown() - { - var expected = new ProgrammaticException("You code is invalid.").ThrowAndCatch(); - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler.When("*").Respond(HttpResponseFactory.GetResponseWithException(ExceptionSerializer, expected)); - - return messageHandler; - }; - unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); - - var actual = CreateClient().ToUpper("aaaa").ShouldThrow(); - - actual.InnerException.ShouldBeOfType(); - actual.InnerException.Message.ShouldBe(expected.Message); - } - - [Test] - public async Task ToUpper_MethodCallFailsWithInvalidJson_CorrectExceptionIsThrown() - { - string badJson = "not JSON!"; - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler.When("*").Respond(HttpResponseFactory.GetResponse(HttpStatusCode.InternalServerError, content: badJson)); - - return messageHandler; - }; - - unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); - - var actual = CreateClient().ToUpper("aaaa").ShouldThrow(); - - actual.EncryptedTags["responseContent"].ShouldBe(badJson); - actual.InnerException.ShouldBeAssignableTo(); - } - - [Test] - public async Task HttpsNotListening_ContinueWithHttp() - { - var host = "host1"; - var httpsPortOffset = 5; - var port = DisposablePort.GetPort().Port; - var dict = new Dictionary - { - {"Discovery.Services.DemoService.Source", "Config"}, - {"Discovery.Services.DemoService.Hosts", host}, - {"Discovery.Services.DemoService.DefaultPort", port.ToString()}, - {"Discovery.Services.DemoService.TryHttps", "true"} - }; - - int httpsTestCount = 0; - - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler - .When("https://*") - .Respond(req => - { - if (req.RequestUri.AbsoluteUri == - $"https://{host}:{port + httpsPortOffset}/") - httpsTestCount++; - - throw new HttpRequestException(); - }); - messageHandler - .When("http://*") - .Respond(req => - { - if (req.RequestUri.AbsoluteUri == $"http://{host}:{port}/DemoService.testMethod") - return HttpResponseFactory.GetResponse(content: "'someResponse'"); - throw new HttpRequestException("Invalid uri"); - }); - - return messageHandler; - }; - - using (var kernel = - new TestingKernel( - k => - { - k.Rebind().To().InSingletonScope(); - k.Rebind>().ToMethod(c => messageHandlerFactory); - var getConfig = k.Get>(); - k.Rebind>().ToMethod(c => - { - var config = getConfig(); - return () => config; - }); - }, dict) - ) - { - - var providerFactory = kernel.Get>(); - var serviceProxy = providerFactory("DemoService"); - serviceProxy.DefaultPort = port; - TracingContext.SetRequestID("1"); - - var request = new HttpServiceRequest("testMethod", null, new Dictionary()); - - for (int i = 0; i < 10; i++) - { - var server = await serviceProxy.Invoke(request, typeof(string)); - - server.ShouldBe("someResponse"); - } - - Assert.That(() => httpsTestCount, Is.EqualTo(1).After(10).Seconds.PollEvery(1).Seconds); - } - } - - - [Test] - public async Task HttpsListening_CallHttpsAfterFirstHttpCall() - { - var host = "host1"; - var httpsPortOffset = 5; - var port = DisposablePort.GetPort().Port; - var dict = new Dictionary - { - {"Discovery.Services.DemoService.Source", "Config"}, - {"Discovery.Services.DemoService.Hosts", host}, - {"Discovery.Services.DemoService.DefaultPort", port.ToString()}, - {"Discovery.Services.DemoService.TryHttps", "true"} - }; - - int httpsTestCount = 0; - - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler - .When("https://*") - .Respond(req => - { - if (req.RequestUri.AbsoluteUri == $"https://{host}:{port + httpsPortOffset}/") - { - httpsTestCount++; - return HttpResponseFactory.GetResponse(content: "'some HTTPS response'"); - } - if (req.RequestUri.AbsoluteUri == $"https://{host}:{port + httpsPortOffset}/DemoService.testMethod") - return HttpResponseFactory.GetResponse(content: "'some HTTPS response'"); - throw new HttpRequestException("Invalid uri"); - }); - messageHandler - .When("http://*") - .Respond(req => - { - if (req.RequestUri.AbsoluteUri == $"http://{host}:{port}/DemoService.testMethod") - return HttpResponseFactory.GetResponse(content: "'some HTTP response'"); - throw new HttpRequestException("Invalid uri"); - }); - - return messageHandler; - }; - - using (var kernel = - new TestingKernel( - k => - { - k.Rebind().To().InSingletonScope(); - k.Rebind>().ToMethod(c => messageHandlerFactory); - var getConfig = k.Get>(); - k.Rebind>().ToMethod(c => - { - var config = getConfig(); - return () => config; - }); - }, dict) - ) - { - - var providerFactory = kernel.Get>(); - var serviceProxy = providerFactory("DemoService"); - serviceProxy.DefaultPort = port; - TracingContext.SetRequestID("1"); - - var request = new HttpServiceRequest("testMethod", null, new Dictionary()); - - for (int i = 0; i < 10; i++) - { - bool httpsTestFinished = httpsTestCount > 0; - - var server = await serviceProxy.Invoke(request, typeof(string)); - - server.ShouldBe( httpsTestFinished ? "some HTTPS response" : "some HTTP response"); - } - - Assert.That(() => httpsTestCount, Is.EqualTo(1).After(10).Seconds.PollEvery(1).Seconds); - } - } - - [Test] - public async Task HttpsStoppedListening_FallbackToHttp() - { - var host = "host1"; - var httpsPortOffset = 5; - var port = DisposablePort.GetPort().Port; - var dict = new Dictionary - { - {"Discovery.Services.DemoService.Source", "Config"}, - {"Discovery.Services.DemoService.Hosts", host}, - {"Discovery.Services.DemoService.DefaultPort", port.ToString()}, - {"Discovery.Services.DemoService.TryHttps", "true"} - }; - - int httpsTestCount = 0; - bool httpsMethodCalled = false; - - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler - .When("https://*") - .Respond(req => - { - if (httpsMethodCalled) - throw new HttpRequestException("", new WebException("", WebExceptionStatus.ProtocolError)); - if (req.RequestUri.AbsoluteUri == $"https://{host}:{port + httpsPortOffset}/") - { - httpsTestCount++; - return HttpResponseFactory.GetResponse(content: "'some HTTPS response'"); - } - - if (req.RequestUri.AbsoluteUri == $"https://{host}:{port + httpsPortOffset}/DemoService.testMethod") - { - httpsMethodCalled = true; - return HttpResponseFactory.GetResponse(content: "'some HTTPS response'"); - } - - throw new HttpRequestException("Invalid uri"); - }); - messageHandler - .When("http://*") - .Respond(req => - { - if (req.RequestUri.AbsoluteUri == $"http://{host}:{port}/DemoService.testMethod") - return HttpResponseFactory.GetResponse(content: "'some HTTP response'"); - if (req.RequestUri.AbsoluteUri == $"http://{host}:{port}/") - return HttpResponseFactory.GetResponse(content: "'{X-Gigya-ServerHostname: someValue}'"); - throw new HttpRequestException("Invalid uri"); - }); - - return messageHandler; - }; - - using (var kernel = - new TestingKernel( - k => - { - k.Rebind().To().InSingletonScope(); - k.Rebind>().ToMethod(c => messageHandlerFactory); - var getConfig = k.Get>(); - k.Rebind>().ToMethod(c => - { - var config = getConfig(); - config.UseHttpsOverride = false; - - return () => config; - }); - }, dict) - ) - { - - var providerFactory = kernel.Get>(); - var serviceProxy = providerFactory("DemoService"); - serviceProxy.DefaultPort = port; - TracingContext.SetRequestID("1"); - - var request = new HttpServiceRequest("testMethod", null, new Dictionary()); - - var server = await serviceProxy.Invoke(request, typeof(string)); - - server.ShouldBe("some HTTP response"); - - Assert.That(() => httpsTestCount, Is.EqualTo(1).After(10).Seconds.PollEvery(1).Seconds); - - server = await serviceProxy.Invoke(request, typeof(string)); - - server.ShouldBe("some HTTPS response"); - - server = await serviceProxy.Invoke(request, typeof(string)); - - server.ShouldBe("some HTTP response"); - } - } - - [Test] - public async Task HttpsDisabled_NoCertificate_CallSucceeds() - { - var host = "host1"; - var httpsPortOffset = 5; - var port = DisposablePort.GetPort().Port; - var dict = new Dictionary - { - {"Discovery.Services.DemoService.Source", "Config"}, - {"Discovery.Services.DemoService.Hosts", host}, - {"Discovery.Services.DemoService.DefaultPort", port.ToString()}, - {"Discovery.Services.DemoService.UseHttpsOverride", "false"} - }; - - int httpsTestCount = 0; - bool httpsMethodCalled = false; - - Func messageHandlerFactory = _=> - { - var messageHandler = new MockHttpMessageHandler(); - messageHandler - .When("https://*") - .Respond(req => - HttpResponseFactory.GetResponseWithException(ExceptionSerializer, new SocketException())); - - messageHandler - .When("http://*") - .Respond(req => HttpResponseFactory.GetResponse(content: "'some HTTP response'")); - - return messageHandler; - }; - - using (var kernel = - new TestingKernel( - k => - { - k.Rebind().To().InSingletonScope(); - k.Rebind>().ToMethod(c => messageHandlerFactory); - - var certificateLocator = Substitute.For(); - certificateLocator - .When(cl => cl.GetCertificate(Arg.Any())) - .Do(x => throw new Exception()); - k.Rebind().ToConstant(certificateLocator); - - var httpsAuthenticator = Substitute.For(); - httpsAuthenticator - .When(a => a.AddHttpMessageHandlerAuthentication(Arg.Any(), Arg.Any())) - .Do(x => throw new Exception()); - k.Rebind().ToConstant(httpsAuthenticator); - }, dict) - ) - { - - var providerFactory = kernel.Get>(); - var serviceProxy = providerFactory("DemoService"); - serviceProxy.DefaultPort = port; - TracingContext.SetRequestID("1"); - - var request = new HttpServiceRequest("testMethod", null, new Dictionary()); - - await serviceProxy.Invoke(request, typeof(string)); - } - } - } -} + public Dictionary Tags { get; set; } + } + + public class Host1 + { + [JsonRequired] + public string ServiceName { get; set; } + + [JsonRequired] + public string Host { get; set; } + + [JsonRequired] + public int Port { get; set; } + } + + public class Overrides + { + [JsonRequired] + public List Hosts { get; set; } + + [JsonRequired] + public string PreferredEnvironment { get; set; } + + [JsonProperty] + public CacheSuppress? SuppressCaching { get; set; } + } + + public class Target + { + [JsonRequired] + public string MethodName { get; set; } + } + + public class GigyaRequestProtocol + { + [JsonRequired] + public Arguments Arguments { get; set; } + + [JsonRequired] + public TracingData TracingData { get; set; } + + [JsonRequired] + public Overrides Overrides { get; set; } + + [JsonRequired] + public Target Target { get; set; } + } + + + [Test] + public async Task RequestContextShouldOverrideHostOnly() + { + const string serviceName = "DemoService"; + int defaultPort = DisposablePort.GetPort().Port; + + var dict = new Dictionary { + {$"Discovery.Services.{serviceName}.Source", "Config"}, + {$"Discovery.Services.{serviceName}.Hosts", "host1"}, + {$"Discovery.Services.{serviceName}.DefaultPort", defaultPort.ToString()} + }; + + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler + .When("*") + .Respond(req => + { + if (req.Method == HttpMethod.Get && req.RequestUri.Scheme == "https") + throw new HttpRequestException(); + + return HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}:{req.RequestUri.Port}'"); + }); + return messageHandler; + }; + + var kernel = new TestingKernel(k => + { + k.Rebind().To().InSingletonScope(); + k.Rebind>().ToMethod(c => messageHandlerFactory); + }, dict); + var providerFactory = kernel.Get>(); + var serviceProxy = providerFactory(serviceName); + + string overrideHost = "override-host"; + + + TracingContext.SetHostOverride(serviceName, overrideHost); + + var request = new HttpServiceRequest("testMethod", null, new Dictionary()); + for (int i = 0; i < 50; i++) + { + var host = (string)await serviceProxy.Invoke(request, typeof(string)); + host.ShouldBe($"{overrideHost}:{defaultPort}"); + } + + } + + + [Test] + public async Task AllHostsAreHavingNetworkErrorsShouldTryEachOnce() + { + var port = DisposablePort.GetPort().Port; + var dict = new Dictionary { + {"Discovery.Services.DemoService.Source", "Config"}, + {"Discovery.Services.DemoService.Hosts", "host1,host2"}, + {"Discovery.Services.DemoService.DefaultPort", port.ToString()} + }; + + int counter = 0; + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler + .When("*") + .Respond(req => + { + bool disableReachabilityChecker = req.Content == null; + if (disableReachabilityChecker) throw new HttpRequestException(); + + counter++; + throw new HttpRequestException(); + }); + + return messageHandler; + }; + + using (var kernel = + new TestingKernel( + k => + { + k.Rebind().To().InSingletonScope(); + k.Rebind>().ToMethod(c => messageHandlerFactory); + }, dict) + ) + { + + var providerFactory = kernel.Get>(); + var serviceProxy = providerFactory("DemoService"); + serviceProxy.DefaultPort = port; + + var request = new HttpServiceRequest("testMethod", null, new Dictionary()); + + Func act = () => serviceProxy.Invoke(request, typeof(string)); + await act.ShouldThrowAsync(); + counter.ShouldBe(2); + } + } + + + [Test] + public async Task OneHostHasNetworkErrorShouldMoveToNextHost() + { + var port = DisposablePort.GetPort().Port; + var dict = new Dictionary + { + {"Discovery.Services.DemoService.Source", "Config"}, + {"Discovery.Services.DemoService.Hosts", "host1,host2,host3"}, + {"Discovery.Services.DemoService.DefaultPort", port.ToString()} + }; + int retries = 5; + int counter = 0; + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler + .When("*") + .Respond(req => + { + + if (req.Method == HttpMethod.Get && req.RequestUri.Scheme == "https") + throw new HttpRequestException(); + + if (req.RequestUri.Host == "host1" || req.RequestUri.Host == "host3") throw new HttpRequestException(); + + counter++; + + return HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}'"); + }); + return messageHandler; + }; + + using (var kernel = + new TestingKernel( + k => + { + k.Rebind().To().InSingletonScope(); + k.Rebind>().ToMethod(c => messageHandlerFactory); + }, dict) + ) + { + + var providerFactory = kernel.Get>(); + var serviceProxy = providerFactory("DemoService"); + serviceProxy.DefaultPort = port; + TracingContext.SetRequestID("1"); + + var request = new HttpServiceRequest("testMethod", null, new Dictionary()); + + for (int i = 0; i < retries; i++) + { + var server = await serviceProxy.Invoke(request, typeof(string)); + server.ShouldBe("host2"); + } + + counter.ShouldBe(retries); + } + } + + + [Test] + public async Task RequestContextOverrideShouldFailOnFirstAttempt() + { + var port = DisposablePort.GetPort().Port; + var dict = new Dictionary + { + {"Discovery.Services.DemoService.Source", "Config"}, + {"Discovery.Services.DemoService.Hosts", "notImpotent"}, + {"Discovery.Services.DemoService.DefaultPort", port.ToString()} + }; + + int counter = 0; + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler + .When("*") + .Respond(req => + { + if (req.Method == HttpMethod.Get && req.RequestUri.Scheme == "https") + throw new HttpRequestException(); + + counter++; + + throw new HttpRequestException(); + }); + return messageHandler; + }; + + using (var kernel = + new TestingKernel( + k => + { + k.Rebind().To().InSingletonScope(); + k.Rebind>().ToMethod(c => messageHandlerFactory); + }, dict) + ) + { + var providerFactory = kernel.Get>(); + var serviceProxy = providerFactory("DemoService"); + serviceProxy.DefaultPort = port; + + + string overrideHost = "override-host"; + int overridePort = 5318; + TracingContext.SetHostOverride("DemoService", overrideHost, overridePort); + + var request = new HttpServiceRequest("testMethod", null, new Dictionary()); + + for (int i = 0; i < 3; i++) + { + Func act = () => serviceProxy.Invoke(request, typeof(string)); + + await act.ShouldThrowAsync(); + } + counter.ShouldBe(3); + } + } + + + [Test] + public async Task FailedHostShouldBeRemovedFromHostList() + { + var port = DisposablePort.GetPort().Port; + var dict = new Dictionary + { + {"Discovery.Services.DemoService.Source", "local"}, + {"Discovery.Services.DemoService.DefaultPort", port.ToString()} + }; + + int counter = 0; + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler + .When("*") + .Respond(req => + { + bool disableReachabilityChecker = req.Content == null; + if (disableReachabilityChecker) throw new HttpRequestException(); + counter++; + + throw new HttpRequestException(); + }); + return messageHandler; + }; + + using (var kernel = + new TestingKernel( + k => + { + k.Rebind().To().InSingletonScope(); + k.Rebind>().ToMethod(c => messageHandlerFactory); + }, dict) + ) + { + + var providerFactory = kernel.Get>(); + var serviceProxy = providerFactory("DemoService"); + serviceProxy.DefaultPort = port; + + var request = new HttpServiceRequest("testMethod", null, new Dictionary()); + + for (int i = 0; i < 10; i++) + { + Func act = () => serviceProxy.Invoke(request, typeof(string)); + + await act.ShouldThrowAsync(); + } + counter.ShouldBe(1); + } + } + + + + + [Test] + public async Task ToUpper_MethodCallSucceeds_ResultIsCorrect() + { + var expected = "AAAA"; + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler.When("*").Respond(HttpResponseFactory.GetResponse(content: $"'{expected}'")); + + return messageHandler; + }; + + unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); + + var actual = await CreateClient().ToUpper("aaaa"); + + actual.ShouldBe(expected); + } + + [Test] + public void ToUpper_MethodCallFailsWithRequestException_CorrectExceptionIsThrown() + { + var expected = new RequestException("You request is invalid.").ThrowAndCatch(); + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler.When("*").Respond(HttpResponseFactory.GetResponseWithException(unitTesting.Get(), expected)); + + return messageHandler; + }; + + unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); + + Func action = async () => await CreateClient().ToUpper("aaaa"); + + action.ShouldThrow().Message.Should().Be(expected.Message); + } + + [Test] + public void ToUpper_MethodCallFailsWithCustomerFacingException_CorrectExceptionIsThrown() + { + var expected = new RequestException("You action is invalid, Mr. Customer.", 30000).ThrowAndCatch(); + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler.When("*").Respond(req => + { + return HttpResponseFactory.GetResponseWithException(ExceptionSerializer, expected); + }); + + return messageHandler; + }; + unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); + var actual = CreateClient().ToUpper("aaaa").ShouldThrow(); + + actual.Message.ShouldBe(expected.Message); + actual.ErrorCode.ShouldBe(expected.ErrorCode); + } + + [Test] + public void ToUpper_MethodCallFailsWithEnvironmentException_CorrectExceptionIsThrown() + { + var expected = new EnvironmentException("You environment is invalid.").ThrowAndCatch(); + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler.When("*").Respond(HttpResponseFactory.GetResponseWithException(ExceptionSerializer, expected)); + + return messageHandler; + }; + unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); + + var actual = CreateClient().ToUpper("aaaa").ShouldThrow(); + + actual.Message.ShouldBe(expected.Message); + } + + [Test] + public void ToUpper_MethodCallFailsWithRemoteServiceException_CorrectExceptionIsThrown() + { + var expected = new RemoteServiceException("A service is invalid.", "someUri").ThrowAndCatch(); + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler.When("*").Respond(HttpResponseFactory.GetResponseWithException(ExceptionSerializer, expected)); + + return messageHandler; + }; + + unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); + + var actual = CreateClient().ToUpper("aaaa").ShouldThrow(); + + actual.Message.ShouldBe(expected.Message); + actual.RequestedUri.ShouldBe(expected.RequestedUri); + actual.InnerException.ShouldBeNull(); + } + + [Test] + public void ToUpper_MethodCallFailsWithProgrammaticException_CorrectExceptionIsThrown() + { + var expected = new ProgrammaticException("You code is invalid.").ThrowAndCatch(); + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler.When("*").Respond(HttpResponseFactory.GetResponseWithException(ExceptionSerializer, expected)); + + return messageHandler; + }; + unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); + + var actual = CreateClient().ToUpper("aaaa").ShouldThrow(); + + actual.InnerException.ShouldBeOfType(); + actual.InnerException.Message.ShouldBe(expected.Message); + } + + [Test] + public void ToUpper_MethodCallFailsWithInvalidJson_CorrectExceptionIsThrown() + { + string badJson = "not JSON!"; + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler.When("*").Respond(HttpResponseFactory.GetResponse(HttpStatusCode.InternalServerError, content: badJson)); + + return messageHandler; + }; + + unitTesting.Rebind>().ToMethod(c => messageHandlerFactory); + + var actual = CreateClient().ToUpper("aaaa").ShouldThrow(); + + actual.EncryptedTags["responseContent"].ShouldBe(badJson); + actual.InnerException.ShouldBeAssignableTo(); + } + + [Test] + public async Task HttpsNotListening_ContinueWithHttp() + { + var host = "host1"; + var httpsPortOffset = 5; + var port = DisposablePort.GetPort().Port; + var dict = new Dictionary + { + {"Discovery.Services.DemoService.Source", "Config"}, + {"Discovery.Services.DemoService.Hosts", host}, + {"Discovery.Services.DemoService.DefaultPort", port.ToString()}, + {"Discovery.Services.DemoService.TryHttps", "true"} + }; + + int httpsTestCount = 0; + + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler + .When("https://*") + .Respond(req => + { + if (req.RequestUri.AbsoluteUri == + $"https://{host}:{port + httpsPortOffset}/") + httpsTestCount++; + + throw new HttpRequestException(); + }); + messageHandler + .When("http://*") + .Respond(req => + { + if (req.RequestUri.AbsoluteUri == $"http://{host}:{port}/DemoService.testMethod") + return HttpResponseFactory.GetResponse(content: "'someResponse'"); + throw new HttpRequestException("Invalid uri"); + }); + + return messageHandler; + }; + + using (var kernel = + new TestingKernel( + k => + { + k.Rebind().To().InSingletonScope(); + k.Rebind>().ToMethod(c => messageHandlerFactory); + var getConfig = k.Get>(); + k.Rebind>().ToMethod(c => + { + var config = getConfig(); + return () => config; + }); + }, dict) + ) + { + + var providerFactory = kernel.Get>(); + var serviceProxy = providerFactory("DemoService"); + serviceProxy.DefaultPort = port; + TracingContext.SetRequestID("1"); + + var request = new HttpServiceRequest("testMethod", null, new Dictionary()); + + for (int i = 0; i < 10; i++) + { + var server = await serviceProxy.Invoke(request, typeof(string)); + + server.ShouldBe("someResponse"); + } + + Assert.That(() => httpsTestCount, Is.EqualTo(1).After(10).Seconds.PollEvery(1).Seconds); + } + } + + [Test] + public async Task HttpsListening_CallHttpsAfterFirstHttpCall() + { + var host = "host1"; + var httpsPortOffset = 5; + var port = DisposablePort.GetPort().Port; + var dict = new Dictionary + { + {"Discovery.Services.DemoService.Source", "Config"}, + {"Discovery.Services.DemoService.Hosts", host}, + {"Discovery.Services.DemoService.DefaultPort", port.ToString()}, + {"Discovery.Services.DemoService.TryHttps", "true"} + }; + + int httpTestCount = 0; + int httpsTestCount = 0; + int httpsReachabilityCount = 0; + + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler + .When("https://*") + .Respond(req => + { + if (req.RequestUri.AbsoluteUri == $"https://{host}:{port + httpsPortOffset}/") + { + httpsReachabilityCount++; + return HttpResponseFactory.GetResponse(content: "'some HTTPS response'"); + } + if (req.RequestUri.AbsoluteUri == $"https://{host}:{port + httpsPortOffset}/DemoService.testMethod") + { + httpsTestCount++; + return HttpResponseFactory.GetResponse(content: "'some HTTPS response'"); + } + throw new HttpRequestException("Invalid uri"); + }); + messageHandler + .When("http://*") + .Respond(req => + { + if (req.RequestUri.AbsoluteUri == $"http://{host}:{port}/DemoService.testMethod") + { + httpTestCount++; + return HttpResponseFactory.GetResponse(content: "'some HTTP response'"); + } + throw new HttpRequestException("Invalid uri"); + }); + + return messageHandler; + }; + + using (var kernel = + new TestingKernel( + k => + { + k.Rebind().To().InSingletonScope(); + k.Rebind>().ToMethod(c => messageHandlerFactory); + var getConfig = k.Get>(); + k.Rebind>().ToMethod(c => + { + var config = getConfig(); + return () => config; + }); + }, dict) + ) + { + + var providerFactory = kernel.Get>(); + var serviceProxy = providerFactory("DemoService"); + serviceProxy.DefaultPort = port; + TracingContext.SetRequestID("1"); + + var request = new HttpServiceRequest("testMethod", null, new Dictionary()); + + for (int i = 0; i < 10; i++) + { + // adding delay to allow ServiceProxyProvider.RunHttpsAvailabilityTest to complete it's execution + if (httpsReachabilityCount == 0) + await Task.Delay(100); + + var server = await serviceProxy.Invoke(request, typeof(string)); + + bool httpsTestFinished = httpsTestCount > 0; + + server.ShouldBe(httpsTestFinished ? "some HTTPS response" : "some HTTP response", $"Iteration #{i}, httpsTestCount:{httpsTestCount}"); + } + + string msg = $" httpTestCount: {httpTestCount}, httpsTestCount: {httpsTestCount}, httpsReachabilityCount: {httpsReachabilityCount}"; + Assert.Greater(httpTestCount, 0, "First HTTP call is missing." + msg); + Assert.Greater(httpsTestCount, 0, "First HTTPS call is missing." + msg); + Assert.Greater(httpsReachabilityCount, 0, "Rechability call is missing." + msg); + } + } + + [Test] + public async Task HttpsStoppedListening_FallbackToHttp() + { + var host = "host1"; + var httpsPortOffset = 5; + var port = DisposablePort.GetPort().Port; + var dict = new Dictionary + { + {"Discovery.Services.DemoService.Source", "Config"}, + {"Discovery.Services.DemoService.Hosts", host}, + {"Discovery.Services.DemoService.DefaultPort", port.ToString()}, + {"Discovery.Services.DemoService.TryHttps", "true"} + }; + + int httpsTestCount = 0; + bool httpsMethodCalled = false; + + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler + .When("https://*") + .Respond(req => + { + if (httpsMethodCalled) + throw new HttpRequestException("Element not found", new WebException("", WebExceptionStatus.ProtocolError)); + if (req.RequestUri.AbsoluteUri == $"https://{host}:{port + httpsPortOffset}/") + { + httpsTestCount++; + return HttpResponseFactory.GetResponse(content: "'some HTTPS response'"); + } + + if (req.RequestUri.AbsoluteUri == $"https://{host}:{port + httpsPortOffset}/DemoService.testMethod") + { + httpsMethodCalled = true; + return HttpResponseFactory.GetResponse(content: "'some HTTPS response'"); + } + + throw new HttpRequestException("Invalid uri"); + }); + messageHandler + .When("http://*") + .Respond(req => + { + if (req.RequestUri.AbsoluteUri == $"http://{host}:{port}/DemoService.testMethod") + return HttpResponseFactory.GetResponse(content: "'some HTTP response'"); + if (req.RequestUri.AbsoluteUri == $"http://{host}:{port}/") + return HttpResponseFactory.GetResponse(content: "'{X-Gigya-ServerHostname: someValue}'"); + throw new HttpRequestException("Invalid uri"); + }); + + return messageHandler; + }; + + using (var kernel = + new TestingKernel( + k => + { + k.Rebind().To().InSingletonScope(); + k.Rebind>().ToMethod(c => messageHandlerFactory); + var getConfig = k.Get>(); + k.Rebind>().ToMethod(c => + { + var config = getConfig(); + config.UseHttpsOverride = false; + + return () => config; + }); + }, dict) + ) + { + + var providerFactory = kernel.Get>(); + var serviceProxy = providerFactory("DemoService"); + serviceProxy.DefaultPort = port; + TracingContext.SetRequestID("1"); + + var request = new HttpServiceRequest("testMethod", null, new Dictionary()); + + var server = await serviceProxy.Invoke(request, typeof(string)); + + server.ShouldBe("some HTTP response"); + + Assert.That(() => httpsTestCount, Is.EqualTo(1).After(10).Seconds.PollEvery(1).Seconds); + + server = await serviceProxy.Invoke(request, typeof(string)); + + server.ShouldBe("some HTTPS response"); + + server = await serviceProxy.Invoke(request, typeof(string)); + + server.ShouldBe("some HTTP response"); + } + } + + [Test] + public async Task HttpsDisabled_NoCertificate_CallSucceeds() + { + var host = "host1"; + var httpsPortOffset = 5; + var port = DisposablePort.GetPort().Port; + var dict = new Dictionary + { + {"Discovery.Services.DemoService.Source", "Config"}, + {"Discovery.Services.DemoService.Hosts", host}, + {"Discovery.Services.DemoService.DefaultPort", port.ToString()}, + {"Discovery.Services.DemoService.UseHttpsOverride", "false"} + }; + + int httpsTestCount = 0; + bool httpsMethodCalled = false; + + Func messageHandlerFactory = _ => + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler + .When("https://*") + .Respond(req => + HttpResponseFactory.GetResponseWithException(ExceptionSerializer, new SocketException())); + + messageHandler + .When("http://*") + .Respond(req => HttpResponseFactory.GetResponse(content: "'some HTTP response'")); + + return messageHandler; + }; + + using (var kernel = + new TestingKernel( + k => + { + k.Rebind().To().InSingletonScope(); + k.Rebind>().ToMethod(c => messageHandlerFactory); + + var certificateLocator = Substitute.For(); + certificateLocator + .When(cl => cl.GetCertificate(Arg.Any())) + .Do(x => throw new Exception()); + k.Rebind().ToConstant(certificateLocator); + + var httpsAuthenticator = Substitute.For(); + httpsAuthenticator + .When(a => a.AddHttpMessageHandlerAuthentication(Arg.Any(), Arg.Any())) + .Do(x => throw new Exception()); + k.Rebind().ToConstant(httpsAuthenticator); + }, dict) + ) + { + + var providerFactory = kernel.Get>(); + var serviceProxy = providerFactory("DemoService"); + serviceProxy.DefaultPort = port; + TracingContext.SetRequestID("1"); + + var request = new HttpServiceRequest("testMethod", null, new Dictionary()); + + await serviceProxy.Invoke(request, typeof(string)); + } + } + + [Test] + [TestCase(true)] + [TestCase(false)] + public async Task RequestsWithHttpRequestsExceptionsContainingConfiguredSubstringsShouldNotBetreatedAsHttpsErrorSuspect(bool handleErrorAsCertificateError) + { + var port = DisposablePort.GetPort().Port; + var dict = new Dictionary { + {"Discovery.Services.DemoService.Source", "Config"}, + {"Discovery.Services.DemoService.Hosts", "host1,host2"}, + {"Discovery.ServiceHttpsOverride", "True"}, + {"Discovery.TryHttps", "True"}, + {"Discovery.Services.DemoService.DefaultPort", port.ToString()}, + }; + + if (false == handleErrorAsCertificateError) + dict.Add("Discovery.CertificateErrorMessageSubstrings-collection", "[\"foo\"]"); + + bool isFirstRequest = true; + + bool isSecondRequestFirstAttempt = true; + + bool usedHttpsInSecondRequest = false; + + Func messageHandlerFactory = _=> + { + var messageHandler = new MockHttpMessageHandler(); + messageHandler + .When("*") + .Respond(req => + { + if (req.RequestUri.AbsolutePath == "/") + return HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}'"); + + if (isFirstRequest) + { + isFirstRequest = false; + return HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}'"); + } + + if (isSecondRequestFirstAttempt) + { + isSecondRequestFirstAttempt = false; + throw new HttpRequestException("foo"); + } + + usedHttpsInSecondRequest = req.RequestUri.Scheme == "https"; + + return HttpResponseFactory.GetResponse(content: $"'{req.RequestUri.Host}'"); + }); + return messageHandler; + }; + + using (var kernel = + new TestingKernel( + k => + { + k.Rebind().To().InSingletonScope(); + k.Rebind>().ToMethod(c => messageHandlerFactory); + }, + dict)) + { + + var providerFactory = kernel.Get>(); + var serviceProxy = providerFactory("DemoService"); + serviceProxy.DefaultPort = port; + + //If we set Request Id we would like always to select same Host + TracingContext.SetRequestID("dumyId1"); + var request = new HttpServiceRequest("testMethod", null, new Dictionary()); + var hostOfFirstReq = (string)await serviceProxy.Invoke(request, typeof(string)); + + var host = (string)await serviceProxy.Invoke(request, typeof(string)); + + if (handleErrorAsCertificateError) + Assert.IsTrue(usedHttpsInSecondRequest); + else + Assert.IsFalse(usedHttpsInSecondRequest); + + + } + } + + } +} \ No newline at end of file diff --git a/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/HttpRequestsFactory.cs b/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/HttpRequestsFactory.cs index 9f108ad5..784c845a 100644 --- a/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/HttpRequestsFactory.cs +++ b/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/HttpRequestsFactory.cs @@ -1,14 +1,13 @@ -using System; -using System.Net; -using System.Net.Http; - -using Gigya.Microdot.Hosting.HttpService; +using Gigya.Microdot.Hosting.HttpService; using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.Exceptions; +using System; +using System.Net; +using System.Net.Http; namespace Gigya.Microdot.UnitTests.ServiceProxyTests { - public static class HttpResponseFactory + public static class HttpResponseFactory { public static HttpResponseMessage GetResponseWithException(JsonExceptionSerializer exceptionSerializer, Exception ex, HttpStatusCode? statusCode = null, bool withGigyaHostHeader = true) { diff --git a/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/JsonExceptionSerializerTests.cs b/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/JsonExceptionSerializerTests.cs index f60851ce..6b266253 100644 --- a/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/JsonExceptionSerializerTests.cs +++ b/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/JsonExceptionSerializerTests.cs @@ -1,55 +1,43 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Reflection; -using System.Runtime.Serialization; -using System.Threading; -using System.Threading.Tasks; -using Gigya.Common.Application.HttpService.Client; +using Gigya.Common.Application.HttpService.Client; using Gigya.Common.Contracts.Exceptions; -using Gigya.Microdot.Configuration; -using Gigya.Microdot.Fakes; -using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.SharedLogic.Configurations.Serialization; using Gigya.Microdot.SharedLogic.Exceptions; using Gigya.Microdot.SharedLogic.Utils; using Newtonsoft.Json; using Ninject; -using NSubstitute; using NUnit.Framework; - using Shouldly; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Reflection; +using System.Runtime.Serialization; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.ServiceProxyTests { public class JsonExceptionSerializerTests : UpdatableConfigTests { private JsonExceptionSerializer ExceptionSerializer { get; set; } - - public override void Setup() - { - - } - - public override void OneTimeSetUp() + + [OneTimeSetUp] + public async Task OneTimeSetupAsync() { base.OneTimeSetUp(); - + ExceptionSerializer = _unitTestingKernel.Get(); - Task t = ChangeConfig(new[] + await ChangeConfig(new[] { new KeyValuePair("StackTraceEnhancerSettings.RegexReplacements.TidyAsyncLocalFunctionNames.Pattern", @"\.<>c__DisplayClass(?:\d+)_(?:\d+)(?:`\d)?\.<<(\w+)>g__(\w+)\|?\d>d.MoveNext\(\)"), new KeyValuePair("StackTraceEnhancerSettings.RegexReplacements.TidyAsyncLocalFunctionNames.Replacement", @".$1.$2(async)") - }); - t.Wait(); - + }, TimeSpan.FromMinutes(1)); } - + protected override Action AdditionalBindings() { return null; @@ -170,6 +158,7 @@ public void InnerException_RoundTrip_AllStackTracesCleaned() actual.StackTrace.ShouldNotContain("at System.Runtime"); actual.StackTrace.ShouldNotContain("End of stack trace from previous location"); actual.StackTrace.ShouldNotContain("__"); + actual.InnerException.ShouldNotBeNull(); actual.InnerException.ShouldBeOfType(); actual.InnerException.Message.ShouldBe(webEx.Message); actual.InnerException.StackTrace.ShouldNotBeNullOrEmpty(); @@ -177,8 +166,8 @@ public void InnerException_RoundTrip_AllStackTracesCleaned() actual.InnerException.StackTrace.ShouldNotContain("End of stack trace"); actual.InnerException.StackTrace.ShouldNotContain("__"); } - - + +#if NETFRAMEWORK [Test] public async Task TryParseExceptionJsonFromNetCoreOriginWithConfigOn() { @@ -196,7 +185,7 @@ await ChangeConfig(new[] string netCoreExceptionJson = null; Assembly asm = Assembly.GetExecutingAssembly(); - using( Stream rsrcStream = asm.GetManifestResourceStream(strResourceName)) + using (Stream rsrcStream = asm.GetManifestResourceStream(strResourceName)) { using (StreamReader sRdr = new StreamReader(rsrcStream)) { @@ -224,7 +213,6 @@ await ChangeConfig(new[] Assert.NotNull(argumentOutOfRange.ActualValue); } - [Test] public async Task TryParseExceptionJsonFromNetCoreOriginWithConfigOff() @@ -250,8 +238,12 @@ await ChangeConfig(new[] Assert.Throws(() => ExceptionSerializer.Deserialize(netCoreExceptionJson)); } +#endif + + } + [Serializable] public class MyException : RequestException { diff --git a/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/MetricsTests.cs b/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/MetricsTests.cs index 86c1378e..f100bac8 100644 --- a/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/MetricsTests.cs +++ b/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/MetricsTests.cs @@ -1,18 +1,15 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; - -using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.ServiceProxy; using Gigya.Microdot.SharedLogic.HttpService; using Metrics; using Metrics.MetricData; - using NUnit.Framework; - using RichardSzalay.MockHttp; +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; // ReSharper disable UnusedVariable diff --git a/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/NinjectTest.cs b/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/NinjectTest.cs index fdb95905..8a70cefd 100644 --- a/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/NinjectTest.cs +++ b/tests/Gigya.Microdot.UnitTests/ServiceProxyTests/NinjectTest.cs @@ -1,12 +1,11 @@ -using System.Threading.Tasks; -using FluentAssertions; +using FluentAssertions; using Gigya.Microdot.Fakes; using Gigya.Microdot.ServiceProxy; using Gigya.Microdot.Testing.Shared; using Ninject; using NSubstitute; - using NUnit.Framework; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.ServiceProxyTests { diff --git a/tests/Gigya.Microdot.UnitTests/ServiceSchemaTests.cs b/tests/Gigya.Microdot.UnitTests/ServiceSchemaTests.cs index 480305e5..a49a1b91 100644 --- a/tests/Gigya.Microdot.UnitTests/ServiceSchemaTests.cs +++ b/tests/Gigya.Microdot.UnitTests/ServiceSchemaTests.cs @@ -1,11 +1,11 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Gigya.Common.Contracts.HttpService; +using Gigya.Common.Contracts.HttpService; using Gigya.ServiceContract.HttpService; using Newtonsoft.Json; using NUnit.Framework; using Shouldly; +using System; +using System.Linq; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests { diff --git a/tests/Gigya.Microdot.UnitTests/StringExtensionsTest.cs b/tests/Gigya.Microdot.UnitTests/StringExtensionsTest.cs index 0f38e16f..09593e09 100644 --- a/tests/Gigya.Microdot.UnitTests/StringExtensionsTest.cs +++ b/tests/Gigya.Microdot.UnitTests/StringExtensionsTest.cs @@ -1,9 +1,8 @@ -using Gigya.Microdot.SharedLogic.Utils; +using Gigya.Microdot.LanguageExtensions; using NUnit.Framework; - using Shouldly; -using Gigya.Microdot.LanguageExtensions; +using System; namespace Gigya.Microdot.UnitTests { @@ -32,5 +31,20 @@ public void IsSubPathOfTest(string path, string baseDirPath, bool isSubPath) { path.IsSubPathOf(baseDirPath).ShouldBe(isSubPath); } + + + [Test] + public void GetDeterministicHashCode_ThrowsForNullInput() + { + string str = null; + Should.Throw(() => str.GetDeterministicHashCode()); + } + + [TestCase("dlshjksdjkfhasdjk", 1472961354)] + [TestCase("", 23)] + public void GetDeterministicHashCode_ReturnsCorrectHashCode(string str, int expectedHashCode) + { + str.GetDeterministicHashCode().ShouldBe(expectedHashCode); + } } } \ No newline at end of file diff --git a/tests/Gigya.Microdot.UnitTests/SystemInitializer/ServiceHostFake.cs b/tests/Gigya.Microdot.UnitTests/SystemInitializer/ServiceHostFake.cs index 8128a870..7bdb0e4c 100644 --- a/tests/Gigya.Microdot.UnitTests/SystemInitializer/ServiceHostFake.cs +++ b/tests/Gigya.Microdot.UnitTests/SystemInitializer/ServiceHostFake.cs @@ -1,5 +1,4 @@ -using System.Threading.Tasks; -using Gigya.Common.Contracts.HttpService; +using Gigya.Common.Contracts.HttpService; using Gigya.Microdot.Common.Tests; using Gigya.Microdot.Hosting; using Gigya.Microdot.Hosting.Environment; @@ -13,6 +12,7 @@ using Gigya.Microdot.SharedLogic.HttpService; using Ninject; using NSubstitute; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.SystemInitializer { diff --git a/tests/Gigya.Microdot.UnitTests/SystemInitializer/SysInitCalledFromHostTest.cs b/tests/Gigya.Microdot.UnitTests/SystemInitializer/SysInitCalledFromHostTest.cs index 8a8b7266..09d7dc9d 100644 --- a/tests/Gigya.Microdot.UnitTests/SystemInitializer/SysInitCalledFromHostTest.cs +++ b/tests/Gigya.Microdot.UnitTests/SystemInitializer/SysInitCalledFromHostTest.cs @@ -1,13 +1,11 @@ -using System.Threading.Tasks; -using Gigya.Microdot.Common.Tests; -using Gigya.Microdot.Hosting.Environment; +using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Hosting.Validators; -using Gigya.Microdot.Ninject.Host; using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.Measurement.Workload; using Gigya.Microdot.Testing.Shared.Service; using NSubstitute; using NUnit.Framework; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests.SystemInitializer { diff --git a/tests/Gigya.Microdot.UnitTests/SystemInitializer/SystemInitializerTests.cs b/tests/Gigya.Microdot.UnitTests/SystemInitializer/SystemInitializerTests.cs index 054c3a21..cce804a6 100644 --- a/tests/Gigya.Microdot.UnitTests/SystemInitializer/SystemInitializerTests.cs +++ b/tests/Gigya.Microdot.UnitTests/SystemInitializer/SystemInitializerTests.cs @@ -1,8 +1,4 @@ -using System; -using System.Linq; -using System.Net; -using System.Threading.Tasks.Dataflow; -using Gigya.Microdot.Configuration; +using Gigya.Microdot.Configuration; using Gigya.Microdot.Configuration.Objects; using Gigya.Microdot.Fakes; using Gigya.Microdot.Hosting.Environment; @@ -11,6 +7,10 @@ using Ninject; using NSubstitute; using NUnit.Framework; +using System; +using System.Linq; +using System.Net; +using System.Threading.Tasks.Dataflow; namespace Gigya.Microdot.UnitTests.SystemInitializer { diff --git a/tests/Gigya.Microdot.UnitTests/TagsExtractorTests.cs b/tests/Gigya.Microdot.UnitTests/TagsExtractorTests.cs index 141675f6..4467d9ec 100644 --- a/tests/Gigya.Microdot.UnitTests/TagsExtractorTests.cs +++ b/tests/Gigya.Microdot.UnitTests/TagsExtractorTests.cs @@ -1,11 +1,11 @@ -using System.Linq; -using Gigya.Common.Contracts.Exceptions; +using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.SharedLogic.Logging; using NUnit.Framework; +using System.Linq; namespace Gigya.Microdot.UnitTests { - [TestFixture,Parallelizable(ParallelScope.Fixtures)] + [TestFixture,Parallelizable(ParallelScope.Fixtures)] public class TagsExtractorTests { [Test] diff --git a/tests/Gigya.Microdot.UnitTests/TestingHost.cs b/tests/Gigya.Microdot.UnitTests/TestingHost.cs index f359b80f..3cb00c7e 100644 --- a/tests/Gigya.Microdot.UnitTests/TestingHost.cs +++ b/tests/Gigya.Microdot.UnitTests/TestingHost.cs @@ -1,6 +1,3 @@ -using System; -using System.Collections.Concurrent; -using System.Threading.Tasks; using Gigya.Microdot.Common.Tests; using Gigya.Microdot.Configuration; using Gigya.Microdot.Fakes; @@ -17,6 +14,9 @@ using Ninject; using Ninject.Syntax; using NSubstitute; +using System; +using System.Collections.Concurrent; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests { diff --git a/tests/Gigya.Microdot.UnitTests/TestingKernel.cs b/tests/Gigya.Microdot.UnitTests/TestingKernel.cs index bb3f75cc..9e298623 100644 --- a/tests/Gigya.Microdot.UnitTests/TestingKernel.cs +++ b/tests/Gigya.Microdot.UnitTests/TestingKernel.cs @@ -20,16 +20,11 @@ // POSSIBILITY OF SUCH DAMAGE. #endregion -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; using Gigya.Microdot.Common.Tests; using Gigya.Microdot.Configuration; using Gigya.Microdot.Fakes; using Gigya.Microdot.Fakes.Discovery; using Gigya.Microdot.Fakes.KernelUtils; -using Gigya.Microdot.Hosting; using Gigya.Microdot.Hosting.Environment; using Gigya.Microdot.Interfaces; using Gigya.Microdot.Interfaces.Events; @@ -44,6 +39,10 @@ using Gigya.Microdot.SharedLogic.Monitor; using Ninject; using NSubstitute; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; namespace Gigya.Microdot.Testing.Shared { diff --git a/tests/Gigya.Microdot.UnitTests/UpdatableConfigTests.cs b/tests/Gigya.Microdot.UnitTests/UpdatableConfigTests.cs index 793a0cb0..a46d9c08 100644 --- a/tests/Gigya.Microdot.UnitTests/UpdatableConfigTests.cs +++ b/tests/Gigya.Microdot.UnitTests/UpdatableConfigTests.cs @@ -1,11 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Threading.Tasks; -using Gigya.Microdot.Fakes; +using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.Configuration; using Gigya.Microdot.Testing.Shared; using Ninject; using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; namespace Gigya.Microdot.UnitTests { @@ -87,14 +87,14 @@ protected async Task ChangeConfig(IEnumerable return await _unitTestingKernel.Get().ApplyChanges(); } - protected async Task ChangeConfig(IEnumerable> keyValue, TimeSpan timout) where T : IConfigObject + protected async Task ChangeConfig(IEnumerable> keyValue, TimeSpan timeout) where T : IConfigObject { foreach (KeyValuePair keyValuePair in keyValue) { _configDic[keyValuePair.Key] = keyValuePair.Value; } - return await _unitTestingKernel.Get().ApplyChanges(timout); + return await _unitTestingKernel.Get().ApplyChanges(timeout); } protected async Task ClearChanges() where T : IConfigObject diff --git a/tests/Gigya.Microdot.UnitTests/app.config b/tests/Gigya.Microdot.UnitTests/app.config deleted file mode 100644 index 5aed17a1..00000000 --- a/tests/Gigya.Microdot.UnitTests/app.config +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - True - - - - - - diff --git a/tests/Gigya.Microdot.UnitTests/paket.references b/tests/Gigya.Microdot.UnitTests/paket.references deleted file mode 100644 index fa961454..00000000 --- a/tests/Gigya.Microdot.UnitTests/paket.references +++ /dev/null @@ -1,19 +0,0 @@ -Gigya.ServiceContract -FluentAssertions -NSubstitute -NUnit -NUnit3TestAdapter -RichardSzalay.MockHttp -Shouldly -Ninject -System.Threading.Tasks.Dataflow -Castle.Core -Microsoft.Orleans.Core -System.ComponentModel.Annotations -System.Net.Http -System.Runtime.Caching -Microsoft.CSharp -Microsoft.NET.Test.Sdk - -# Remove after the transition to netcore completed -System.ServiceProcess.ServiceController