├── .editorconfig ├── .gitattributes ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── appveyor.yml └── src ├── Zyanea.Tests ├── Async │ ├── ISampleAsyncService.cs │ └── SampleAsyncService.cs ├── BasicTests.cs ├── Sync │ ├── ISampleSyncService.cs │ └── SampleSyncService.cs └── Zyanea.Tests.csproj ├── Zyanea.sln └── Zyanea ├── AsyncInterceptor.cs ├── ReplyMessage.cs ├── RequestMessage.cs ├── ZyanClient.cs ├── ZyanServer.cs ├── ZyanServerExtensions.cs └── Zyanea.csproj /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig: http://EditorConfig.org 2 | # VS extension: https://visualstudiogallery.msdn.microsoft.com/c8bccfe2-650c-4b42-bc5c-845e21f96328 3 | 4 | # tab indentation 5 | [*.cs] 6 | indent_style = tab 7 | indent_size = 4 8 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | *.VC.VC.opendb 85 | 86 | # Visual Studio profiler 87 | *.psess 88 | *.vsp 89 | *.vspx 90 | *.sap 91 | 92 | # TFS 2012 Local Workspace 93 | $tf/ 94 | 95 | # Guidance Automation Toolkit 96 | *.gpState 97 | 98 | # ReSharper is a .NET coding add-in 99 | _ReSharper*/ 100 | *.[Rr]e[Ss]harper 101 | *.DotSettings.user 102 | 103 | # JustCode is a .NET coding add-in 104 | .JustCode 105 | 106 | # TeamCity is a build add-in 107 | _TeamCity* 108 | 109 | # DotCover is a Code Coverage Tool 110 | *.dotCover 111 | 112 | # NCrunch 113 | _NCrunch_* 114 | .*crunch*.local.xml 115 | nCrunchTemp_* 116 | 117 | # MightyMoose 118 | *.mm.* 119 | AutoTest.Net/ 120 | 121 | # Web workbench (sass) 122 | .sass-cache/ 123 | 124 | # Installshield output folder 125 | [Ee]xpress/ 126 | 127 | # DocProject is a documentation generator add-in 128 | DocProject/buildhelp/ 129 | DocProject/Help/*.HxT 130 | DocProject/Help/*.HxC 131 | DocProject/Help/*.hhc 132 | DocProject/Help/*.hhk 133 | DocProject/Help/*.hhp 134 | DocProject/Help/Html2 135 | DocProject/Help/html 136 | 137 | # Click-Once directory 138 | publish/ 139 | 140 | # Publish Web Output 141 | *.[Pp]ublish.xml 142 | *.azurePubxml 143 | # TODO: Comment the next line if you want to checkin your web deploy settings 144 | # but database connection strings (with potential passwords) will be unencrypted 145 | *.pubxml 146 | *.publishproj 147 | 148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 149 | # checkin your Azure Web App publish settings, but sensitive information contained 150 | # in these scripts will be unencrypted 151 | PublishScripts/ 152 | 153 | # NuGet Packages 154 | *.nupkg 155 | # The packages folder can be ignored because of Package Restore 156 | **/packages/* 157 | # except build/, which is used as an MSBuild target. 158 | !**/packages/build/ 159 | # Uncomment if necessary however generally it will be regenerated when needed 160 | #!**/packages/repositories.config 161 | # NuGet v3's project.json files produces more ignoreable files 162 | *.nuget.props 163 | *.nuget.targets 164 | 165 | # Microsoft Azure Build Output 166 | csx/ 167 | *.build.csdef 168 | 169 | # Microsoft Azure Emulator 170 | ecf/ 171 | rcf/ 172 | 173 | # Windows Store app package directories and files 174 | AppPackages/ 175 | BundleArtifacts/ 176 | Package.StoreAssociation.xml 177 | _pkginfo.txt 178 | 179 | # Visual Studio cache files 180 | # files ending in .cache can be ignored 181 | *.[Cc]ache 182 | # but keep track of directories ending in .cache 183 | !*.[Cc]ache/ 184 | 185 | # Others 186 | ClientBin/ 187 | ~$* 188 | *~ 189 | *.dbmdl 190 | *.dbproj.schemaview 191 | *.pfx 192 | *.publishsettings 193 | node_modules/ 194 | orleans.codegen.cs 195 | 196 | # Since there are multiple workflows, uncomment next line to ignore bower_components 197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 198 | #bower_components/ 199 | 200 | # RIA/Silverlight projects 201 | Generated_Code/ 202 | 203 | # Backup & report files from converting an old project file 204 | # to a newer Visual Studio version. Backup files are not needed, 205 | # because we have git ;-) 206 | _UpgradeReport_Files/ 207 | Backup*/ 208 | UpgradeLog*.XML 209 | UpgradeLog*.htm 210 | 211 | # SQL Server files 212 | *.mdf 213 | *.ldf 214 | 215 | # Business Intelligence projects 216 | *.rdl.data 217 | *.bim.layout 218 | *.bim_*.settings 219 | 220 | # Microsoft Fakes 221 | FakesAssemblies/ 222 | 223 | # GhostDoc plugin setting file 224 | *.GhostDoc.xml 225 | 226 | # Node.js Tools for Visual Studio 227 | .ntvs_analysis.dat 228 | 229 | # Visual Studio 6 build log 230 | *.plg 231 | 232 | # Visual Studio 6 workspace options file 233 | *.opt 234 | 235 | # Visual Studio LightSwitch build output 236 | **/*.HTMLClient/GeneratedArtifacts 237 | **/*.DesktopClient/GeneratedArtifacts 238 | **/*.DesktopClient/ModelManifest.xml 239 | **/*.Server/GeneratedArtifacts 240 | **/*.Server/ModelManifest.xml 241 | _Pvt_Extensions 242 | 243 | # Paket dependency manager 244 | .paket/paket.exe 245 | paket-files/ 246 | 247 | # FAKE - F# Make 248 | .fake/ 249 | 250 | # JetBrains Rider 251 | .idea/ 252 | *.sln.iml 253 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: csharp 2 | mono: none 3 | dotnet: 2.0.0 4 | dist: trusty 5 | 6 | addons: 7 | apt: 8 | sources: 9 | - sourceline: 'deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-trusty-prod trusty main' 10 | key_url: 'https://packages.microsoft.com/keys/microsoft.asc' 11 | packages: 12 | - dotnet-hostfxr-1.0.1 13 | - dotnet-sharedframework-microsoft.netcore.app-1.0.5 14 | 15 | script: 16 | - dotnet restore src 17 | - dotnet build src 18 | - dotnet test src/Zyanea.Tests 19 | 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Alexey Yakovlev 4 | Copyright (c) 2017 Zyan Contributors 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy 7 | of this software and associated documentation files (the "Software"), to deal 8 | in the Software without restriction, including without limitation the rights 9 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the Software is 11 | furnished to do so, subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 19 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 22 | SOFTWARE. 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Zyanea 2 | 3 | [![Appveyor build status](https://ci.appveyor.com/api/projects/status/by3vda06qflkufao?svg=true)](https://ci.appveyor.com/project/yallie/zyanea) 4 | [![Travis-CI build status](https://travis-ci.org/yallie/Zyanea.svg?branch=master)](https://travis-ci.org/yallie/Zyanea) 5 | 6 | Zyanea is the codename for the next version of [Zyan Communication Framework](http://zyan.com.de). 7 | It's an easy to use secure distributed application framework for .NET Core. 8 | 9 | Goals: 10 | 11 | - Support .NET Core 12 | - Decouple from .NET Remoting technology 13 | - Use modern libraries for sockets, IoC, security, serialization, etc 14 | - Support asynchronous interfaces natively: return values of Task/ValueTask 15 | - Provide all Zyan services: events, remote LINQ, authentication, sessions, etc 16 | - Support serialization of POCOs, LINQ expressions, delegates, streams 17 | - More? 18 | 19 | Non-goals: 20 | 21 | - Heterogeneous environment (like connecting from .NET to Java) 22 | - Obsolete versions of .NET framework 23 | - Transport-level compatibility with Zyan 2.x 24 | 25 | ## Code sample 26 | 27 | ```c# 28 | // shared library 29 | public interface IHelloService 30 | { 31 | Task SayHello(string message); 32 | } 33 | 34 | // server 35 | using (var server = new ZyanServer("tcp://127.0.0.1:5800")) 36 | { 37 | server.Register(); 38 | Console.ReadLine(); 39 | } 40 | 41 | // client 42 | using (var client = new ZyanClient("tcp://127.0.0.1:5800")) 43 | { 44 | var proxy = client.CreateProxy(); 45 | await proxy.SayHello("World"); 46 | } 47 | ``` 48 | 49 | # Technology stack currently used: 50 | 51 | - NetMQ for transport layer (ZeroMQ protocol) 52 | - MessageWire for zero-knowledge-proof security (SRP v6 protocol) 53 | - Castle.DynamicProxy for the runtime-generated proxies 54 | - DryIoc container for IoC 55 | - Hyperion for polymorphic serialization 56 | 57 | ## NetMQ 58 | 59 | NetMQ is a 100% native C# port of the lightweight messaging library ZeroMQ. 60 | 61 | NetMQ extends the standard socket interfaces with features traditionally 62 | provided by specialised messaging middleware products. NetMQ sockets provide 63 | an abstraction of asynchronous message queues, multiple messaging patterns, 64 | message filtering (subscriptions), seamless access to multiple transport 65 | protocols, and more. 66 | 67 | ## MessageWire 68 | 69 | MessageWire is a Secure Remote Password Protocol v6 implementation, a kind of 70 | zero knowledge proof, that enables secure authentication and encryption without 71 | passing the actual identity key (password) or any other knowledge required 72 | to crack the encryption for messages exchanged between client (dealer socket) 73 | and server (router socket) using the NetMQ library, a .NET implementation of ZeroMQ. 74 | 75 | Get the [NuGet package](https://www.nuget.org/packages/MessageWire). 76 | 77 | Primary sources and references can be found here: 78 | 79 | - [Secure Remote Password Protocol](https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol) 80 | - [Zero Knowledge Proof](https://en.wikipedia.org/wiki/Zero-knowledge_proof) 81 | 82 | ## Castle.DynamicProxy 83 | 84 | Castle.DynamicProxy is a lightweight, lightning fast framework for generating 85 | proxies on the fly, used extensively by multiple projects within Castle (Windsor, 86 | MonoRail) and outside of it (NHibernate, Rhino Mocks, AutoMapper and many others). 87 | 88 | ## DryIoc 89 | 90 | DryIoc is fast, small, full-featured IoC Container for .NET 91 | designed for low-ceremony use, performance, and extensibility. 92 | 93 | ## Hyperion 94 | 95 | A high performance polymorphic serializer for the .NET framework, fork of the Wire serializer. 96 | 97 | Hyperion was designed to safely transfer messages in distributed systems, 98 | for example service bus or actor model based systems. In message based systems, 99 | it is common to receive different types of messages and apply pattern matching 100 | over those messages. If the messages does not carry over all the relevant type 101 | information to the receiveing side, the message might no longer match exactly 102 | what your system expect. 103 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | version: 1.0.{build} 2 | image: Visual Studio 2017 3 | install: 4 | - cmd: appveyor downloadfile https://dist.nuget.org/win-x86-commandline/v4.3.0/nuget.exe 5 | before_build: 6 | - cmd: nuget restore src 7 | build: 8 | verbosity: minimal 9 | test_script: 10 | - cmd: dotnet test src/Zyanea.Tests 11 | -------------------------------------------------------------------------------- /src/Zyanea.Tests/Async/ISampleAsyncService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using System.Threading.Tasks; 5 | 6 | namespace Zyanea.Tests.Async 7 | { 8 | public interface ISampleAsyncService 9 | { 10 | Task PerformShortOperation(); 11 | 12 | Task PerformLongOperation(); 13 | 14 | Task ThrowException(); 15 | 16 | Task Add(int a, int b); 17 | 18 | Task Concatenate(params string[] strings); 19 | 20 | Task Construct(int y, int m, int d); 21 | 22 | Task Now { get; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Zyanea.Tests/Async/SampleAsyncService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace Zyanea.Tests.Async 8 | { 9 | internal class SampleAsyncService : ISampleAsyncService 10 | { 11 | public bool ShortOperationPerformed { get; private set; } 12 | 13 | public Task PerformShortOperation() 14 | { 15 | ShortOperationPerformed = true; 16 | return Task.CompletedTask; 17 | } 18 | 19 | public bool LongOperationPerformed { get; private set; } 20 | 21 | public async Task PerformLongOperation() 22 | { 23 | await Task.Delay(300); 24 | LongOperationPerformed = true; 25 | } 26 | 27 | public async Task ThrowException() 28 | { 29 | await Task.Delay(1); 30 | throw new NotImplementedException(nameof(ISampleAsyncService)); 31 | } 32 | 33 | public async Task Add(int a, int b) 34 | { 35 | await Task.Delay(1); 36 | return a + b; 37 | } 38 | 39 | public async Task Concatenate(params string[] strings) 40 | { 41 | await Task.Delay(1); 42 | return string.Concat(strings); 43 | } 44 | 45 | public async Task Construct(int y, int m, int d) 46 | { 47 | await Task.Delay(1); 48 | return new DateTime(y, m, d); 49 | } 50 | 51 | public Task Now => GetNow(); 52 | 53 | private async Task GetNow() 54 | { 55 | await Task.Delay(1); 56 | return DateTimeOffset.Now; 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/Zyanea.Tests/BasicTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using DryIoc; 4 | using MessageWire; 5 | using Xunit; 6 | using Zyanea.Tests.Async; 7 | using Zyanea.Tests.Sync; 8 | 9 | namespace Zyanea.Tests 10 | { 11 | public class BasicTests : IDisposable 12 | { 13 | public BasicTests() 14 | { 15 | Wire.Linger = new TimeSpan(0, 0, 0, 1); 16 | } 17 | 18 | void IDisposable.Dispose() 19 | { 20 | Wire.Cleanup(); 21 | } 22 | 23 | const string ServerUrl = "tcp://127.0.0.1:5800"; 24 | 25 | [Fact] 26 | public void ZyanServerCanRegisterAndResolveComponents() 27 | { 28 | using (var server = new ZyanServer()) 29 | { 30 | server.Register(); 31 | var component = server.Resolve(); 32 | 33 | Assert.NotNull(component); 34 | Assert.IsType(component); 35 | } 36 | } 37 | 38 | [Fact] 39 | public void ZyanServerCanBeConnectedTo() 40 | { 41 | using (var server = new ZyanServer(ServerUrl)) 42 | using (var client = new ZyanClient(ServerUrl)) 43 | { 44 | Assert.True(client.IsConnected); 45 | } 46 | } 47 | 48 | [Fact] 49 | public void ZyanClientDoesntImmediatelyConnect() 50 | { 51 | // Assert.DoesNotThrow 52 | using (var client = new ZyanClient(ServerUrl)) 53 | { 54 | } 55 | } 56 | 57 | [Fact] 58 | public void ZyanClientCanCreateProxies() 59 | { 60 | // Assert.DoesNotThrow 61 | using (var client = new ZyanClient(ServerUrl)) 62 | { 63 | var proxy = client.CreateProxy(); 64 | Assert.NotNull(proxy); 65 | } 66 | } 67 | 68 | [Fact] 69 | public void ZyanClientCanCallVoidMethodSynchronously() 70 | { 71 | using (var server = new ZyanServer(ServerUrl)) 72 | { 73 | server.Register(); 74 | 75 | using (var client = new ZyanClient(ServerUrl)) 76 | { 77 | var proxy = client.CreateProxy(); 78 | 79 | // Assert.DoesNotThrow 80 | proxy.Void(); 81 | } 82 | } 83 | } 84 | 85 | [Fact] 86 | public void ZyanClientCanCallVoidMethodSynchronouslyAndItsActuallyExecutedOnServer() 87 | { 88 | using (var server = new ZyanServer(ServerUrl)) 89 | { 90 | server.Register(Reuse.Singleton); 91 | var sync = server.Resolve() as SampleSyncService; 92 | Assert.False(sync.VoidExecuted); 93 | 94 | using (var client = new ZyanClient(ServerUrl)) 95 | { 96 | var proxy = client.CreateProxy(); 97 | 98 | // Assert.DoesNotThrow 99 | proxy.Void(); 100 | Assert.True(sync.VoidExecuted); 101 | } 102 | } 103 | } 104 | 105 | [Fact] 106 | public void ZyanClientCanCallMethodSynchronouslyAndGetTheStringResult() 107 | { 108 | using (var server = new ZyanServer(ServerUrl)) 109 | { 110 | server.Register(); 111 | 112 | using (var client = new ZyanClient(ServerUrl)) 113 | { 114 | var proxy = client.CreateProxy(); 115 | 116 | // Assert.DoesNotThrow 117 | var result = proxy.GetVersion(); 118 | Assert.Equal(SampleSyncService.Version, result); 119 | } 120 | } 121 | } 122 | 123 | [Fact] 124 | public void ZyanClientCanCallMethodSynchronouslyAndGetTheDateResult() 125 | { 126 | using (var server = new ZyanServer(ServerUrl)) 127 | { 128 | server.Register(); 129 | 130 | using (var client = new ZyanClient(ServerUrl)) 131 | { 132 | var proxy = client.CreateProxy(); 133 | 134 | // Assert.DoesNotThrow 135 | var result = proxy.GetDate(2017, 09, 17); 136 | Assert.Equal(new DateTime(2017, 09, 17), result); 137 | } 138 | } 139 | } 140 | 141 | [Fact] 142 | public void ZyanClientCanCallMethodSynchronouslyAndCatchTheException() 143 | { 144 | using (var server = new ZyanServer(ServerUrl)) 145 | { 146 | server.Register(); 147 | 148 | using (var client = new ZyanClient(ServerUrl)) 149 | { 150 | var proxy = client.CreateProxy(); 151 | 152 | var ex = Assert.Throws(() => 153 | { 154 | proxy.ThrowException(); 155 | }); 156 | 157 | Assert.Equal(nameof(ISampleSyncService), ex.Message); 158 | } 159 | } 160 | } 161 | 162 | [Fact] 163 | public void ZyanClientCanAssignRemotePropertySynchronously() 164 | { 165 | using (var server = new ZyanServer(ServerUrl)) 166 | { 167 | // preserving property value between calls requires the Singleton reuse 168 | server.Register(Reuse.Singleton); 169 | 170 | using (var client = new ZyanClient(ServerUrl)) 171 | { 172 | var proxy = client.CreateProxy(); 173 | 174 | // Assert.DoesNotThrow 175 | proxy.Platform = nameof(ZyanClientCanAssignRemotePropertySynchronously); 176 | var result = proxy.Platform; 177 | 178 | Assert.Equal(nameof(ZyanClientCanAssignRemotePropertySynchronously), result); 179 | } 180 | } 181 | } 182 | 183 | [Fact] 184 | public async Task ZyanClientCanCallAsyncTaskMethod() 185 | { 186 | using (var server = new ZyanServer(ServerUrl)) 187 | { 188 | server.Register(); 189 | 190 | using (var client = new ZyanClient(ServerUrl)) 191 | { 192 | var proxy = client.CreateProxy(); 193 | 194 | // Assert.DoesNotThrow 195 | await proxy.PerformShortOperation(); 196 | } 197 | } 198 | } 199 | 200 | [Fact] 201 | public async Task ZyanClientCanCallShortAsyncTaskMethodAndItsActuallyExecuted() 202 | { 203 | using (var server = new ZyanServer(ServerUrl)) 204 | { 205 | server.Register(Reuse.Singleton); 206 | var async = server.Resolve() as SampleAsyncService; 207 | Assert.False(async.ShortOperationPerformed); 208 | 209 | using (var client = new ZyanClient(ServerUrl)) 210 | { 211 | var proxy = client.CreateProxy(); 212 | 213 | // Assert.DoesNotThrow 214 | await proxy.PerformShortOperation(); 215 | Assert.True(async.ShortOperationPerformed); 216 | } 217 | } 218 | } 219 | 220 | [Fact] 221 | public async Task ZyanClientCanCallLongAsyncTaskMethodAndItsActuallyExecuted() 222 | { 223 | using (var server = new ZyanServer(ServerUrl)) 224 | { 225 | server.Register(Reuse.Singleton); 226 | var async = server.Resolve() as SampleAsyncService; 227 | Assert.False(async.LongOperationPerformed); 228 | 229 | using (var client = new ZyanClient(ServerUrl)) 230 | { 231 | var proxy = client.CreateProxy(); 232 | 233 | // Assert.DoesNotThrow 234 | await proxy.PerformLongOperation(); 235 | Assert.True(async.LongOperationPerformed); 236 | } 237 | } 238 | } 239 | 240 | [Fact] 241 | public async Task ZyanClientCanCallAsyncTaskMethodAndCatchTheException() 242 | { 243 | using (var server = new ZyanServer(ServerUrl)) 244 | { 245 | server.Register(); 246 | 247 | using (var client = new ZyanClient(ServerUrl)) 248 | { 249 | var proxy = client.CreateProxy(); 250 | 251 | var ex = await Assert.ThrowsAsync(async () => 252 | { 253 | await proxy.ThrowException(); 254 | }); 255 | 256 | Assert.Equal(nameof(ISampleAsyncService), ex.Message); 257 | } 258 | } 259 | } 260 | 261 | [Fact] 262 | public async Task ZyanClientCanCallAsyncTaskIntMethodWithParameters() 263 | { 264 | using (var server = new ZyanServer(ServerUrl)) 265 | { 266 | server.Register(); 267 | 268 | using (var client = new ZyanClient(ServerUrl)) 269 | { 270 | var proxy = client.CreateProxy(); 271 | 272 | // Assert.DoesNotThrow 273 | var result = await proxy.Add(12300, 45); 274 | Assert.Equal(12345, result); 275 | } 276 | } 277 | } 278 | 279 | [Fact] 280 | public async Task ZyanClientCanCallAsyncTaskStringMethodWithParameters() 281 | { 282 | using (var server = new ZyanServer(ServerUrl)) 283 | { 284 | server.Register(); 285 | 286 | using (var client = new ZyanClient(ServerUrl)) 287 | { 288 | var proxy = client.CreateProxy(); 289 | 290 | // Assert.DoesNotThrow 291 | var result = await proxy.Concatenate("Get", "Uninitialized", "Object"); 292 | Assert.Equal("GetUninitializedObject", result); 293 | } 294 | } 295 | } 296 | 297 | [Fact] 298 | public async Task ZyanClientCanCallAsyncTaskDateTimeMethodWithParameters() 299 | { 300 | using (var server = new ZyanServer(ServerUrl)) 301 | { 302 | server.Register(); 303 | 304 | using (var client = new ZyanClient(ServerUrl)) 305 | { 306 | var proxy = client.CreateProxy(); 307 | 308 | // Assert.DoesNotThrow 309 | var result = await proxy.Construct(2017, 09, 19); 310 | Assert.Equal(new DateTime(2017, 09, 19), result); 311 | } 312 | } 313 | } 314 | 315 | [Fact] 316 | public async Task ZyanClientCanReadRemotePropertyAsynchronously() 317 | { 318 | using (var server = new ZyanServer(ServerUrl)) 319 | { 320 | server.Register(); 321 | 322 | using (var client = new ZyanClient(ServerUrl)) 323 | { 324 | var proxy = client.CreateProxy(); 325 | 326 | // Assert.DoesNotThrow 327 | var nowBefore = DateTimeOffset.Now; 328 | var nowRemote = await proxy.Now; 329 | var nowAfter = DateTimeOffset.Now; 330 | 331 | Assert.True(nowBefore <= nowRemote); 332 | Assert.True(nowRemote <= nowAfter); 333 | } 334 | } 335 | } 336 | } 337 | } 338 | -------------------------------------------------------------------------------- /src/Zyanea.Tests/Sync/ISampleSyncService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Zyanea.Tests.Sync 6 | { 7 | public interface ISampleSyncService 8 | { 9 | void Void(); 10 | 11 | string GetVersion(); 12 | 13 | DateTime GetDate(int year, int month, int day); 14 | 15 | void ThrowException(); 16 | 17 | string Platform { get; set; } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Zyanea.Tests/Sync/SampleSyncService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Zyanea.Tests.Sync 4 | { 5 | internal class SampleSyncService : ISampleSyncService 6 | { 7 | public const string Version = "0.0.1 alpha"; 8 | 9 | public DateTime GetDate(int year, int month, int day) 10 | { 11 | return new DateTime(year, month, day); 12 | } 13 | 14 | public string GetVersion() 15 | { 16 | return Version; 17 | } 18 | 19 | public void Void() 20 | { 21 | VoidExecuted = true; 22 | } 23 | 24 | public bool VoidExecuted { get; private set; } 25 | 26 | public void ThrowException() 27 | { 28 | throw new NotImplementedException(nameof(ISampleSyncService)); 29 | } 30 | 31 | public string Platform { get; set; } 32 | } 33 | } -------------------------------------------------------------------------------- /src/Zyanea.Tests/Zyanea.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp2.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/Zyanea.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26730.15 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{B2B7F7CF-457D-4EBE-B34C-7AF0B49C0B54}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{4A54949E-A48E-44EF-8BB8-6BECCA868E2E}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".docs", ".docs", "{2A8A94FC-650A-41AE-9012-CC80CBDB70B8}" 11 | ProjectSection(SolutionItems) = preProject 12 | ..\README.md = ..\README.md 13 | EndProjectSection 14 | EndProject 15 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Zyanea", "Zyanea\Zyanea.csproj", "{9B00B692-ADD7-461D-9967-012716B1D350}" 16 | EndProject 17 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Zyanea.Tests", "Zyanea.Tests\Zyanea.Tests.csproj", "{D9FEBEAF-6829-4646-AF59-34EF01E1A09B}" 18 | EndProject 19 | Global 20 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 21 | Debug|Any CPU = Debug|Any CPU 22 | Release|Any CPU = Release|Any CPU 23 | EndGlobalSection 24 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 25 | {9B00B692-ADD7-461D-9967-012716B1D350}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {9B00B692-ADD7-461D-9967-012716B1D350}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {9B00B692-ADD7-461D-9967-012716B1D350}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {9B00B692-ADD7-461D-9967-012716B1D350}.Release|Any CPU.Build.0 = Release|Any CPU 29 | {D9FEBEAF-6829-4646-AF59-34EF01E1A09B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {D9FEBEAF-6829-4646-AF59-34EF01E1A09B}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {D9FEBEAF-6829-4646-AF59-34EF01E1A09B}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {D9FEBEAF-6829-4646-AF59-34EF01E1A09B}.Release|Any CPU.Build.0 = Release|Any CPU 33 | EndGlobalSection 34 | GlobalSection(SolutionProperties) = preSolution 35 | HideSolutionNode = FALSE 36 | EndGlobalSection 37 | GlobalSection(NestedProjects) = preSolution 38 | {9B00B692-ADD7-461D-9967-012716B1D350} = {B2B7F7CF-457D-4EBE-B34C-7AF0B49C0B54} 39 | {D9FEBEAF-6829-4646-AF59-34EF01E1A09B} = {B2B7F7CF-457D-4EBE-B34C-7AF0B49C0B54} 40 | EndGlobalSection 41 | GlobalSection(ExtensibilityGlobals) = postSolution 42 | SolutionGuid = {4D78F946-1236-4D86-9C64-1353CC6D049E} 43 | EndGlobalSection 44 | EndGlobal 45 | -------------------------------------------------------------------------------- /src/Zyanea/AsyncInterceptor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using Castle.DynamicProxy; 4 | 5 | namespace Zyanea 6 | { 7 | internal class AsyncInterceptor : IAsyncInterceptor 8 | { 9 | public AsyncInterceptor(ZyanClient client, Type componentType) 10 | { 11 | Client = client; 12 | ComponentType = componentType; 13 | } 14 | 15 | public ZyanClient Client { get; } 16 | 17 | public Type ComponentType { get; } 18 | 19 | public void InterceptSynchronous(IInvocation invocation) 20 | { 21 | // send the method invocation message 22 | var msg = new RequestMessage(invocation, ComponentType); 23 | Client.SendMessage(msg); 24 | 25 | // wait for the reply message synchronously 26 | invocation.ReturnValue = Client.GetSyncResult(msg.MessageId); 27 | } 28 | 29 | public void InterceptAsynchronous(IInvocation invocation) 30 | { 31 | invocation.ReturnValue = InternalInterceptAsynchronous(invocation); 32 | } 33 | 34 | private async Task InternalInterceptAsynchronous(IInvocation invocation) 35 | { 36 | // send the method invocation message 37 | var msg = new RequestMessage(invocation, ComponentType); 38 | Client.SendMessage(msg); 39 | 40 | // wait for the reply message asynchronously 41 | await Client.GetAsyncResult(msg.MessageId); 42 | } 43 | 44 | public void InterceptAsynchronous(IInvocation invocation) 45 | { 46 | invocation.ReturnValue = InternalInterceptAsynchronous(invocation); 47 | } 48 | 49 | private async Task InternalInterceptAsynchronous(IInvocation invocation) 50 | { 51 | // send the method invocation message 52 | var msg = new RequestMessage(invocation, ComponentType); 53 | Client.SendMessage(msg); 54 | 55 | // wait for the reply message asynchronously 56 | return await Client.GetAsyncResult(msg.MessageId); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/Zyanea/ReplyMessage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Zyanea 6 | { 7 | public class ReplyMessage 8 | { 9 | public ReplyMessage(RequestMessage msg) 10 | { 11 | RequestMessageId = msg.MessageId; 12 | } 13 | 14 | public Guid RequestMessageId { get; } 15 | 16 | public object Result { get; set; } 17 | 18 | public Exception Exception { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Zyanea/RequestMessage.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Reflection; 4 | using System.Text; 5 | using Castle.DynamicProxy; 6 | 7 | namespace Zyanea 8 | { 9 | public class RequestMessage 10 | { 11 | public RequestMessage(IInvocation invocation, Type componentType) 12 | { 13 | MessageId = Guid.NewGuid(); 14 | ComponentType = componentType; 15 | Method = invocation.Method; 16 | GenericArguments = invocation.GenericArguments; 17 | Arguments = invocation.Arguments; 18 | } 19 | 20 | public Guid MessageId { get; } 21 | 22 | public Type ComponentType { get; } 23 | 24 | public MethodInfo Method { get; } 25 | 26 | public Type[] GenericArguments { get; } 27 | 28 | public object[] Arguments { get; } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Zyanea/ZyanClient.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Concurrent; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Runtime.ExceptionServices; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Castle.DynamicProxy; 9 | using Hyperion; 10 | using MessageWire; 11 | 12 | namespace Zyanea 13 | { 14 | public class ZyanClient : IDisposable 15 | { 16 | public ZyanClient(string serverUrl) 17 | { 18 | ServerUrl = serverUrl; 19 | Client = new Client(serverUrl); 20 | Client.MessageReceived += HandleReceivedMessage; 21 | } 22 | 23 | public void Dispose() 24 | { 25 | if (IsDisposed) 26 | { 27 | return; 28 | } 29 | 30 | IsDisposed = true; 31 | Client?.Dispose(); 32 | } 33 | 34 | public bool IsDisposed { get; private set; } 35 | 36 | public string ServerUrl { get; } 37 | 38 | public IClient Client { get; } 39 | 40 | public bool IsConnected => Client.IsHostAlive; 41 | 42 | private ProxyGenerator ProxyGenerator { get; } = 43 | new ProxyGenerator(disableSignedModule: true); 44 | 45 | private Serializer Serializer { get; } = 46 | new Serializer(new SerializerOptions(preserveObjectReferences: true)); 47 | 48 | public IService CreateProxy() 49 | where IService: class 50 | { 51 | var interceptor = new AsyncInterceptor(this, typeof(IService)); 52 | return ProxyGenerator.CreateInterfaceProxyWithTargetInterface(null, interceptor); 53 | } 54 | 55 | private ConcurrentDictionary> PendingMessages { get; } = 56 | new ConcurrentDictionary>(); 57 | 58 | internal void SendMessage(RequestMessage zyanMessage) 59 | { 60 | // serialize and send the message to the remote host 61 | using (var ms = new MemoryStream()) 62 | { 63 | PendingMessages[zyanMessage.MessageId] = new TaskCompletionSource(); 64 | Serializer.Serialize(zyanMessage, ms); 65 | var serialized = ms.ToArray(); 66 | Client.Send(serialized); 67 | } 68 | } 69 | 70 | private void HandleReceivedMessage(object sender, MessageEventArgs e) 71 | { 72 | // deserialize the reply message 73 | using (var ms = new MemoryStream(e.Message.Frames[0])) 74 | { 75 | var replyMessage = Serializer.Deserialize(ms); 76 | var tcs = PendingMessages[replyMessage.RequestMessageId]; 77 | 78 | // signal the remote exception 79 | if (replyMessage.Exception != null) 80 | { 81 | tcs.SetException(replyMessage.Exception); 82 | return; 83 | } 84 | 85 | // signal the result 86 | tcs.SetResult(replyMessage.Result); 87 | } 88 | } 89 | 90 | private Task GetResultTask(Guid messageId) 91 | { 92 | if (PendingMessages.TryGetValue(messageId, out var tcs)) 93 | { 94 | return tcs.Task; 95 | } 96 | 97 | throw new InvalidOperationException($"Message {messageId} already handled"); 98 | } 99 | 100 | internal object GetSyncResult(Guid messageId) 101 | { 102 | // task.Result wraps the exception in AggregateException 103 | // task.GetAwaiter().GetResult() does not 104 | return GetResultTask(messageId).GetAwaiter().GetResult(); 105 | } 106 | 107 | internal Task GetAsyncResult(Guid messageId) 108 | { 109 | return GetResultTask(messageId); 110 | } 111 | 112 | internal async Task GetAsyncResult(Guid messageId) 113 | { 114 | var result = await GetResultTask(messageId); 115 | return (TResult)result; 116 | } 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/Zyanea/ZyanServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Reflection; 4 | using System.Threading.Tasks; 5 | using DryIoc; 6 | using DryIoc.MefAttributedModel; 7 | using Hyperion; 8 | using MessageWire; 9 | 10 | namespace Zyanea 11 | { 12 | public class ZyanServer : IDisposable 13 | { 14 | public ZyanServer(string serverUrl = null) 15 | { 16 | if (!string.IsNullOrWhiteSpace(serverUrl)) 17 | { 18 | Start(serverUrl); 19 | } 20 | } 21 | 22 | public void Start(string serverUrl) 23 | { 24 | ServerUrl = serverUrl; 25 | Host = new Host(ServerUrl); 26 | Host.MessageReceived += HandleReceivedMessage; 27 | } 28 | 29 | public void Dispose() 30 | { 31 | if (IsDisposed) 32 | { 33 | return; 34 | } 35 | 36 | IsDisposed = true; 37 | Host?.Dispose(); 38 | Container?.Dispose(); 39 | } 40 | 41 | public bool IsDisposed { get; private set; } 42 | 43 | public string ServerUrl { get; private set; } 44 | 45 | public IHost Host { get; private set; } 46 | 47 | public IContainer Container { get; } = 48 | new Container().WithMef().With(r => r.WithDefaultReuse(Reuse.Transient)); 49 | 50 | private Serializer Serializer { get; } = 51 | new Serializer(new SerializerOptions(preserveObjectReferences: true)); 52 | 53 | private async void HandleReceivedMessage(object sender, MessageEventArgs e) 54 | { 55 | using (var ms = new MemoryStream(e.Message.Frames[0])) 56 | { 57 | // deserialize the request message and prepare the reply 58 | var requestMessage = Serializer.Deserialize(ms); 59 | var replyMessage = new ReplyMessage(requestMessage); 60 | 61 | try 62 | { 63 | // invoke the request message and get the result 64 | var component = Container.Resolve(requestMessage.ComponentType); 65 | var result = requestMessage.Method.Invoke(component, requestMessage.Arguments); 66 | 67 | // handle task results 68 | var task = result as Task; 69 | if (task != null) 70 | { 71 | await task; 72 | 73 | // handle Task 74 | var taskType = task.GetType().GetTypeInfo(); 75 | if (taskType.IsGenericType) 76 | { 77 | // TODO: cache resultProperty and convert it to a delegate 78 | var resultProperty = taskType.GetProperty(nameof(Task.Result)); 79 | replyMessage.Result = resultProperty.GetValue(task); 80 | } 81 | else 82 | { 83 | replyMessage.Result = null; 84 | } 85 | } 86 | else 87 | { 88 | replyMessage.Result = result; 89 | } 90 | } 91 | catch (Exception ex) 92 | { 93 | // skip the useless TargetInvocationException 94 | // also, it's not supported by the serializer 95 | if (ex is TargetInvocationException) 96 | { 97 | ex = ex.InnerException; 98 | } 99 | 100 | // wrap the exception to send back to the client 101 | replyMessage.Exception = ex; 102 | } 103 | finally 104 | { 105 | // serialize the reply message 106 | ms.SetLength(0); 107 | Serializer.Serialize(replyMessage, ms); 108 | var serialized = ms.ToArray(); 109 | 110 | // send the reply 111 | Host.Send(e.Message.ClientId, serialized); 112 | } 113 | } 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/Zyanea/ZyanServerExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using DryIoc; 5 | 6 | namespace Zyanea 7 | { 8 | public static class ZyanServerExtensions 9 | { 10 | public static void Register(this ZyanServer self) 11 | where Service : IService 12 | { 13 | self.Container.Register(); 14 | } 15 | 16 | public static void Register(this ZyanServer self, IReuse reuse) 17 | where Service : IService 18 | { 19 | self.Container.Register(reuse); 20 | } 21 | 22 | public static IService Resolve(this ZyanServer self) 23 | { 24 | return self.Container.Resolve(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Zyanea/Zyanea.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Zyanea is a proof-of-concept version of Zyan over NetMQ using MessageWire Zero-Knowledge Proof layer. 5 | netstandard2.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | --------------------------------------------------------------------------------