From e22e0d952dcbb571d07d480f1ad5bf6734ba89d9 Mon Sep 17 00:00:00 2001 From: Ahmed Zamil Date: Tue, 17 Mar 2026 22:15:43 +0300 Subject: [PATCH] renaming 2 --- Esiur.ASPNet/Program.cs | 2 +- Esiur.AspNetCore/EsiurMiddleware.cs | 14 +- Esiur.AspNetCore/EsiurOptions.cs | 5 +- Esiur.AspNetCore/README.md | 2 +- Esiur.CLI/Program.cs | 4 +- Esiur.CLI/Properties/launchSettings.json | 2 +- Esiur.CLI/README.md | 4 +- .../Program.cs | 4 +- .../Web/js/app.js | 2 +- Esiur.Stores.EntityCore/EntityStore.cs | 6 +- Esiur.Stores.MongoDB/MongoDBStore.cs | 30 +- Esiur/Core/InvocationContext.cs | 6 +- Esiur/Data/Codec.cs | 32 +- Esiur/Data/DataConverter.cs | 2 - Esiur/Data/DataDeserializer - Copy.cs | 74 +- Esiur/Data/DataDeserializer.cs | 255 ++-- Esiur/Data/DataSerializer.cs | 103 +- Esiur/Data/Map.cs | 1 - Esiur/Data/ResourceJsonConverter.cs | 3 +- Esiur/Data/RuntimeCaster.cs | 2 +- Esiur/Data/TDU.cs | 3 +- Esiur/Data/TRU.cs | 1 - Esiur/Data/Types/ConstantDef.cs | 2 +- Esiur/Data/Types/FunctionDef.cs | 8 +- Esiur/Data/Types/MemberDef.cs | 2 +- Esiur/Data/Types/PropertyDef.cs | 40 +- Esiur/Data/Types/TypeDef.cs | 27 +- .../Net/{HTTP/IIPoHTTP.cs => Http/EPoHTTP.cs} | 10 +- Esiur/Net/{HTTP/IIPoWS.cs => Http/EPoWS.cs} | 12 +- Esiur/Net/IIP/DistributedConnectionConfig.cs | 36 - .../DistributedResourceAttachRequestInfo.cs | 20 - Esiur/Net/IIP/PropertyContext.cs | 36 - ...PAuthExtensions.cs => EpAuthExtensions.cs} | 10 +- .../{IIPAuthPacket.cs => EpAuthPacket.cs} | 86 +- ...nowledge.cs => EpAuthPacketAcknowledge.cs} | 2 +- ...hPacketAction.cs => EpAuthPacketAction.cs} | 2 +- ...acketCommand.cs => EpAuthPacketCommand.cs} | 2 +- ...uthPacketEvent.cs => EpAuthPacketEvent.cs} | 2 +- ...orithm.cs => EpAuthPacketHashAlgorithm.cs} | 2 +- ...hPacketHeader.cs => EpAuthPacketHeader.cs} | 2 +- ...ion.cs => EpAuthPacketIAuthDestination.cs} | 2 +- ...thFormat.cs => EpAuthPacketIAuthFormat.cs} | 2 +- ...thHeader.cs => EpAuthPacketIAuthHeader.cs} | 2 +- ...nitialize.cs => EpAuthPacketInitialize.cs} | 2 +- ...m.cs => EpAuthPacketPublicKeyAlgorithm.cs} | 2 +- .../Net/Packets/{IIPPacket.cs => EpPacket.cs} | 34 +- ...ketAttachInfo.cs => EpPacketAttachInfo.cs} | 4 +- ...IIPPacketCommand.cs => EpPacketCommand.cs} | 2 +- ...otification.cs => EpPacketNotification.cs} | 2 +- .../{IIPPacketReply.cs => EpPacketReply.cs} | 2 +- .../{IIPPacketReport.cs => EpPacketReport.cs} | 2 +- ...IIPPacketRequest.cs => EpPacketRequest.cs} | 10 +- Esiur/Net/UDP/UDPServer.cs | 2 +- Esiur/{Net/IIP => Protocol}/EntryPoint.cs | 11 +- .../EpConnection.cs} | 464 +++--- Esiur/Protocol/EpConnectionConfig.cs | 35 + .../EpConnectionProtocol.cs} | 328 ++--- .../EpConnectionStatus.cs} | 4 +- .../EpResource.cs} | 26 +- Esiur/Protocol/EpResourceAttachRequestInfo.cs | 19 + .../EpResourceEvent.cs} | 4 +- .../EpResourceQueueItem.cs} | 10 +- .../EpServer.cs} | 22 +- .../EpSession.cs} | 5 +- Esiur/Protocol/PropertyContext.cs | 36 + .../ResourcePropertyChangedEventArgs.cs | 2 +- Esiur/Proxy/ResourceGenerator.cs | 16 +- ...mplateGenerator.cs => TypeDefGenerator.cs} | 20 +- Esiur/README.md | 10 +- Esiur/Resource/IStore.cs | 8 +- Esiur/Resource/Instance.cs | 1297 ++++++++--------- Esiur/Resource/ResourceEventHandler.cs | 5 +- Esiur/Resource/StorageMode.cs | 2 +- Esiur/Resource/StoreGeneric.cs | 6 +- Esiur/Resource/Warehouse.cs | 173 +-- Esiur/Security/Authority/Authentication.cs | 1 - Esiur/Security/Authority/Session.cs | 4 +- .../Membership/AuthorizationRequest.cs | 38 +- .../Membership/AuthorizationResults.cs | 6 +- Esiur/Security/Membership/IMembership.cs | 5 +- Esiur/Security/Membership/SimpleMembership.cs | 12 +- .../Permissions/StorePermissionsManager.cs | 4 +- .../Permissions/UserPermissionsManager.cs | 4 +- Esiur/Stores/MemoryStore.cs | 8 +- Esiur/Stores/TemporaryStore.cs | 6 +- Test/MyResource.cs | 2 +- Test/MyService.cs | 6 +- Test/Program.cs | 26 +- 88 files changed, 1685 insertions(+), 1866 deletions(-) rename Esiur/Net/{HTTP/IIPoHTTP.cs => Http/EPoHTTP.cs} (73%) rename Esiur/Net/{HTTP/IIPoWS.cs => Http/EPoWS.cs} (89%) delete mode 100644 Esiur/Net/IIP/DistributedConnectionConfig.cs delete mode 100644 Esiur/Net/IIP/DistributedResourceAttachRequestInfo.cs delete mode 100644 Esiur/Net/IIP/PropertyContext.cs rename Esiur/Net/Packets/{IIPAuthExtensions.cs => EpAuthExtensions.cs} (62%) rename Esiur/Net/Packets/{IIPAuthPacket.cs => EpAuthPacket.cs} (77%) rename Esiur/Net/Packets/{IIPAuthPacketAcknowledge.cs => EpAuthPacketAcknowledge.cs} (94%) rename Esiur/Net/Packets/{IIPAuthPacketAction.cs => EpAuthPacketAction.cs} (93%) rename Esiur/Net/Packets/{IIPAuthPacketCommand.cs => EpAuthPacketCommand.cs} (82%) rename Esiur/Net/Packets/{IIPAuthPacketEvent.cs => EpAuthPacketEvent.cs} (88%) rename Esiur/Net/Packets/{IIPAuthPacketHashAlgorithm.cs => EpAuthPacketHashAlgorithm.cs} (77%) rename Esiur/Net/Packets/{IIPAuthPacketHeader.cs => EpAuthPacketHeader.cs} (94%) rename Esiur/Net/Packets/{IIPAuthPacketIAuthDestination.cs => EpAuthPacketIAuthDestination.cs} (86%) rename Esiur/Net/Packets/{IIPAuthPacketIAuthFormat.cs => EpAuthPacketIAuthFormat.cs} (87%) rename Esiur/Net/Packets/{IIPAuthPacketIAuthHeader.cs => EpAuthPacketIAuthHeader.cs} (86%) rename Esiur/Net/Packets/{IIPAuthPacketInitialize.cs => EpAuthPacketInitialize.cs} (95%) rename Esiur/Net/Packets/{IIPAuthPacketPublicKeyAlgorithm.cs => EpAuthPacketPublicKeyAlgorithm.cs} (75%) rename Esiur/Net/Packets/{IIPPacket.cs => EpPacket.cs} (76%) rename Esiur/Net/Packets/{IIPPacketAttachInfo.cs => EpPacketAttachInfo.cs} (74%) rename Esiur/Net/Packets/{IIPPacketCommand.cs => EpPacketCommand.cs} (83%) rename Esiur/Net/Packets/{IIPPacketNotification.cs => EpPacketNotification.cs} (88%) rename Esiur/Net/Packets/{IIPPacketReply.cs => EpPacketReply.cs} (90%) rename Esiur/Net/Packets/{IIPPacketReport.cs => EpPacketReport.cs} (85%) rename Esiur/Net/Packets/{IIPPacketRequest.cs => EpPacketRequest.cs} (82%) rename Esiur/{Net/IIP => Protocol}/EntryPoint.cs (86%) rename Esiur/{Net/IIP/DistributedConnection.cs => Protocol/EpConnection.cs} (74%) create mode 100644 Esiur/Protocol/EpConnectionConfig.cs rename Esiur/{Net/IIP/DistributedConnectionProtocol.cs => Protocol/EpConnectionProtocol.cs} (83%) rename Esiur/{Net/IIP/ConnectionStatus.cs => Protocol/EpConnectionStatus.cs} (70%) rename Esiur/{Net/IIP/DistributedResource.cs => Protocol/EpResource.cs} (94%) create mode 100644 Esiur/Protocol/EpResourceAttachRequestInfo.cs rename Esiur/{Net/IIP/DistributedResourceEvent.cs => Protocol/EpResourceEvent.cs} (91%) rename Esiur/{Net/IIP/DistributedResourceQueueItem.cs => Protocol/EpResourceQueueItem.cs} (86%) rename Esiur/{Net/IIP/DistributedServer.cs => Protocol/EpServer.cs} (87%) rename Esiur/{Net/IIP/DistributedSession.cs => Protocol/EpSession.cs} (93%) create mode 100644 Esiur/Protocol/PropertyContext.cs rename Esiur/{Net/IIP => Protocol}/ResourcePropertyChangedEventArgs.cs (95%) rename Esiur/Proxy/{TemplateGenerator.cs => TypeDefGenerator.cs} (95%) diff --git a/Esiur.ASPNet/Program.cs b/Esiur.ASPNet/Program.cs index 4d90cf6..c4f65f9 100644 --- a/Esiur.ASPNet/Program.cs +++ b/Esiur.ASPNet/Program.cs @@ -27,7 +27,7 @@ SOFTWARE. using Esiur.AspNetCore; using Esiur.AspNetCore.Example; using Esiur.Core; -using Esiur.Net.IIP; +using Esiur.Net.EP; using Esiur.Net.Sockets; using Esiur.Resource; using Esiur.Stores; diff --git a/Esiur.AspNetCore/EsiurMiddleware.cs b/Esiur.AspNetCore/EsiurMiddleware.cs index 010b733..0b97e7c 100644 --- a/Esiur.AspNetCore/EsiurMiddleware.cs +++ b/Esiur.AspNetCore/EsiurMiddleware.cs @@ -24,8 +24,8 @@ SOFTWARE. */ -using Esiur.Net.IIP; using Esiur.Net.Sockets; +using Esiur.Protocol; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -35,7 +35,7 @@ namespace Esiur.AspNetCore { public class EsiurMiddleware { - readonly DistributedServer server; + readonly EpServer server; readonly RequestDelegate next; readonly ILoggerFactory loggerFactory; @@ -44,13 +44,13 @@ namespace Esiur.AspNetCore var buffer = new ArraySegment(new byte[10240]); if (context.WebSockets.IsWebSocketRequest - && context.WebSockets.WebSocketRequestedProtocols.Contains("iip")) + && context.WebSockets.WebSocketRequestedProtocols.Contains("EP")) { - var webSocket = await context.WebSockets.AcceptWebSocketAsync("iip"); + var webSocket = await context.WebSockets.AcceptWebSocketAsync("EP"); var socket = new FrameworkWebSocket(webSocket); - var iipConnection = new DistributedConnection(); - server.Add(iipConnection); - iipConnection.Assign(socket); + var EPConnection = new EpConnection(); + server.Add(EPConnection); + EPConnection.Assign(socket); socket.Begin(); // @TODO: Change this diff --git a/Esiur.AspNetCore/EsiurOptions.cs b/Esiur.AspNetCore/EsiurOptions.cs index 279375b..3be78be 100644 --- a/Esiur.AspNetCore/EsiurOptions.cs +++ b/Esiur.AspNetCore/EsiurOptions.cs @@ -24,12 +24,13 @@ SOFTWARE. */ -using Esiur.Net.IIP; + +using Esiur.Protocol; namespace Esiur.AspNetCore { public class EsiurOptions { - public required DistributedServer Server { get; set; } + public required EpServer Server { get; set; } } } diff --git a/Esiur.AspNetCore/README.md b/Esiur.AspNetCore/README.md index e7b1915..f888149 100644 --- a/Esiur.AspNetCore/README.md +++ b/Esiur.AspNetCore/README.md @@ -46,6 +46,6 @@ To access the shell Now you can simply test the running service typing ```javascript -let x = await wh.get("iip://localhost:8080/sys/service", {secure: false}); +let x = await wh.get("EP://localhost:8080/sys/service", {secure: false}); await x.Hello(); ``` diff --git a/Esiur.CLI/Program.cs b/Esiur.CLI/Program.cs index 99d597e..6863153 100644 --- a/Esiur.CLI/Program.cs +++ b/Esiur.CLI/Program.cs @@ -47,7 +47,7 @@ if (args.Length > 0) { try { - var path = Esiur.Proxy.TemplateGenerator.GetTemplate(url, o.Dir, false, o.Username, o.Password, o.AsyncSetters); + var path = Esiur.Proxy.TypeDefGenerator.GetTemplate(url, o.Dir, false, o.Username, o.Password, o.AsyncSetters); Console.WriteLine($"Generated successfully: {path}"); } catch (Exception ex) @@ -83,7 +83,7 @@ static void PrintHelp() Console.WriteLine("Usage: [arguments]"); Console.WriteLine(""); Console.WriteLine("Available commands:"); - Console.WriteLine("\tget-template\tGet a template from an IIP link."); + Console.WriteLine("\tget-template\tGet a template from an EP link."); Console.WriteLine("\tversion\t\tPrint Esiur version."); Console.WriteLine(""); Console.WriteLine("Global options:"); diff --git a/Esiur.CLI/Properties/launchSettings.json b/Esiur.CLI/Properties/launchSettings.json index 3de5e59..a101bf0 100644 --- a/Esiur.CLI/Properties/launchSettings.json +++ b/Esiur.CLI/Properties/launchSettings.json @@ -2,7 +2,7 @@ "profiles": { "Esiur.CLI": { "commandName": "Project", - "commandLineArgs": "get-template iip://phase.delta.iq/sys/phase --dir c:\\temp\\an" + "commandLineArgs": "get-template EP://phase.delta.iq/sys/phase --dir c:\\temp\\an" } } } \ No newline at end of file diff --git a/Esiur.CLI/README.md b/Esiur.CLI/README.md index d8123db..db6dae3 100644 --- a/Esiur.CLI/README.md +++ b/Esiur.CLI/README.md @@ -9,7 +9,7 @@ A command-line utility to generate # Usage ``` Available commands: - get-template Get a template from an IIP link. + get-template Get a template from an EP link. version Print Esiur version. Global options: @@ -23,7 +23,7 @@ Global options: ## Example ``` - dotnet run esiur get-template iip://localhost/sys/service + dotnet run esiur get-template EP://localhost/sys/service ``` diff --git a/Esiur.Examples.StandaloneWebServerDemo/Program.cs b/Esiur.Examples.StandaloneWebServerDemo/Program.cs index 8c0cfbb..3a86c72 100644 --- a/Esiur.Examples.StandaloneWebServerDemo/Program.cs +++ b/Esiur.Examples.StandaloneWebServerDemo/Program.cs @@ -1,7 +1,7 @@  using Esiur.Examples.StandaloneWebServerDemo; using Esiur.Net.HTTP; -using Esiur.Net.IIP; +using Esiur.Protocol; using Esiur.Resource; using Esiur.Stores; using Microsoft.AspNetCore.StaticFiles; @@ -18,7 +18,7 @@ internal class Program // Create a store to keep objects. var system = await wh.Put("sys", new MemoryStore()); // Create a distibuted server - var esiurServer = await wh.Put("sys/server", new DistributedServer()); + var esiurServer = await wh.Put("sys/server", new EpServer()); // Add your object to the store var service = await wh.Put("sys/demo", new Demo()); diff --git a/Esiur.Examples.StandaloneWebServerDemo/Web/js/app.js b/Esiur.Examples.StandaloneWebServerDemo/Web/js/app.js index 1421da7..5c67947 100644 --- a/Esiur.Examples.StandaloneWebServerDemo/Web/js/app.js +++ b/Esiur.Examples.StandaloneWebServerDemo/Web/js/app.js @@ -1,7 +1,7 @@ async function init() { try { - connection = await wh.get(`iip://${window.location.hostname}`, { + connection = await wh.get(`EP://${window.location.hostname}`, { autoReconnect: true }); diff --git a/Esiur.Stores.EntityCore/EntityStore.cs b/Esiur.Stores.EntityCore/EntityStore.cs index f203e63..75ea7ac 100644 --- a/Esiur.Stores.EntityCore/EntityStore.cs +++ b/Esiur.Stores.EntityCore/EntityStore.cs @@ -34,7 +34,7 @@ using Microsoft.EntityFrameworkCore.Metadata; using System.Reflection; using Esiur.Security.Authority; using System.Collections; -using Esiur.Data.Schema; +using Esiur.Data.Types; namespace Esiur.Stores.EntityCore; public class EntityStore : IStore @@ -179,7 +179,7 @@ public class EntityStore : IStore //throw new NotImplementedException(); } - public bool Modify(IResource resource, string propertyName, object value, ulong? age, DateTime? dateTime) + public bool Modify(IResource resource, PropertyDef propertyDef, object value, ulong? age, DateTime? dateTime) { return true; //throw new NotImplementedException(); @@ -216,7 +216,7 @@ public class EntityStore : IStore throw new NotImplementedException(); } - public AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate) + public AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate) { throw new NotImplementedException(); } diff --git a/Esiur.Stores.MongoDB/MongoDBStore.cs b/Esiur.Stores.MongoDB/MongoDBStore.cs index af35733..8bb7928 100644 --- a/Esiur.Stores.MongoDB/MongoDBStore.cs +++ b/Esiur.Stores.MongoDB/MongoDBStore.cs @@ -35,7 +35,7 @@ using System.Threading.Tasks; using System.Linq; using Esiur.Security.Permissions; using Esiur.Proxy; -using Esiur.Data.Schema; +using Esiur.Data.Types; namespace Esiur.Stores.MongoDB; @@ -342,7 +342,7 @@ public class MongoDBStore : IStore var parents = new BsonArray(); var children = new BsonArray(); - var schema = resource.Instance.Schema; + var typeDef = resource.Instance.Definition; // setup attributes resource.Instance.Variables["children"] = new string[0]; @@ -381,7 +381,7 @@ public class MongoDBStore : IStore var values = new BsonDocument(); - foreach (var pt in schema.Properties) + foreach (var pt in typeDef.Properties) { var rt = pt.PropertyInfo.GetValue(resource, null); @@ -594,7 +594,7 @@ public class MongoDBStore : IStore var parents = new BsonArray(); var children = new BsonArray(); - var schema = resource.Instance.Schema; + var typeDef = resource.Instance.Definition; //foreach (IResource c in resource.Instance.Children) // children.Add(c.Instance.Link); @@ -607,7 +607,7 @@ public class MongoDBStore : IStore var values = new BsonDocument(); - foreach (var pt in schema.Properties) + foreach (var pt in typeDef.Properties) { /* #if NETSTANDARD1_5 @@ -728,11 +728,11 @@ public class MongoDBStore : IStore return reply; } - AsyncReply> GetRecordByAge(IResource resource, ulong fromAge, ulong toAge) + AsyncReply> GetRecordByAge(IResource resource, ulong fromAge, ulong toAge) { - var properties = resource.Instance.Schema.Properties.Where(x => x.Recordable).ToList(); + var properties = resource.Instance.Definition.Properties.Where(x => x.HasHistory).ToList(); - var reply = new AsyncReply>(); + var reply = new AsyncReply>(); AsyncBag bag = new AsyncBag(); @@ -743,7 +743,7 @@ public class MongoDBStore : IStore bag.Then(x => { - var list = new KeyList(); + var list = new KeyList(); for (var i = 0; i < x.Length; i++) list.Add(properties[i], x[i]); @@ -754,11 +754,11 @@ public class MongoDBStore : IStore return reply; } - public AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate) + public AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate) { - var properties = resource.Instance.Schema.Properties.Where(x => x.Recordable).ToList(); + var properties = resource.Instance.Definition.Properties.Where(x => x.HasHistory).ToList(); - var reply = new AsyncReply>(); + var reply = new AsyncReply>(); AsyncBag bag = new AsyncBag(); @@ -769,7 +769,7 @@ public class MongoDBStore : IStore bag.Then(x => { - var list = new KeyList(); + var list = new KeyList(); for (var i = 0; i < x.Length; i++) list.Add(properties[i], x[i]); @@ -780,7 +780,7 @@ public class MongoDBStore : IStore return reply; } - public bool Modify(IResource resource, string propertyName, object value, ulong? age, DateTime? dateTime) + public bool Modify(IResource resource, PropertyDef propertyDef, object value, ulong? age, DateTime? dateTime) { if (resource == this) @@ -790,7 +790,7 @@ public class MongoDBStore : IStore var filter = Builders.Filter.Eq("_id", new BsonObjectId(new ObjectId(objectId))); var update = Builders.Update - .Set("values." + propertyName, new BsonDocument { { "age", BsonValue.Create(age) }, + .Set("values." + propertyDef.Name, new BsonDocument { { "age", BsonValue.Create(age) }, { "modification", dateTime }, { "value", Compose(value) } }); diff --git a/Esiur/Core/InvocationContext.cs b/Esiur/Core/InvocationContext.cs index c97a20b..9c5e847 100644 --- a/Esiur/Core/InvocationContext.cs +++ b/Esiur/Core/InvocationContext.cs @@ -1,4 +1,4 @@ -using Esiur.Net.IIP; +using Esiur.Protocol; using System; using System.Collections.Generic; using System.Text; @@ -36,10 +36,10 @@ namespace Esiur.Core Connection.SendWarning(CallbackId, level, message); } - public DistributedConnection Connection { get; internal set; } + public EpConnection Connection { get; internal set; } - internal InvocationContext(DistributedConnection connection, uint callbackId) + internal InvocationContext(EpConnection connection, uint callbackId) { Connection = connection; CallbackId = callbackId; diff --git a/Esiur/Data/Codec.cs b/Esiur/Data/Codec.cs index 11ab61a..147b7e0 100644 --- a/Esiur/Data/Codec.cs +++ b/Esiur/Data/Codec.cs @@ -25,12 +25,12 @@ SOFTWARE. using System; using System.Collections.Generic; using Esiur.Core; -using Esiur.Net.IIP; using Esiur.Resource; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Collections; +using Esiur.Protocol; namespace Esiur.Data; @@ -39,9 +39,9 @@ namespace Esiur.Data; public static class Codec { - //delegate AsyncReply AsyncParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence); + //delegate AsyncReply AsyncParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence); - delegate object AsyncParser(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence); + delegate object AsyncParser(ParsedTDU tdu, EpConnection connection, uint[] requestSequence); delegate object SyncParser(ParsedTDU tdu, Warehouse warehouse); static AsyncParser[][] FixedAsyncParsers = new AsyncParser[][] @@ -189,10 +189,10 @@ public static class Codec /// Bytes array /// Zero-indexed offset. /// Output the number of bytes parsed - /// DistributedConnection is required in case a structure in the array holds items at the other end. + /// EpConnection is required in case a structure in the array holds items at the other end. /// DataType, in case the data is not prepended with DataType /// Value - public static (uint, object) ParseAsync(byte[] data, uint offset, DistributedConnection connection, uint[] requestSequence) + public static (uint, object) ParseAsync(byte[] data, uint offset, EpConnection connection, uint[] requestSequence) { var tdu = ParsedTDU.Parse(data, offset, (uint)data.Length); @@ -219,7 +219,7 @@ public static class Codec } } - public static (uint, object) ParseAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static (uint, object) ParseAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { if (tdu.Class == TDUClass.Invalid) throw new NullReferenceException("DataType can't be parsed."); @@ -293,21 +293,21 @@ public static class Codec /// Check if a resource is local to a given connection. /// /// Resource to check. - /// DistributedConnection to check if the resource is local to it. + /// EpConnection to check if the resource is local to it. /// True, if the resource owner is the given connection, otherwise False. - public static bool IsLocalResource(IResource resource, DistributedConnection connection) + public static bool IsLocalResource(IResource resource, EpConnection connection) { if (resource == null) throw new NullReferenceException("Resource is null."); - if (resource is DistributedResource) - if (((DistributedResource)(resource)).DistributedResourceConnection == connection) + if (resource is EpResource) + if (((EpResource)(resource)).DistributedResourceConnection == connection) return true; return false; } - public delegate TDU Composer(object value, Warehouse warehouse, DistributedConnection connection); + public delegate TDU Composer(object value, Warehouse warehouse, EpConnection connection); public static Dictionary Composers = new Dictionary() { @@ -382,7 +382,7 @@ public static class Codec internal static TDU - ComposeInternal(object valueOrSource, Warehouse warehouse, DistributedConnection connection) + ComposeInternal(object valueOrSource, Warehouse warehouse, EpConnection connection) { if (valueOrSource == null) return new TDU(TDUIdentifier.Null, null, 0); @@ -400,9 +400,9 @@ public static class Codec else if (genericType == typeof(Func<>)) { var args = genericType.GetGenericArguments(); - if (args.Length == 2 && args[0] == typeof(DistributedConnection)) + if (args.Length == 2 && args[0] == typeof(EpConnection)) { - //Func a; + //Func a; //a.Invoke() } } @@ -497,10 +497,10 @@ public static class Codec /// Compose a variable /// /// Value to compose. - /// DistributedConnection is required to check locality. + /// EpConnection is required to check locality. /// If True, prepend the DataType at the beginning of the output. /// Array of bytes in the network byte order. - public static byte[] Compose(object valueOrSource, Warehouse warehouse, DistributedConnection connection)//, bool prependType = true) + public static byte[] Compose(object valueOrSource, Warehouse warehouse, EpConnection connection)//, bool prependType = true) { var tdu = ComposeInternal(valueOrSource, warehouse, connection); return tdu.Composed; diff --git a/Esiur/Data/DataConverter.cs b/Esiur/Data/DataConverter.cs index 527703c..efdac8e 100644 --- a/Esiur/Data/DataConverter.cs +++ b/Esiur/Data/DataConverter.cs @@ -26,8 +26,6 @@ using System; using System.Collections.Generic; using System.Linq; using System.Text; -using Esiur.Net.IIP; - using System.Runtime.InteropServices; using System.Diagnostics; using System.Net; diff --git a/Esiur/Data/DataDeserializer - Copy.cs b/Esiur/Data/DataDeserializer - Copy.cs index c25cbc1..6532f12 100644 --- a/Esiur/Data/DataDeserializer - Copy.cs +++ b/Esiur/Data/DataDeserializer - Copy.cs @@ -1,5 +1,5 @@ using Esiur.Core; -using Esiur.Net.IIP; +using Esiur.Net.EP; using Esiur.Resource; using System; using System.Collections.Generic; @@ -14,115 +14,115 @@ namespace Esiur.Data; public static class DataDeserializer { - public static AsyncReply NullParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply NullParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { return new AsyncReply(null); } - public static AsyncReply BooleanTrueParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply BooleanTrueParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { return new AsyncReply(true); } - public static AsyncReply BooleanFalseParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply BooleanFalseParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { return new AsyncReply(false); } - public static AsyncReply NotModifiedParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply NotModifiedParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { return new AsyncReply(new NotModified()); } - public static AsyncReply ByteParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply ByteParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { return new AsyncReply(data[offset]); } - public static AsyncReply SByteParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply SByteParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { return new AsyncReply((sbyte)data[offset]); } - public static unsafe AsyncReply Char16Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply Char16Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(*(char*)ptr); } - public static AsyncReply Char8Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply Char8Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { return new AsyncReply((char)data[offset]); } - public static unsafe AsyncReply Int16Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply Int16Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(*(short*)ptr); } - public static unsafe AsyncReply UInt16Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply UInt16Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(*(ushort*)ptr); } - public static unsafe AsyncReply Int32Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply Int32Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(*(int*)ptr); } - public static unsafe AsyncReply UInt32Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply UInt32Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(*(uint*)ptr); } - public static unsafe AsyncReply Float32Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply Float32Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(*(float*)ptr); } - public static unsafe AsyncReply Float64Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply Float64Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(*(double*)ptr); } - public static unsafe AsyncReply Float128Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply Float128Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(*(decimal*)ptr); } - public static unsafe AsyncReply Int128Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply Int128Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(*(decimal*)ptr); } - public static unsafe AsyncReply UInt128Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply UInt128Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(*(decimal*)ptr); } - public static unsafe AsyncReply Int64Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply Int64Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(*(long*)ptr); } - public static unsafe AsyncReply UInt64Parser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply UInt64Parser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(*(ulong*)ptr); } - public static unsafe AsyncReply DateTimeParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply DateTimeParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return new AsyncReply(new DateTime(*(long*)ptr, DateTimeKind.Utc)); @@ -130,30 +130,30 @@ public static class DataDeserializer } - public static unsafe AsyncReply ResourceParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply ResourceParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return connection.Fetch(*(uint*)ptr, requestSequence); } - public static unsafe AsyncReply LocalResourceParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply LocalResourceParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &data[offset]) return Warehouse.GetById(*(uint*)ptr); } - public static unsafe AsyncReply RawDataParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply RawDataParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { return new AsyncReply(data.Clip(offset, length)); } - public static unsafe AsyncReply StringParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply StringParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { return new AsyncReply(data.GetString(offset, length)); } - public static unsafe AsyncReply RecordParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply RecordParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { var reply = new AsyncReply(); @@ -229,12 +229,12 @@ public static class DataDeserializer return reply; } - public static unsafe AsyncReply ConstantParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply ConstantParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { throw new NotImplementedException(); } - public static unsafe AsyncReply EnumParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply EnumParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { var classId = data.GetUUID(offset); @@ -262,7 +262,7 @@ public static class DataDeserializer - public static AsyncReply RecordListParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply RecordListParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { var rt = new AsyncBag(); @@ -286,7 +286,7 @@ public static class DataDeserializer return rt; } - public static AsyncReply ResourceListParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply ResourceListParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { var rt = new AsyncBag(); @@ -311,7 +311,7 @@ public static class DataDeserializer } - public static AsyncBag ListParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncBag ListParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { var rt = new AsyncBag(); @@ -335,7 +335,7 @@ public static class DataDeserializer return rt; } - public static AsyncReply TypedMapParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply TypedMapParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { // get key type var (keyCs, keyRepType) = RepresentationType.Parse(data, offset); @@ -384,7 +384,7 @@ public static class DataDeserializer } - public static AsyncReply TupleParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply TupleParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { var results = new AsyncBag(); var rt = new AsyncReply(); @@ -443,7 +443,7 @@ public static class DataDeserializer return rt; } - public static AsyncReply TypedListParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply TypedListParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence) { var rt = new AsyncBag(); @@ -478,7 +478,7 @@ public static class DataDeserializer } - public static AsyncBag PropertyValueArrayParser(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence)//, bool ageIncluded = true) + public static AsyncBag PropertyValueArrayParser(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence)//, bool ageIncluded = true) { var rt = new AsyncBag(); @@ -499,7 +499,7 @@ public static class DataDeserializer } - public static (uint, AsyncReply) PropertyValueParser(byte[] data, uint offset, DistributedConnection connection, uint[] requestSequence)//, bool ageIncluded = true) + public static (uint, AsyncReply) PropertyValueParser(byte[] data, uint offset, EpConnection connection, uint[] requestSequence)//, bool ageIncluded = true) { var reply = new AsyncReply(); @@ -520,7 +520,7 @@ public static class DataDeserializer return (16 + valueSize, reply); } - public static AsyncReply> HistoryParser(byte[] data, uint offset, uint length, IResource resource, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply> HistoryParser(byte[] data, uint offset, uint length, IResource resource, EpConnection connection, uint[] requestSequence) { //var count = (int)toAge - (int)fromAge; diff --git a/Esiur/Data/DataDeserializer.cs b/Esiur/Data/DataDeserializer.cs index b372518..3629c78 100644 --- a/Esiur/Data/DataDeserializer.cs +++ b/Esiur/Data/DataDeserializer.cs @@ -1,9 +1,9 @@ using Esiur.Core; using Esiur.Data; using Esiur.Data.GVWIE; -using Esiur.Data.Schema; +using Esiur.Data.Types; using Esiur.Misc; -using Esiur.Net.IIP; +using Esiur.Protocol; using Esiur.Resource; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; @@ -17,7 +17,7 @@ namespace Esiur.Data; public static class DataDeserializer { - public static object NullParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static object NullParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { return null; } @@ -27,7 +27,7 @@ public static class DataDeserializer return null; } - public static object BooleanTrueParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static object BooleanTrueParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { return true; } @@ -37,7 +37,7 @@ public static class DataDeserializer return true; } - public static object BooleanFalseParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static object BooleanFalseParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { return false; } @@ -47,7 +47,7 @@ public static class DataDeserializer return false; } - public static object NotModifiedParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static object NotModifiedParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { return NotModified.Default; } @@ -57,7 +57,7 @@ public static class DataDeserializer return NotModified.Default; } - public static object UInt8ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static object UInt8ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { return tdu.Data[tdu.Offset]; } @@ -66,7 +66,7 @@ public static class DataDeserializer return tdu.Data[tdu.Offset]; } - public static object Int8ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static object Int8ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { return (sbyte)tdu.Data[tdu.Offset]; } @@ -75,7 +75,7 @@ public static class DataDeserializer return (sbyte)tdu.Data[tdu.Offset]; } - public static unsafe object Char16ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object Char16ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(char*)ptr; @@ -87,7 +87,7 @@ public static class DataDeserializer return *(char*)ptr; } - public static object Char8ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static object Char8ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { return (char)tdu.Data[tdu.Offset]; } @@ -98,7 +98,7 @@ public static class DataDeserializer } - public static unsafe object Int16ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object Int16ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(short*)ptr; @@ -110,7 +110,7 @@ public static class DataDeserializer return *(short*)ptr; } - public static unsafe object UInt16ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object UInt16ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(ushort*)ptr; @@ -122,7 +122,7 @@ public static class DataDeserializer return *(ushort*)ptr; } - public static unsafe object Int32ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object Int32ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(int*)ptr; @@ -134,7 +134,7 @@ public static class DataDeserializer return *(int*)ptr; } - public static unsafe object UInt32ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object UInt32ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(uint*)ptr; @@ -147,7 +147,7 @@ public static class DataDeserializer } - public static unsafe object Float32ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object Float32ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(float*)ptr; @@ -159,7 +159,7 @@ public static class DataDeserializer return *(float*)ptr; } - public static unsafe object Float64ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object Float64ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(double*)ptr; @@ -172,7 +172,7 @@ public static class DataDeserializer } - public static unsafe object Decimal128ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object Decimal128ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(decimal*)ptr; @@ -184,7 +184,7 @@ public static class DataDeserializer return *(decimal*)ptr; } - public static unsafe object UUIDParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object UUIDParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { return new UUID(tdu.Data, tdu.Offset); } @@ -196,7 +196,7 @@ public static class DataDeserializer - public static unsafe object Int128ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object Int128ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr1 = &tdu.Data[tdu.Offset]) fixed (byte* ptr2 = &tdu.Data[tdu.Offset + 8]) @@ -210,7 +210,7 @@ public static class DataDeserializer return new Int128(*(ulong*)ptr1, *(ulong*)ptr2); } - public static unsafe object UInt128ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object UInt128ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr1 = &tdu.Data[tdu.Offset]) fixed (byte* ptr2 = &tdu.Data[tdu.Offset + 8]) @@ -224,7 +224,7 @@ public static class DataDeserializer return new UInt128(*(ulong*)ptr1, *(ulong*)ptr2); } - public static unsafe object Int64ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object Int64ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(long*)ptr; @@ -237,7 +237,7 @@ public static class DataDeserializer } - public static unsafe object UInt64ParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object UInt64ParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return *(ulong*)ptr; @@ -250,7 +250,7 @@ public static class DataDeserializer } - public static unsafe object DateTimeParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object DateTimeParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) return new DateTime(*(long*)ptr, DateTimeKind.Utc); @@ -264,7 +264,7 @@ public static class DataDeserializer } - public static object ResourceLinkParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static object ResourceLinkParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { var link = tdu.Data.GetString(tdu.Offset, (uint)tdu.ContentLength); if (connection == null) @@ -283,7 +283,7 @@ public static class DataDeserializer return new ResourceLink(link); } - public static unsafe object ResourceParser8Async(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object ResourceParser8Async(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { if (connection == null) return new ResourceId(false, tdu.Data[tdu.Offset]); @@ -296,7 +296,7 @@ public static class DataDeserializer return new ResourceId(false, tdu.Data[tdu.Offset]); } - public static unsafe object LocalResourceParser8Async(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object LocalResourceParser8Async(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { if (connection == null) return new ResourceId(true, tdu.Data[tdu.Offset]); @@ -309,7 +309,7 @@ public static class DataDeserializer return new ResourceId(true, tdu.Data[tdu.Offset]); } - public static unsafe object ResourceParser16Async(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object ResourceParser16Async(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) if (connection == null) @@ -325,7 +325,7 @@ public static class DataDeserializer } - public static unsafe object LocalResourceParser16Async(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object LocalResourceParser16Async(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) if (connection == null) @@ -340,7 +340,7 @@ public static class DataDeserializer return new ResourceId(true, *(ushort*)ptr); } - public static unsafe object ResourceParser32Async(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object ResourceParser32Async(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) if (connection == null) @@ -356,7 +356,7 @@ public static class DataDeserializer } - public static unsafe object LocalResourceParser32Async(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object LocalResourceParser32Async(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { fixed (byte* ptr = &tdu.Data[tdu.Offset]) if (connection == null) @@ -372,7 +372,7 @@ public static class DataDeserializer } - public static unsafe object RawDataParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object RawDataParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { return tdu.Data.Clip(tdu.Offset, (uint)tdu.ContentLength); } @@ -383,7 +383,7 @@ public static class DataDeserializer } - public static unsafe object StringParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object StringParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { return tdu.Data.GetString(tdu.Offset, (uint)tdu.ContentLength); } @@ -393,10 +393,10 @@ public static class DataDeserializer return tdu.Data.GetString(tdu.Offset, (uint)tdu.ContentLength); } - public static unsafe object RecordParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object RecordParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { - var classId = tdu.Metadata.GetUUID(0); - var template = connection.Instance.Warehouse.GetTemplateByClassId(classId, + var typeId = tdu.Metadata.GetUUID(0); + var typeDef = connection.Instance.Warehouse.GetTypeDefById(typeId, TypeDefKind.Record); var rt = new AsyncReply(); @@ -410,9 +410,9 @@ public static class DataDeserializer var length = tdu.ContentLength; var ends = offset + (uint)length; - var initRecord = (TypeDef template) => + var initRecord = (TypeDef typeDef) => { - for (var i = 0; i < template.Properties.Length; i++) + for (var i = 0; i < typeDef.Properties.Length; i++) { current = ParsedTDU.Parse(tdu.Data, offset, ends); @@ -428,7 +428,7 @@ public static class DataDeserializer } else if (current.Identifier == TDUIdentifier.TypeOfTarget) { - var (idf, mt) = template.Properties[i].ValueType.GetMetadata(); + var (idf, mt) = typeDef.Properties[i].ValueType.GetMetadata(); current.Class = TDUClass.Typed; current.Identifier = idf; current.Metadata = mt; @@ -454,16 +454,16 @@ public static class DataDeserializer list.Then(results => { - if (template.DefinedType != null) + if (typeDef.DefinedType != null) { - var record = Activator.CreateInstance(template.DefinedType) as IRecord; - for (var i = 0; i < template.Properties.Length; i++) + var record = Activator.CreateInstance(typeDef.DefinedType) as IRecord; + for (var i = 0; i < typeDef.Properties.Length; i++) { try { - var v = RuntimeCaster.Cast(results[i], template.Properties[i].PropertyInfo.PropertyType); - template.Properties[i].PropertyInfo.SetValue(record, v); + var v = RuntimeCaster.Cast(results[i], typeDef.Properties[i].PropertyInfo.PropertyType); + typeDef.Properties[i].PropertyInfo.SetValue(record, v); } catch (Exception ex) { @@ -477,8 +477,8 @@ public static class DataDeserializer { var record = new Record(); - for (var i = 0; i < template.Properties.Length; i++) - record.Add(template.Properties[i].Name, results[i]); + for (var i = 0; i < typeDef.Properties.Length; i++) + record.Add(typeDef.Properties[i].Name, results[i]); rt.Trigger(record); } @@ -492,14 +492,14 @@ public static class DataDeserializer }; - if (template != null) + if (typeDef != null) { - initRecord(template); + initRecord(typeDef); } else if (connection != null) { - // try to get the template from the other end - connection.GetTemplate(classId).Then(tmp => + // try to get the TypeDef from the other end + connection.GetTypeDefById(typeId).Then(tmp => { initRecord(tmp); }).Error(x => rt.TriggerError(x)); @@ -511,87 +511,20 @@ public static class DataDeserializer return rt; - - - //var classId = tdu.Metadata.GetUUID(0); - - //var template = connection.Instance.Warehouse.GetTemplateByClassId(classId, TemplateType.Record); - - //var initRecord = (TypeSchema template) => - //{ - // ListParserAsync(tdu, connection, requestSequence).Then(r => - // { - // var ar = (object[])r; - - // if (template == null) - // { - // // @TODO: add parse if no template settings - // reply.TriggerError(new AsyncException(ErrorType.Management, (ushort)ExceptionCode.TemplateNotFound, - // "Template not found for record.")); - // } - // else if (template.DefinedType != null) - // { - // var record = Activator.CreateInstance(template.DefinedType) as IRecord; - // for (var i = 0; i < template.Properties.Length; i++) - // { - // try - // { - // //var v = Convert.ChangeType(ar[i], template.Properties[i].PropertyInfo.PropertyType); - // var v = RuntimeCaster.Cast(ar[i], template.Properties[i].PropertyInfo.PropertyType); - // template.Properties[i].PropertyInfo.SetValue(record, v); - // } - // catch (Exception ex) - // { - // Global.Log(ex); - // } - // } - - // reply.Trigger(record); - // } - // else - // { - // var record = new Record(); - - // for (var i = 0; i < template.Properties.Length; i++) - // record.Add(template.Properties[i].Name, ar[i]); - - // reply.Trigger(record); - // } - - // }); - //}; - - //if (template != null) - //{ - // initRecord(template); - //} - //else if (connection != null) - //{ - // // try to get the template from the other end - // connection.GetTemplate(classId).Then(tmp => - // { - // initRecord(tmp); - // }).Error(x => reply.TriggerError(x)); - //} - //else - //{ - // initRecord(null); - //} - - //return reply; + } public static unsafe object RecordParser(ParsedTDU tdu, Warehouse warehouse) { var classId = tdu.Metadata.GetUUID(0); - var template = warehouse.GetTypeDefByClassId(classId, TypeDefKind.Record); + var typeDef = warehouse.GetTypeDefById(classId, TypeDefKind.Record); - if (template == null) + if (typeDef == null) { - // @TODO: add parse if no template settings - throw new AsyncException(ErrorType.Management, (ushort)ExceptionCode.SchemaNotFound, - "Template not found for record."); + // @TODO: add parse if no TypeDef settings + throw new AsyncException(ErrorType.Management, (ushort)ExceptionCode.TypeDefNotFound, + "TypeDef not found for record."); } var list = new List(); @@ -604,7 +537,7 @@ public static class DataDeserializer var ends = offset + (uint)length; - for (var i = 0; i < template.Properties.Length; i++) + for (var i = 0; i < typeDef.Properties.Length; i++) { current = ParsedTDU.Parse(tdu.Data, offset, ends); @@ -620,7 +553,7 @@ public static class DataDeserializer } else if (current.Identifier == TDUIdentifier.TypeOfTarget) { - var (idf, mt) = template.Properties[i].ValueType.GetMetadata(); + var (idf, mt) = typeDef.Properties[i].ValueType.GetMetadata(); current.Class = TDUClass.Typed; current.Identifier = idf; current.Metadata = mt; @@ -642,16 +575,16 @@ public static class DataDeserializer } - if (template.DefinedType != null) + if (typeDef.DefinedType != null) { - var record = Activator.CreateInstance(template.DefinedType) as IRecord; - for (var i = 0; i < template.Properties.Length; i++) + var record = Activator.CreateInstance(typeDef.DefinedType) as IRecord; + for (var i = 0; i < typeDef.Properties.Length; i++) { try { - var v = RuntimeCaster.Cast(list[i], template.Properties[i].PropertyInfo.PropertyType); - template.Properties[i].PropertyInfo.SetValue(record, v); + var v = RuntimeCaster.Cast(list[i], typeDef.Properties[i].PropertyInfo.PropertyType); + typeDef.Properties[i].PropertyInfo.SetValue(record, v); } catch (Exception ex) { @@ -665,14 +598,14 @@ public static class DataDeserializer { var record = new Record(); - for (var i = 0; i < template.Properties.Length; i++) - record.Add(template.Properties[i].Name, list[i]); + for (var i = 0; i < typeDef.Properties.Length; i++) + record.Add(typeDef.Properties[i].Name, list[i]); return record; } } - public static unsafe object ConstantParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe object ConstantParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { throw new NotImplementedException(); } @@ -682,26 +615,26 @@ public static class DataDeserializer throw new NotImplementedException(); } - public static unsafe AsyncReply EnumParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static unsafe AsyncReply EnumParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { - var classId = tdu.Metadata.GetUUID(0); + var typeId = tdu.Metadata.GetUUID(0); var index = tdu.Data[tdu.Offset]; - var template = connection.Instance.Warehouse.GetTemplateByClassId(classId, + var typeDef = connection.Instance.Warehouse.GetTypeDefById(typeId, TypeDefKind.Enum); - if (template != null) + if (typeDef != null) { - return new AsyncReply(template.Constants[index].Value); + return new AsyncReply(typeDef.Constants[index].Value); } else { var reply = new AsyncReply(); - connection.GetTemplate(classId).Then(tmp => + connection.GetTypeDefById(typeId).Then(tmp => { reply.Trigger(tmp.Constants[index].Value); }).Error(x => reply.TriggerError(x)); @@ -713,25 +646,25 @@ public static class DataDeserializer public static unsafe object EnumParser(ParsedTDU tdu, Warehouse warehouse) { - var classId = tdu.Metadata.GetUUID(0); + var typeId = tdu.Metadata.GetUUID(0); var index = tdu.Data[tdu.Offset]; - var template = warehouse.GetTemplateByClassId(classId, TypeDefKind.Enum); + var typeDef = warehouse.GetTypeDefById(typeId, TypeDefKind.Enum); - if (template != null) + if (typeDef != null) { - return template.Constants[index].Value; + return typeDef.Constants[index].Value; } else { - throw new AsyncException(ErrorType.Management, (ushort)ExceptionCode.SchemaNotFound, - "Template not found for enum."); + throw new AsyncException(ErrorType.Management, (ushort)ExceptionCode.TypeDefNotFound, + "TypeDef not found for enum."); } } - public static AsyncReply RecordListParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply RecordListParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { var rt = new AsyncBag(); @@ -784,7 +717,7 @@ public static class DataDeserializer return rt.ToArray(); } - public static AsyncReply ResourceListParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply ResourceListParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { var rt = new AsyncBag(); @@ -838,7 +771,7 @@ public static class DataDeserializer return rt.ToArray(); } - public static AsyncBag ListParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static AsyncBag ListParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { //var rt = new AsyncBag(); @@ -990,7 +923,7 @@ public static class DataDeserializer } - public static AsyncReply TypedMapParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply TypedMapParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { var rt = new AsyncReply(); @@ -1105,12 +1038,12 @@ public static class DataDeserializer var enumType = tru.GetRuntimeType(warehouse); var enums = Array.CreateInstance(enumType, (int)tdu.ContentLength); - var enumTemplate = warehouse.GetTemplateByType(enumType); + var enumTypeDef = warehouse.GetTypeDefByType(enumType); for (var i = 0; i < (int)tdu.ContentLength; i++) { var index = tdu.Data[tdu.Offset + i]; - enums.SetValue(enumTemplate.Constants[index].Value, i); + enums.SetValue(enumTypeDef.Constants[index].Value, i); } return enums; @@ -1202,7 +1135,7 @@ public static class DataDeserializer } - public static AsyncReply TupleParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply TupleParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { var rt = new AsyncReply(); @@ -1392,7 +1325,7 @@ public static class DataDeserializer } - public static AsyncReply TypedArrayParserAsync(ParsedTDU tdu, TRU tru, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply TypedArrayParserAsync(ParsedTDU tdu, TRU tru, EpConnection connection, uint[] requestSequence) { switch (tru.Identifier) { @@ -1419,13 +1352,13 @@ public static class DataDeserializer var enumType = tru.GetRuntimeType(connection.Instance.Warehouse); var rt = Array.CreateInstance(enumType, (int)tdu.ContentLength); - var enumTemplate = connection.Instance.Warehouse.GetTemplateByType(enumType); + var enumTypeDef = connection.Instance.Warehouse.GetTypeDefByType(enumType); for (var i = 0; i < (int)tdu.ContentLength; i++) { var index = tdu.Data[tdu.Offset + i]; - rt.SetValue(Enum.ToObject(enumType, enumTemplate.Constants[index].Value), i); + rt.SetValue(Enum.ToObject(enumType, enumTypeDef.Constants[index].Value), i); } return new AsyncReply(rt); @@ -1488,7 +1421,7 @@ public static class DataDeserializer } - public static AsyncReply TypedListParserAsync(ParsedTDU tdu, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply TypedListParserAsync(ParsedTDU tdu, EpConnection connection, uint[] requestSequence) { // get the type var (hdrCs, tru) = TRU.Parse(tdu.Metadata, 0); @@ -1573,7 +1506,7 @@ public static class DataDeserializer return TypedArrayParser(tdu, tru, warehouse); } - public static AsyncBag PropertyValueArrayParserAsync(byte[] data, uint offset, uint length, DistributedConnection connection, uint[] requestSequence)//, bool ageIncluded = true) + public static AsyncBag PropertyValueArrayParserAsync(byte[] data, uint offset, uint length, EpConnection connection, uint[] requestSequence)//, bool ageIncluded = true) { var rt = new AsyncBag(); @@ -1597,7 +1530,7 @@ public static class DataDeserializer } - public static (uint, AsyncReply) PropertyValueParserAsync(byte[] data, uint offset, DistributedConnection connection, uint[] requestSequence)//, bool ageIncluded = true) + public static (uint, AsyncReply) PropertyValueParserAsync(byte[] data, uint offset, EpConnection connection, uint[] requestSequence)//, bool ageIncluded = true) { var reply = new AsyncReply(); @@ -1625,13 +1558,13 @@ public static class DataDeserializer return (16 + valueSize, reply); } - public static AsyncReply> HistoryParserAsync(byte[] data, uint offset, uint length, IResource resource, DistributedConnection connection, uint[] requestSequence) + public static AsyncReply> HistoryParserAsync(byte[] data, uint offset, uint length, IResource resource, EpConnection connection, uint[] requestSequence) { //var count = (int)toAge - (int)fromAge; - var list = new KeyList(); + var list = new KeyList(); - var reply = new AsyncReply>(); + var reply = new AsyncReply>(); var bagOfBags = new AsyncBag(); @@ -1639,7 +1572,7 @@ public static class DataDeserializer while (offset < ends) { var index = data[offset++]; - var pt = resource.Instance.Schema.GetPropertyDefByIndex(index); + var pt = resource.Instance.Definition.GetPropertyDefByIndex(index); list.Add(pt, null); var cs = data.GetUInt32(offset, Endian.Little); offset += 4; diff --git a/Esiur/Data/DataSerializer.cs b/Esiur/Data/DataSerializer.cs index cdb8761..e2c6a97 100644 --- a/Esiur/Data/DataSerializer.cs +++ b/Esiur/Data/DataSerializer.cs @@ -1,7 +1,7 @@ using Esiur.Core; using Esiur.Data.GVWIE; -using Esiur.Data.Schema; -using Esiur.Net.IIP; +using Esiur.Data.Types; +using Esiur.Protocol; using Esiur.Resource; using Microsoft.CodeAnalysis; using System; @@ -17,7 +17,7 @@ public static class DataSerializer { public delegate byte[] Serializer(object value); - public static unsafe TDU Int32Composer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU Int32Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (int)value; @@ -44,7 +44,7 @@ public static class DataSerializer } } - public static unsafe TDU UInt32Composer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU UInt32Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (uint)value; @@ -73,7 +73,7 @@ public static class DataSerializer } } - public static unsafe TDU Int16Composer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU Int16Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (short)value; @@ -93,7 +93,7 @@ public static class DataSerializer } } - public static unsafe TDU UInt16Composer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU UInt16Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (ushort)value; @@ -114,7 +114,7 @@ public static class DataSerializer } - public static unsafe TDU Float32Composer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU Float32Composer(object value, Warehouse warehouse, EpConnection connection) { float v = (float)value; @@ -152,7 +152,7 @@ public static class DataSerializer } - public unsafe static TDU Float64Composer(object value, Warehouse warehouse, DistributedConnection connection) + public unsafe static TDU Float64Composer(object value, Warehouse warehouse, EpConnection connection) { double v = (double)value; @@ -211,7 +211,7 @@ public static class DataSerializer return new TDU(TDUIdentifier.Float64, rt, 8); } } - public static unsafe TDU Int64Composer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU Int64Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (long)value; @@ -249,7 +249,7 @@ public static class DataSerializer } } - public static unsafe TDU UInt64Composer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU UInt64Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (ulong)value; @@ -288,7 +288,7 @@ public static class DataSerializer } - public static unsafe TDU DateTimeComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU DateTimeComposer(object value, Warehouse warehouse, EpConnection connection) { var v = ((DateTime)value).ToUniversalTime().Ticks; var rt = new byte[8]; @@ -298,7 +298,7 @@ public static class DataSerializer return new TDU(TDUIdentifier.DateTime, rt, 8); } - //public static unsafe TDU Decimal128Composer(object value, Warehouse warehouse, DistributedConnection connection) + //public static unsafe TDU Decimal128Composer(object value, Warehouse warehouse, EpConnection connection) //{ // var v = (decimal)value; // var rt = new byte[16]; @@ -308,7 +308,7 @@ public static class DataSerializer // return new TDU(TDUIdentifier.Decimal128, rt, 16); //} - public static unsafe TDU Decimal128Composer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU Decimal128Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (decimal)value; @@ -381,14 +381,14 @@ public static class DataSerializer } } - public static TDU StringComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU StringComposer(object value, Warehouse warehouse, EpConnection connection) { var b = Encoding.UTF8.GetBytes((string)value); return new TDU(TDUIdentifier.String, b, (uint)b.Length); } - public static TDU ResourceLinkComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU ResourceLinkComposer(object value, Warehouse warehouse, EpConnection connection) { var b = Encoding.UTF8.GetBytes((ResourceLink)value); @@ -396,7 +396,7 @@ public static class DataSerializer } - public static TDU EnumComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU EnumComposer(object value, Warehouse warehouse, EpConnection connection) { if (value == null) return new TDU(TDUIdentifier.Null, null, 0); @@ -406,11 +406,11 @@ public static class DataSerializer //if (warehouse == null) // throw new Exception("Warehouse not set."); - var template = warehouse.GetTemplateByType(value.GetType()); + var typeDef = warehouse.GetTypeDefByType(value.GetType()); var intVal = Convert.ChangeType(value, (value as Enum).GetTypeCode()); - var ct = template.Constants.FirstOrDefault(x => x.Value.Equals(intVal)); + var ct = typeDef.Constants.FirstOrDefault(x => x.Value.Equals(intVal)); if (ct == null) return new TDU(TDUIdentifier.Null, null, 0); @@ -418,28 +418,28 @@ public static class DataSerializer //return Codec.ComposeInternal(intVal, warehouse, connection); return new TDU(TDUIdentifier.TypedEnum, - new byte[] { ct.Index }, 1, template.ClassId.Data); + new byte[] { ct.Index }, 1, typeDef.Id.Data); } - public static TDU UInt8Composer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU UInt8Composer(object value, Warehouse warehouse, EpConnection connection) { return new TDU(TDUIdentifier.UInt8, new byte[] { (byte)value }, 1); } - public static TDU Int8Composer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU Int8Composer(object value, Warehouse warehouse, EpConnection connection) { return new TDU(TDUIdentifier.Int8, new byte[] { (byte)(sbyte)value }, 1); } - public static TDU Char8Composer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU Char8Composer(object value, Warehouse warehouse, EpConnection connection) { return new TDU(TDUIdentifier.Int8, new byte[] { (byte)(char)value }, 1); } - public static unsafe TDU Char16Composer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU Char16Composer(object value, Warehouse warehouse, EpConnection connection) { var v = (char)value; var rt = new byte[2]; @@ -450,7 +450,7 @@ public static class DataSerializer } - public static TDU BoolComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU BoolComposer(object value, Warehouse warehouse, EpConnection connection) { if ((bool)value) { @@ -463,24 +463,24 @@ public static class DataSerializer } - public static TDU NotModifiedComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU NotModifiedComposer(object value, Warehouse warehouse, EpConnection connection) { return new TDU(TDUIdentifier.NotModified, null, 0); } - public static TDU RawDataComposerFromArray(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU RawDataComposerFromArray(object value, Warehouse warehouse, EpConnection connection) { var b = (byte[])value; return new TDU(TDUIdentifier.RawData, b, (uint)b.Length); } - public static TDU RawDataComposerFromList(dynamic value, Warehouse warehouse, DistributedConnection connection) + public static TDU RawDataComposerFromList(dynamic value, Warehouse warehouse, EpConnection connection) { var b = value as List; return new TDU(TDUIdentifier.RawData, b.ToArray(), (uint)b.Count); } - //public static (TDUIdentifier, byte[]) ListComposerFromArray(dynamic value, DistributedConnection connection) + //public static (TDUIdentifier, byte[]) ListComposerFromArray(dynamic value, EpConnection connection) //{ // var rt = new List(); // var array = (object[])value; @@ -491,7 +491,7 @@ public static class DataSerializer // return (TDUIdentifier.List, rt.ToArray()); //} - public static TDU ListComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU ListComposer(object value, Warehouse warehouse, EpConnection connection) { var composed = DynamicArrayComposer((IEnumerable)value, warehouse, connection); @@ -534,7 +534,7 @@ public static class DataSerializer //return new TDU(TDUIdentifier.List, rt.ToArray(), (uint)rt.Count); } - public static byte[] TypedArrayComposer(IEnumerable value, TRU tru, Warehouse warehouse, DistributedConnection connection) + public static byte[] TypedArrayComposer(IEnumerable value, TRU tru, Warehouse warehouse, EpConnection connection) { byte[] composed; @@ -570,12 +570,12 @@ public static class DataSerializer { var rt = new List(); - var template = warehouse.GetTemplateByType(tru.GetRuntimeType(warehouse)); + var typeDef = warehouse.GetTypeDefByType(tru.GetRuntimeType(warehouse)); foreach (var v in value) { var intVal = Convert.ChangeType(v, (v as Enum).GetTypeCode()); - var ct = template.Constants.FirstOrDefault(x => x.Value.Equals(intVal)); + var ct = typeDef.Constants.FirstOrDefault(x => x.Value.Equals(intVal)); if (ct == null) throw new Exception("Unknown Enum."); rt.Add(ct.Index); @@ -630,7 +630,7 @@ public static class DataSerializer } - public static TDU TypedListComposer(IEnumerable value, Type type, Warehouse warehouse, DistributedConnection connection) + public static TDU TypedListComposer(IEnumerable value, Type type, Warehouse warehouse, EpConnection connection) { var tru = TRU.FromType(type); @@ -644,7 +644,7 @@ public static class DataSerializer return new TDU(TDUIdentifier.TypedList, composed, (uint)composed.Length, metadata); } - //public static byte[] PropertyValueComposer(PropertyValue propertyValue, DistributedConnection connection)//, bool includeAge = true) + //public static byte[] PropertyValueComposer(PropertyValue propertyValue, EpConnection connection)//, bool includeAge = true) //{ // var rt = new BinaryList(); @@ -655,7 +655,7 @@ public static class DataSerializer // .ToArray(); //} - public static TDU PropertyValueArrayComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU PropertyValueArrayComposer(object value, Warehouse warehouse, EpConnection connection) { if (value == null) return new TDU(TDUIdentifier.Null, new byte[0], 0); @@ -674,7 +674,7 @@ public static class DataSerializer (uint)rt.Count); } - public static TDU TypedMapComposer(object value, Type keyType, Type valueType, Warehouse warehouse, DistributedConnection connection) + public static TDU TypedMapComposer(object value, Type keyType, Type valueType, Warehouse warehouse, EpConnection connection) { if (value == null) return new TDU(TDUIdentifier.Null, new byte[0], 0); @@ -712,7 +712,7 @@ public static class DataSerializer //return new TDU(TDUIdentifier.TypedMap, rt.ToArray(), (uint)rt.Count, // ); } - public static TDU TypedDictionaryComposer(object value, Type keyType, Type valueType, Warehouse warehouse, DistributedConnection connection) + public static TDU TypedDictionaryComposer(object value, Type keyType, Type valueType, Warehouse warehouse, EpConnection connection) { if (value == null) @@ -775,7 +775,7 @@ public static class DataSerializer // DC.Combine(kt, 0, (uint)kt.Length, vt, 0, (uint)vt.Length)); } - public static byte[] DynamicArrayComposer(IEnumerable value, Warehouse warehouse, DistributedConnection connection) + public static byte[] DynamicArrayComposer(IEnumerable value, Warehouse warehouse, EpConnection connection) { if (value == null) return null; @@ -806,7 +806,7 @@ public static class DataSerializer return rt.ToArray(); } - public static TDU ResourceListComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU ResourceListComposer(object value, Warehouse warehouse, EpConnection connection) { if (value == null) return new TDU(TDUIdentifier.Null, new byte[0], 0); @@ -817,7 +817,7 @@ public static class DataSerializer (uint)composed.Length); } - public static TDU RecordListComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU RecordListComposer(object value, Warehouse warehouse, EpConnection connection) { if (value == null) return new TDU(TDUIdentifier.Null, new byte[0], 0); @@ -829,7 +829,7 @@ public static class DataSerializer } - public static unsafe TDU ResourceComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU ResourceComposer(object value, Warehouse warehouse, EpConnection connection) { var resource = (IResource)value; @@ -840,7 +840,7 @@ public static class DataSerializer if (Codec.IsLocalResource(resource, connection)) { - var rid = (resource as DistributedResource).DistributedResourceInstanceId; + var rid = (resource as EpResource).DistributedResourceInstanceId; if (rid <= 0xFF) return new TDU(TDUIdentifier.LocalResource8, new byte[] { (byte)rid }, 1); @@ -863,7 +863,6 @@ public static class DataSerializer else { - //rt.Append((value as IResource).Instance.Template.ClassId, (value as IResource).Instance.Id); connection.cache.Add(value as IResource, DateTime.UtcNow); var rid = resource.Instance.Id; @@ -888,7 +887,7 @@ public static class DataSerializer } } - public static unsafe TDU MapComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU MapComposer(object value, Warehouse warehouse, EpConnection connection) { if (value == null) return new TDU(TDUIdentifier.Null, new byte[0], 1); @@ -902,21 +901,21 @@ public static class DataSerializer return new TDU(TDUIdentifier.Map, rt.ToArray(), (uint)rt.Count); } - public static unsafe TDU UUIDComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU UUIDComposer(object value, Warehouse warehouse, EpConnection connection) { return new TDU(TDUIdentifier.UUID, ((UUID)value).Data, 16); } - public static unsafe TDU RecordComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static unsafe TDU RecordComposer(object value, Warehouse warehouse, EpConnection connection) { var rt = new List(); var record = (IRecord)value; - var template = warehouse.GetTemplateByType(record.GetType()); + var typeDef = warehouse.GetTypeDefByType(record.GetType()); - foreach (var pt in template.Properties) + foreach (var pt in typeDef.Properties) { var propValue = pt.PropertyInfo.GetValue(record, null); @@ -940,11 +939,11 @@ public static class DataSerializer return new TDU(TDUIdentifier.Record, rt.ToArray(), (uint)rt.Count, - template.ClassId.Data); + typeDef.Id.Data); } - public static byte[] HistoryComposer(KeyList history, Warehouse warehouse, - DistributedConnection connection, bool prependLength = false) + public static byte[] HistoryComposer(KeyList history, Warehouse warehouse, + EpConnection connection, bool prependLength = false) { //@TODO:Test var rt = new BinaryList(); @@ -959,7 +958,7 @@ public static class DataSerializer return rt.ToArray(); } - public static TDU TupleComposer(object value, Warehouse warehouse, DistributedConnection connection) + public static TDU TupleComposer(object value, Warehouse warehouse, EpConnection connection) { if (value == null) return new TDU(TDUIdentifier.Null, new byte[0], 0); diff --git a/Esiur/Data/Map.cs b/Esiur/Data/Map.cs index f9d6dfe..cccb312 100644 --- a/Esiur/Data/Map.cs +++ b/Esiur/Data/Map.cs @@ -25,7 +25,6 @@ SOFTWARE. using Esiur.Core; using Esiur.Data; using Esiur.Misc; -using Esiur.Net.IIP; using System; using System.Collections; using System.Collections.Generic; diff --git a/Esiur/Data/ResourceJsonConverter.cs b/Esiur/Data/ResourceJsonConverter.cs index 9dc601b..d2fa855 100644 --- a/Esiur/Data/ResourceJsonConverter.cs +++ b/Esiur/Data/ResourceJsonConverter.cs @@ -23,7 +23,6 @@ SOFTWARE. */ -using Esiur.Net.IIP; using Esiur.Resource; using System; using System.Collections.Generic; @@ -52,7 +51,7 @@ class ResourceJsonConverter : JsonConverter writer.WriteStartObject(); - foreach (var pt in resource.Instance.Schema.Properties) + foreach (var pt in resource.Instance.Definition.Properties) { var rt = pt.PropertyInfo.GetValue(resource, null); if (rt != null && rt.GetType().IsGenericType) diff --git a/Esiur/Data/RuntimeCaster.cs b/Esiur/Data/RuntimeCaster.cs index 084aa72..608ecfe 100644 --- a/Esiur/Data/RuntimeCaster.cs +++ b/Esiur/Data/RuntimeCaster.cs @@ -458,7 +458,7 @@ public static class RuntimeCaster [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsListType(Type t) { - return t.IsGenericType && t.GetGenericTypeDef() == typeof(List<>); + return t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>); } [MethodImpl(MethodImplOptions.AggressiveInlining)] diff --git a/Esiur/Data/TDU.cs b/Esiur/Data/TDU.cs index a4a8059..abc0e3a 100644 --- a/Esiur/Data/TDU.cs +++ b/Esiur/Data/TDU.cs @@ -1,5 +1,4 @@ -using Esiur.Net.IIP; -using System; +using System; using System.Collections.Generic; using System.Text; using System.Xml.Linq; diff --git a/Esiur/Data/TRU.cs b/Esiur/Data/TRU.cs index 7629976..c932193 100644 --- a/Esiur/Data/TRU.cs +++ b/Esiur/Data/TRU.cs @@ -1,6 +1,5 @@ using Esiur.Core; using Esiur.Data.Types; -using Esiur.Net.IIP; using Esiur.Resource; using Microsoft.CodeAnalysis; using System; diff --git a/Esiur/Data/Types/ConstantDef.cs b/Esiur/Data/Types/ConstantDef.cs index 3c06e0a..44f05ef 100644 --- a/Esiur/Data/Types/ConstantDef.cs +++ b/Esiur/Data/Types/ConstantDef.cs @@ -107,7 +107,7 @@ public class ConstantDef : MemberDef var value = ci.GetValue(null); - if (typeDef?.Type == TypeDefKind.Enum) + if (typeDef?.Kind == TypeDefKind.Enum) value = Convert.ChangeType(value, ci.FieldType.GetEnumUnderlyingType()); Map annotations = null; diff --git a/Esiur/Data/Types/FunctionDef.cs b/Esiur/Data/Types/FunctionDef.cs index 1bd2c90..94145e1 100644 --- a/Esiur/Data/Types/FunctionDef.cs +++ b/Esiur/Data/Types/FunctionDef.cs @@ -1,6 +1,6 @@ using Esiur.Core; using Esiur.Data; -using Esiur.Net.IIP; +using Esiur.Protocol; using Esiur.Resource; using System; using System.Collections.Generic; @@ -217,7 +217,7 @@ public class FunctionDef : MemberDef if (args.Length > 0) { - if (args.Last().ParameterType == typeof(DistributedConnection) + if (args.Last().ParameterType == typeof(EpConnection) || args.Last().ParameterType == typeof(InvocationContext)) args = args.Take(args.Count() - 1).ToArray(); } @@ -286,7 +286,7 @@ public class FunctionDef : MemberDef { annotations = new Map(); annotations.Add("", "(" + String.Join(",", - mi.GetParameters().Where(x => x.ParameterType != typeof(DistributedConnection)) + mi.GetParameters().Where(x => x.ParameterType != typeof(EpConnection)) .Select(x => "[" + x.ParameterType.Name + "] " + x.Name)) + ") -> " + mi.ReturnType.Name); } @@ -307,7 +307,7 @@ public class FunctionDef : MemberDef public override string ToString() { - //return = "(" + String.Join(",", mi.GetParameters().Where(x => x.ParameterType != typeof(DistributedConnection)).Select(x => "[" + x.ParameterType.Name + "] " + x.Name)) + ") -> " + mi.ReturnType.Name; + //return = "(" + String.Join(",", mi.GetParameters().Where(x => x.ParameterType != typeof(EpConnection)).Select(x => "[" + x.ParameterType.Name + "] " + x.Name)) + ") -> " + mi.ReturnType.Name; return $"{ReturnType} {Name}({string.Join(", ", Arguments.Select(a => a.ToString()))})"; } diff --git a/Esiur/Data/Types/MemberDef.cs b/Esiur/Data/Types/MemberDef.cs index 1f4d1f0..99bd8eb 100644 --- a/Esiur/Data/Types/MemberDef.cs +++ b/Esiur/Data/Types/MemberDef.cs @@ -22,7 +22,7 @@ public class MemberDef // Inherited = inherited; //} - public string Fullname => Definition.ClassName + "." + Name; + public string Fullname => Definition.Name + "." + Name; //public virtual byte[] Compose() //{ diff --git a/Esiur/Data/Types/PropertyDef.cs b/Esiur/Data/Types/PropertyDef.cs index 7f210f9..2a3dd0f 100644 --- a/Esiur/Data/Types/PropertyDef.cs +++ b/Esiur/Data/Types/PropertyDef.cs @@ -1,5 +1,5 @@ using Esiur.Data; -using Esiur.Net.IIP; +using Esiur.Protocol; using Esiur.Resource; using System; using System.Collections.Generic; @@ -34,7 +34,7 @@ public class PropertyDef : MemberDef } */ //bool ReadOnly; - //IIPTypes::DataType ReturnType; + //EPTypes::DataType ReturnType; public PropertyPermission Permission { get; @@ -43,7 +43,7 @@ public class PropertyDef : MemberDef //public bool IsNullable { get; set; } - public bool Recordable + public bool HasHistory { get; set; @@ -87,7 +87,7 @@ public class PropertyDef : MemberDef var hasAnnotation = ((data[offset] & 0x8) == 0x8); - var recordable = ((data[offset] & 1) == 1); + var hasHistory = ((data[offset] & 1) == 1); var permission = (PropertyPermission)((data[offset++] >> 1) & 0x3); var name = data.GetString(offset + 1, data[offset]); @@ -116,7 +116,7 @@ public class PropertyDef : MemberDef Name = name, Inherited = inherited, Permission = permission, - Recordable = recordable, + HasHistory = hasHistory, ValueType = valueType, Annotations = annotations }); @@ -127,7 +127,7 @@ public class PropertyDef : MemberDef { var name = DC.ToBytes(Name); - var pv = ((byte)(Permission) << 1) | (Recordable ? 1 : 0); + var pv = ((byte)(Permission) << 1) | (HasHistory ? 1 : 0); if (Inherited) pv |= 0x80; @@ -193,17 +193,7 @@ public class PropertyDef : MemberDef } } - //public PropertyTemplate(TypeSchema template, byte index, string name, bool inherited, - // TRU valueType, string readAnnotation = null, string writeAnnotation = null, bool recordable = false) - // : base(template, index, name, inherited) - //{ - // this.Recordable = recordable; - // //this.Storage = storage; - // if (readAnnotation != null) - // this.ReadAnnotation = readAnnotation; - // this.WriteAnnotation = writeAnnotation; - // this.ValueType = valueType; - //} + public static PropertyDef MakePropertyDef(Type type, PropertyInfo pi, string name, byte index, PropertyPermission permission, TypeDef schema) { @@ -273,24 +263,12 @@ public class PropertyDef : MemberDef Inherited = pi.DeclaringType != type, ValueType = propType, PropertyInfo = pi, - Recordable = storageAttr == null ? false : storageAttr.Mode == StorageMode.Recordable, + HasHistory = storageAttr == null ? false : storageAttr.Mode == StorageMode.History, Permission = permission, Annotations = annotations, }; - //var pt = new PropertyTemplate(TypeSchema, index, customName ?? pi.Name, pi.DeclaringType != type, propType); - - //if (storageAttr != null) - // pt.Recordable = storageAttr.Mode == StorageMode.Recordable; - - //if (annotationAttr != null) - // pt.ReadAnnotation = annotationAttr.Annotation; - //else - // pt.ReadAnnotation = GetTypeAnnotationName(pi.PropertyType); - - //pt.PropertyInfo = pi; - - //return pt; + } diff --git a/Esiur/Data/Types/TypeDef.cs b/Esiur/Data/Types/TypeDef.cs index 63c2ab9..c72ca22 100644 --- a/Esiur/Data/Types/TypeDef.cs +++ b/Esiur/Data/Types/TypeDef.cs @@ -8,9 +8,9 @@ using Esiur.Data; using Esiur.Core; using System.Security.Cryptography; using Esiur.Proxy; -using Esiur.Net.IIP; using System.Runtime.CompilerServices; using Esiur.Resource; +using Esiur.Protocol; namespace Esiur.Data.Types; @@ -245,7 +245,7 @@ public class TypeDef // Get parents while (parentType != null) { - var parentTemplate = warehouse.GetTemplateByType(parentType); + var parentTemplate = warehouse.GetTypeDefByType(parentType); if (parentTemplate != null) { list.Add(parentTemplate); @@ -262,7 +262,7 @@ public class TypeDef foreach (var functionReturnType in functionReturnTypes) { - var functionReturnTemplate = warehouse.GetTemplateByType(functionReturnType); + var functionReturnTemplate = warehouse.GetTypeDefByType(functionReturnType); if (functionReturnTemplate != null) { if (!bag.Contains(functionReturnTemplate)) @@ -281,7 +281,7 @@ public class TypeDef foreach (var fpType in fpTypes) { - var fpt = warehouse.GetTemplateByType(fpType); + var fpt = warehouse.GetTypeDefByType(fpType); if (fpt != null) { if (!bag.Contains(fpt)) @@ -293,18 +293,18 @@ public class TypeDef } } - // skip DistributedConnection argument + // skip EpConnection argument if (args.Length > 0) { var last = args.Last(); - if (last.ParameterType != typeof(DistributedConnection)) + if (last.ParameterType != typeof(EpConnection)) { var fpTypes = GetDistributedTypes(last.ParameterType); foreach (var fpType in fpTypes) { - var fpt = warehouse.GetTemplateByType(fpType); + var fpt = warehouse.GetTypeDefByType(fpType); if (fpt != null) { if (!bag.Contains(fpt)) @@ -326,7 +326,7 @@ public class TypeDef foreach (var propertyType in propertyTypes) { - var propertyTemplate = warehouse.GetTemplateByType(propertyType); + var propertyTemplate = warehouse.GetTypeDefByType(propertyType); if (propertyTemplate != null) { if (!bag.Contains(propertyTemplate)) @@ -345,7 +345,7 @@ public class TypeDef foreach (var eventType in eventTypes) { - var eventTemplate = warehouse.GetTemplateByType(eventType); + var eventTemplate = warehouse.GetTypeDefByType(eventType); if (eventTemplate != null) { @@ -398,7 +398,7 @@ public class TypeDef else throw new Exception("Type must implement IResource, IRecord or inherit from DistributedResource."); - IsWrapper = Codec.InheritsClass(type, typeof(DistributedResource)); + IsWrapper = Codec.InheritsClass(type, typeof(EpResource)); type = ResourceProxy.GetBaseType(type); @@ -410,7 +410,7 @@ public class TypeDef typeId = GetTypeUUID(type); if (warehouse != null) - warehouse.RegisterSchema(this); + warehouse.RegisterTypeDef(this); var hierarchy = GetHierarchy(type); @@ -729,6 +729,7 @@ public class TypeDef byte functionIndex = 0; byte propertyIndex = 0; byte eventIndex = 0; + byte constantIndex = 0; for (int i = 0; i < methodsCount; i++) { @@ -750,14 +751,14 @@ public class TypeDef } else if (type == 2) // Event { - var (len, et) = EventDef.Parse(data, offset, propertyIndex++, inherited); + var (len, et) = EventDef.Parse(data, offset, eventIndex++, inherited); offset += len; od.events.Add(et); } // constant else if (type == 3) { - var (len, ct) = ConstantDef.Parse(data, offset, propertyIndex++, inherited); + var (len, ct) = ConstantDef.Parse(data, offset, constantIndex++, inherited); offset += len; od.constants.Add(ct); } diff --git a/Esiur/Net/HTTP/IIPoHTTP.cs b/Esiur/Net/Http/EPoHTTP.cs similarity index 73% rename from Esiur/Net/HTTP/IIPoHTTP.cs rename to Esiur/Net/Http/EPoHTTP.cs index 00d64f1..9e84986 100644 --- a/Esiur/Net/HTTP/IIPoHTTP.cs +++ b/Esiur/Net/Http/EPoHTTP.cs @@ -1,25 +1,25 @@ using Esiur.Core; -using Esiur.Net.IIP; using Esiur.Net.Packets; +using Esiur.Protocol; using Esiur.Resource; using System; using System.Collections.Generic; using System.Text; namespace Esiur.Net.HTTP; -public class IIPoHTTP : HTTPFilter +public class EPoHTTP : HTTPFilter { [Attribute] EntryPoint EntryPoint { get; set; } public override AsyncReply Execute(HTTPConnection sender) { - if (sender.Request.URL != "iip") + if (sender.Request.URL != "EP") return new AsyncReply(false); - IIPPacketRequest action = (IIPPacketRequest)Convert.ToByte(sender.Request.Query["a"]); + EpPacketRequest action = (EpPacketRequest)Convert.ToByte(sender.Request.Query["a"]); - if (action == IIPPacketRequest.Query) + if (action == EpPacketRequest.Query) { EntryPoint.Query(sender.Request.Query["l"], null).Then(x => { diff --git a/Esiur/Net/HTTP/IIPoWS.cs b/Esiur/Net/Http/EPoWS.cs similarity index 89% rename from Esiur/Net/HTTP/IIPoWS.cs rename to Esiur/Net/Http/EPoWS.cs index 3ddd5fd..2da2cbd 100644 --- a/Esiur/Net/HTTP/IIPoWS.cs +++ b/Esiur/Net/Http/EPoWS.cs @@ -28,15 +28,15 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Esiur.Resource; -using Esiur.Net.IIP; using Esiur.Net.Sockets; using Esiur.Core; +using Esiur.Protocol; namespace Esiur.Net.HTTP; -public class IIPoWS : HTTPFilter +public class EPoWS : HTTPFilter { [Attribute] - public DistributedServer Server + public EpServer Server { get; set; @@ -59,10 +59,10 @@ public class IIPoWS : HTTPFilter var wsSocket = new WSocket(tcpSocket); httpServer.Remove(sender); - var iipConnection = new DistributedConnection(); + var EPConnection = new EpConnection(); - Server.Add(iipConnection); - iipConnection.Assign(wsSocket); + Server.Add(EPConnection); + EPConnection.Assign(wsSocket); wsSocket.Begin(); return new AsyncReply(true); diff --git a/Esiur/Net/IIP/DistributedConnectionConfig.cs b/Esiur/Net/IIP/DistributedConnectionConfig.cs deleted file mode 100644 index ba96a85..0000000 --- a/Esiur/Net/IIP/DistributedConnectionConfig.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Esiur.Core; -using Esiur.Data; -using Esiur.Net.Packets; -using Esiur.Security.Membership; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Esiur.Net.IIP -{ - public class DistributedConnectionConfig - { - public ExceptionLevel ExceptionLevel { get; set; } - = ExceptionLevel.Code | ExceptionLevel.Message | ExceptionLevel.Source | ExceptionLevel.Trace; - - public Func> Authenticator { get; set; } - - public bool AutoReconnect { get; set; } = false; - - public uint ReconnectInterval { get; set; } = 5; - - public string Username { get; set; } - - public bool UseWebSocket { get; set; } - - public bool SecureWebSocket { get; set; } - - public string Password { get; set; } - - public string Token { get; set; } - - public ulong TokenIndex { get; set; } - - public string Domain { get; set; } - } -} diff --git a/Esiur/Net/IIP/DistributedResourceAttachRequestInfo.cs b/Esiur/Net/IIP/DistributedResourceAttachRequestInfo.cs deleted file mode 100644 index 164efb9..0000000 --- a/Esiur/Net/IIP/DistributedResourceAttachRequestInfo.cs +++ /dev/null @@ -1,20 +0,0 @@ -using Esiur.Core; -using Esiur.Resource; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Esiur.Net.IIP -{ - internal class DistributedResourceAttachRequestInfo - { - public AsyncReply Reply { get; set; } - public uint[] RequestSequence { get; set; } - - public DistributedResourceAttachRequestInfo(AsyncReply reply, uint[] requestSequence) - { - Reply = reply; - RequestSequence = requestSequence; - } - } -} diff --git a/Esiur/Net/IIP/PropertyContext.cs b/Esiur/Net/IIP/PropertyContext.cs deleted file mode 100644 index 5532ea0..0000000 --- a/Esiur/Net/IIP/PropertyContext.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Esiur.Net.IIP; - -public interface IPropertyContext -{ - object GetValue(DistributedConnection connection); -} - -public class PropertyContext : IPropertyContext -{ - public T Value { get; private set; } - public DistributedConnection Connection { get; private set; } - public Func Method { get; private set; } - - public PropertyContext(DistributedConnection connection, T value) - { - this.Value = value; - this.Connection = connection; - } - - public PropertyContext(Func method) - { - this.Method = method; - } - - public static implicit operator PropertyContext(Func method) - => new PropertyContext(method); - - public object GetValue(DistributedConnection connection) - { - return Method.Invoke(connection); - } -} diff --git a/Esiur/Net/Packets/IIPAuthExtensions.cs b/Esiur/Net/Packets/EpAuthExtensions.cs similarity index 62% rename from Esiur/Net/Packets/IIPAuthExtensions.cs rename to Esiur/Net/Packets/EpAuthExtensions.cs index 9bd4c23..af9852a 100644 --- a/Esiur/Net/Packets/IIPAuthExtensions.cs +++ b/Esiur/Net/Packets/EpAuthExtensions.cs @@ -4,19 +4,19 @@ using System.Text; namespace Esiur.Net.Packets { - public static class IIPAuthExtensions + public static class EpAuthExtensions { - public static IIPAuthPacketIAuthFormat GetIAuthFormat(this object value) + public static EpAuthPacketIAuthFormat GetIAuthFormat(this object value) { if (value is string) - return IIPAuthPacketIAuthFormat.Text; + return EpAuthPacketIAuthFormat.Text; else if (value is int || value is uint || value is byte || value is sbyte || value is short || value is ushort || value is long || value is ulong) - return IIPAuthPacketIAuthFormat.Number; + return EpAuthPacketIAuthFormat.Number; else if (value.GetType().IsArray) - return IIPAuthPacketIAuthFormat.Choice; + return EpAuthPacketIAuthFormat.Choice; throw new Exception("Unknown IAuth format"); } diff --git a/Esiur/Net/Packets/IIPAuthPacket.cs b/Esiur/Net/Packets/EpAuthPacket.cs similarity index 77% rename from Esiur/Net/Packets/IIPAuthPacket.cs rename to Esiur/Net/Packets/EpAuthPacket.cs index 506f1c8..5a84e55 100644 --- a/Esiur/Net/Packets/IIPAuthPacket.cs +++ b/Esiur/Net/Packets/EpAuthPacket.cs @@ -35,33 +35,33 @@ using System.Timers; namespace Esiur.Net.Packets; -public class IIPAuthPacket : Packet +public class EpAuthPacket : Packet { - public IIPAuthPacketCommand Command + public EpAuthPacketCommand Command { get; set; } - public IIPAuthPacketInitialize Initialization + public EpAuthPacketInitialize Initialization { get; set; } - public IIPAuthPacketAcknowledge Acknowledgement + public EpAuthPacketAcknowledge Acknowledgement { get; set; } - public IIPAuthPacketAction Action + public EpAuthPacketAction Action { get; set; } - public IIPAuthPacketEvent Event + public EpAuthPacketEvent Event { get; set; @@ -92,13 +92,13 @@ public class IIPAuthPacket : Packet } - public IIPAuthPacketPublicKeyAlgorithm PublicKeyAlgorithm + public EpAuthPacketPublicKeyAlgorithm PublicKeyAlgorithm { get; set; } - public IIPAuthPacketHashAlgorithm HashAlgorithm + public EpAuthPacketHashAlgorithm HashAlgorithm { get; set; @@ -176,14 +176,14 @@ public class IIPAuthPacket : Packet if (NotEnough(offset, ends, 1)) return -dataLengthNeeded; - Command = (IIPAuthPacketCommand)(data[offset] >> 6); + Command = (EpAuthPacketCommand)(data[offset] >> 6); - if (Command == IIPAuthPacketCommand.Initialize) + if (Command == EpAuthPacketCommand.Initialize) { LocalMethod = (AuthenticationMethod)(data[offset] >> 4 & 0x3); RemoteMethod = (AuthenticationMethod)(data[offset] >> 2 & 0x3); - Initialization = (IIPAuthPacketInitialize)(data[offset++] & 0xFC); // remove last two reserved LSBs + Initialization = (EpAuthPacketInitialize)(data[offset++] & 0xFC); // remove last two reserved LSBs if (NotEnough(offset, ends, 1)) return -dataLengthNeeded; @@ -197,13 +197,13 @@ public class IIPAuthPacket : Packet offset += (uint)DataType.Value.TotalLength; } - else if (Command == IIPAuthPacketCommand.Acknowledge) + else if (Command == EpAuthPacketCommand.Acknowledge) { LocalMethod = (AuthenticationMethod)(data[offset] >> 4 & 0x3); RemoteMethod = (AuthenticationMethod)(data[offset] >> 2 & 0x3); - Acknowledgement = (IIPAuthPacketAcknowledge)(data[offset++] & 0xFC); // remove last two reserved LSBs + Acknowledgement = (EpAuthPacketAcknowledge)(data[offset++] & 0xFC); // remove last two reserved LSBs if (NotEnough(offset, ends, 1)) return -dataLengthNeeded; @@ -216,19 +216,19 @@ public class IIPAuthPacket : Packet offset += (uint)DataType.Value.TotalLength; } - else if (Command == IIPAuthPacketCommand.Action) + else if (Command == EpAuthPacketCommand.Action) { - Action = (IIPAuthPacketAction)data[offset++]; // (IIPAuthPacketAction)(data[offset++] & 0x3f); + Action = (EpAuthPacketAction)data[offset++]; // (EPAuthPacketAction)(data[offset++] & 0x3f); - if (Action == IIPAuthPacketAction.AuthenticateHash - || Action == IIPAuthPacketAction.AuthenticatePublicHash - || Action == IIPAuthPacketAction.AuthenticatePrivateHash - || Action == IIPAuthPacketAction.AuthenticatePublicPrivateHash) + if (Action == EpAuthPacketAction.AuthenticateHash + || Action == EpAuthPacketAction.AuthenticatePublicHash + || Action == EpAuthPacketAction.AuthenticatePrivateHash + || Action == EpAuthPacketAction.AuthenticatePublicPrivateHash) { if (NotEnough(offset, ends, 3)) return -dataLengthNeeded; - HashAlgorithm = (IIPAuthPacketHashAlgorithm)data[offset++]; + HashAlgorithm = (EpAuthPacketHashAlgorithm)data[offset++]; var hashLength = data.GetUInt16(offset, Endian.Little); offset += 2; @@ -241,13 +241,13 @@ public class IIPAuthPacket : Packet offset += hashLength; } - else if (Action == IIPAuthPacketAction.AuthenticatePrivateHashCert - || Action == IIPAuthPacketAction.AuthenticatePublicPrivateHashCert) + else if (Action == EpAuthPacketAction.AuthenticatePrivateHashCert + || Action == EpAuthPacketAction.AuthenticatePublicPrivateHashCert) { if (NotEnough(offset, ends, 3)) return -dataLengthNeeded; - HashAlgorithm = (IIPAuthPacketHashAlgorithm)data[offset++]; + HashAlgorithm = (EpAuthPacketHashAlgorithm)data[offset++]; var hashLength = data.GetUInt16(offset, Endian.Little); offset += 2; @@ -272,7 +272,7 @@ public class IIPAuthPacket : Packet offset += certLength; } - else if (Action == IIPAuthPacketAction.IAuthPlain) + else if (Action == EpAuthPacketAction.IAuthPlain) { if (NotEnough(offset, ends, 5)) return -dataLengthNeeded; @@ -288,7 +288,7 @@ public class IIPAuthPacket : Packet offset += (uint)DataType.Value.TotalLength; } - else if (Action == IIPAuthPacketAction.IAuthHashed) + else if (Action == EpAuthPacketAction.IAuthHashed) { if (NotEnough(offset, ends, 7)) return -dataLengthNeeded; @@ -296,7 +296,7 @@ public class IIPAuthPacket : Packet Reference = data.GetUInt32(offset, Endian.Little); offset += 4; - HashAlgorithm = (IIPAuthPacketHashAlgorithm)data[offset++]; + HashAlgorithm = (EpAuthPacketHashAlgorithm)data[offset++]; var cl = data.GetUInt16(offset, Endian.Little); offset += 2; @@ -309,7 +309,7 @@ public class IIPAuthPacket : Packet offset += cl; } - else if (Action == IIPAuthPacketAction.IAuthEncrypted) + else if (Action == EpAuthPacketAction.IAuthEncrypted) { if (NotEnough(offset, ends, 7)) return -dataLengthNeeded; @@ -317,7 +317,7 @@ public class IIPAuthPacket : Packet Reference = data.GetUInt32(offset, Endian.Little); offset += 4; - PublicKeyAlgorithm = (IIPAuthPacketPublicKeyAlgorithm)data[offset++]; + PublicKeyAlgorithm = (EpAuthPacketPublicKeyAlgorithm)data[offset++]; var cl = data.GetUInt16(offset, Endian.Little); offset += 2; @@ -330,11 +330,11 @@ public class IIPAuthPacket : Packet offset += cl; } - else if (Action == IIPAuthPacketAction.EstablishNewSession) + else if (Action == EpAuthPacketAction.EstablishNewSession) { // Nothing here } - else if (Action == IIPAuthPacketAction.EstablishResumeSession) + else if (Action == EpAuthPacketAction.EstablishResumeSession) { if (NotEnough(offset, ends, 1)) return -dataLengthNeeded; @@ -349,7 +349,7 @@ public class IIPAuthPacket : Packet offset += sessionLength; } - else if (Action == IIPAuthPacketAction.EncryptKeyExchange) + else if (Action == EpAuthPacketAction.EncryptKeyExchange) { if (NotEnough(offset, ends, 2)) return -dataLengthNeeded; @@ -366,13 +366,13 @@ public class IIPAuthPacket : Packet offset += keyLength; } - else if (Action == IIPAuthPacketAction.RegisterEndToEndKey - || Action == IIPAuthPacketAction.RegisterHomomorphic) + else if (Action == EpAuthPacketAction.RegisterEndToEndKey + || Action == EpAuthPacketAction.RegisterHomomorphic) { if (NotEnough(offset, ends, 3)) return -dataLengthNeeded; - PublicKeyAlgorithm = (IIPAuthPacketPublicKeyAlgorithm)data[offset++]; + PublicKeyAlgorithm = (EpAuthPacketPublicKeyAlgorithm)data[offset++]; var keyLength = data.GetUInt16(offset, Endian.Little); @@ -387,14 +387,14 @@ public class IIPAuthPacket : Packet } } - else if (Command == IIPAuthPacketCommand.Event) + else if (Command == EpAuthPacketCommand.Event) { - Event = (IIPAuthPacketEvent)data[offset++]; + Event = (EpAuthPacketEvent)data[offset++]; - if (Event == IIPAuthPacketEvent.ErrorTerminate - || Event == IIPAuthPacketEvent.ErrorMustEncrypt - || Event == IIPAuthPacketEvent.ErrorRetry) + if (Event == EpAuthPacketEvent.ErrorTerminate + || Event == EpAuthPacketEvent.ErrorMustEncrypt + || Event == EpAuthPacketEvent.ErrorRetry) { if (NotEnough(offset, ends, 3)) return -dataLengthNeeded; @@ -411,7 +411,7 @@ public class IIPAuthPacket : Packet offset += msgLength; } - else if (Event == IIPAuthPacketEvent.IndicationEstablished) + else if (Event == EpAuthPacketEvent.IndicationEstablished) { if (NotEnough(offset, ends, 2)) return -dataLengthNeeded; @@ -438,9 +438,9 @@ public class IIPAuthPacket : Packet offset += accountLength; } - else if (Event == IIPAuthPacketEvent.IAuthPlain - || Event == IIPAuthPacketEvent.IAuthHashed - || Event == IIPAuthPacketEvent.IAuthEncrypted) + else if (Event == EpAuthPacketEvent.IAuthPlain + || Event == EpAuthPacketEvent.IAuthHashed + || Event == EpAuthPacketEvent.IAuthEncrypted) { if (NotEnough(offset, ends, 1)) return -dataLengthNeeded; diff --git a/Esiur/Net/Packets/IIPAuthPacketAcknowledge.cs b/Esiur/Net/Packets/EpAuthPacketAcknowledge.cs similarity index 94% rename from Esiur/Net/Packets/IIPAuthPacketAcknowledge.cs rename to Esiur/Net/Packets/EpAuthPacketAcknowledge.cs index 1feec89..7fc2f3b 100644 --- a/Esiur/Net/Packets/IIPAuthPacketAcknowledge.cs +++ b/Esiur/Net/Packets/EpAuthPacketAcknowledge.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPAuthPacketAcknowledge : byte + public enum EpAuthPacketAcknowledge : byte { NoAuthNoAuth = 0x40, // 0b01000000, NoAuthCredentials = 0x44, // 0b01000100, diff --git a/Esiur/Net/Packets/IIPAuthPacketAction.cs b/Esiur/Net/Packets/EpAuthPacketAction.cs similarity index 93% rename from Esiur/Net/Packets/IIPAuthPacketAction.cs rename to Esiur/Net/Packets/EpAuthPacketAction.cs index f4a581d..a2da57f 100644 --- a/Esiur/Net/Packets/IIPAuthPacketAction.cs +++ b/Esiur/Net/Packets/EpAuthPacketAction.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPAuthPacketAction : byte + public enum EpAuthPacketAction : byte { AuthenticateHash = 0x80, AuthenticatePublicHash = 0x81, diff --git a/Esiur/Net/Packets/IIPAuthPacketCommand.cs b/Esiur/Net/Packets/EpAuthPacketCommand.cs similarity index 82% rename from Esiur/Net/Packets/IIPAuthPacketCommand.cs rename to Esiur/Net/Packets/EpAuthPacketCommand.cs index 6d810f9..7cf7796 100644 --- a/Esiur/Net/Packets/IIPAuthPacketCommand.cs +++ b/Esiur/Net/Packets/EpAuthPacketCommand.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPAuthPacketCommand : byte + public enum EpAuthPacketCommand : byte { Initialize = 0x0, Acknowledge = 0x1, diff --git a/Esiur/Net/Packets/IIPAuthPacketEvent.cs b/Esiur/Net/Packets/EpAuthPacketEvent.cs similarity index 88% rename from Esiur/Net/Packets/IIPAuthPacketEvent.cs rename to Esiur/Net/Packets/EpAuthPacketEvent.cs index 4f3079b..bcd3c29 100644 --- a/Esiur/Net/Packets/IIPAuthPacketEvent.cs +++ b/Esiur/Net/Packets/EpAuthPacketEvent.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPAuthPacketEvent : byte + public enum EpAuthPacketEvent : byte { ErrorTerminate = 0xC0, ErrorMustEncrypt = 0xC1, diff --git a/Esiur/Net/Packets/IIPAuthPacketHashAlgorithm.cs b/Esiur/Net/Packets/EpAuthPacketHashAlgorithm.cs similarity index 77% rename from Esiur/Net/Packets/IIPAuthPacketHashAlgorithm.cs rename to Esiur/Net/Packets/EpAuthPacketHashAlgorithm.cs index 08eb245..044d21d 100644 --- a/Esiur/Net/Packets/IIPAuthPacketHashAlgorithm.cs +++ b/Esiur/Net/Packets/EpAuthPacketHashAlgorithm.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPAuthPacketHashAlgorithm + public enum EpAuthPacketHashAlgorithm { SHA256, SHA3, diff --git a/Esiur/Net/Packets/IIPAuthPacketHeader.cs b/Esiur/Net/Packets/EpAuthPacketHeader.cs similarity index 94% rename from Esiur/Net/Packets/IIPAuthPacketHeader.cs rename to Esiur/Net/Packets/EpAuthPacketHeader.cs index e8e156a..6750c93 100644 --- a/Esiur/Net/Packets/IIPAuthPacketHeader.cs +++ b/Esiur/Net/Packets/EpAuthPacketHeader.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPAuthPacketHeader + public enum EpAuthPacketHeader { Version = 0, Domain = 1, diff --git a/Esiur/Net/Packets/IIPAuthPacketIAuthDestination.cs b/Esiur/Net/Packets/EpAuthPacketIAuthDestination.cs similarity index 86% rename from Esiur/Net/Packets/IIPAuthPacketIAuthDestination.cs rename to Esiur/Net/Packets/EpAuthPacketIAuthDestination.cs index 500abe3..43bc03b 100644 --- a/Esiur/Net/Packets/IIPAuthPacketIAuthDestination.cs +++ b/Esiur/Net/Packets/EpAuthPacketIAuthDestination.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPAuthPacketIAuthDestination + public enum EpAuthPacketIAuthDestination { Self = 0, Device = 1, // logged in device diff --git a/Esiur/Net/Packets/IIPAuthPacketIAuthFormat.cs b/Esiur/Net/Packets/EpAuthPacketIAuthFormat.cs similarity index 87% rename from Esiur/Net/Packets/IIPAuthPacketIAuthFormat.cs rename to Esiur/Net/Packets/EpAuthPacketIAuthFormat.cs index e0746d9..76c0dd6 100644 --- a/Esiur/Net/Packets/IIPAuthPacketIAuthFormat.cs +++ b/Esiur/Net/Packets/EpAuthPacketIAuthFormat.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPAuthPacketIAuthFormat + public enum EpAuthPacketIAuthFormat { None = 0, Number = 1, diff --git a/Esiur/Net/Packets/IIPAuthPacketIAuthHeader.cs b/Esiur/Net/Packets/EpAuthPacketIAuthHeader.cs similarity index 86% rename from Esiur/Net/Packets/IIPAuthPacketIAuthHeader.cs rename to Esiur/Net/Packets/EpAuthPacketIAuthHeader.cs index 76ae9ea..8e9abe6 100644 --- a/Esiur/Net/Packets/IIPAuthPacketIAuthHeader.cs +++ b/Esiur/Net/Packets/EpAuthPacketIAuthHeader.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPAuthPacketIAuthHeader : byte + public enum EpAuthPacketIAuthHeader : byte { Reference = 0, Destination = 1, diff --git a/Esiur/Net/Packets/IIPAuthPacketInitialize.cs b/Esiur/Net/Packets/EpAuthPacketInitialize.cs similarity index 95% rename from Esiur/Net/Packets/IIPAuthPacketInitialize.cs rename to Esiur/Net/Packets/EpAuthPacketInitialize.cs index e09d0ad..93fbce7 100644 --- a/Esiur/Net/Packets/IIPAuthPacketInitialize.cs +++ b/Esiur/Net/Packets/EpAuthPacketInitialize.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPAuthPacketInitialize + public enum EpAuthPacketInitialize { NoAuthNoAuth = 0x0, //0b00000000, NoAuthCredentials = 0x4, //0b00000100, diff --git a/Esiur/Net/Packets/IIPAuthPacketPublicKeyAlgorithm.cs b/Esiur/Net/Packets/EpAuthPacketPublicKeyAlgorithm.cs similarity index 75% rename from Esiur/Net/Packets/IIPAuthPacketPublicKeyAlgorithm.cs rename to Esiur/Net/Packets/EpAuthPacketPublicKeyAlgorithm.cs index 27895b7..6b464fa 100644 --- a/Esiur/Net/Packets/IIPAuthPacketPublicKeyAlgorithm.cs +++ b/Esiur/Net/Packets/EpAuthPacketPublicKeyAlgorithm.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPAuthPacketPublicKeyAlgorithm + public enum EpAuthPacketPublicKeyAlgorithm { RSA = 0, CKKS = 1, diff --git a/Esiur/Net/Packets/IIPPacket.cs b/Esiur/Net/Packets/EpPacket.cs similarity index 76% rename from Esiur/Net/Packets/IIPPacket.cs rename to Esiur/Net/Packets/EpPacket.cs index 80c8381..8a8f2fd 100644 --- a/Esiur/Net/Packets/IIPPacket.cs +++ b/Esiur/Net/Packets/EpPacket.cs @@ -32,15 +32,15 @@ using System.Text; using System.Threading.Tasks; namespace Esiur.Net.Packets; -class IIPPacket : Packet +class EpPacket : Packet { public uint CallbackId { get; set; } - public IIPPacketMethod Method { get; set; } - public IIPPacketRequest Request { get; set; } - public IIPPacketReply Reply { get; set; } + public EpPacketMethod Method { get; set; } + public EpPacketRequest Request { get; set; } + public EpPacketReply Reply { get; set; } - public IIPPacketNotification Notification { get; set; } + public EpPacketNotification Notification { get; set; } public byte Extension { get; set; } @@ -59,10 +59,10 @@ class IIPPacket : Packet { return Method switch { - IIPPacketMethod.Notification => $"{Method} {Notification}", - IIPPacketMethod.Request => $"{Method} {Request}", - IIPPacketMethod.Reply => $"{Method} {Reply}", - IIPPacketMethod.Extension => $"{Method} {Extension}", + EpPacketMethod.Notification => $"{Method} {Notification}", + EpPacketMethod.Request => $"{Method} {Request}", + EpPacketMethod.Reply => $"{Method} {Reply}", + EpPacketMethod.Extension => $"{Method} {Extension}", _ => $"{Method}" }; } @@ -88,15 +88,15 @@ class IIPPacket : Packet var hasDTU = (data[offset] & 0x20) == 0x20; - Method = (IIPPacketMethod)(data[offset] >> 6); + Method = (EpPacketMethod)(data[offset] >> 6); - if (Method == IIPPacketMethod.Notification) + if (Method == EpPacketMethod.Notification) { - Notification = (IIPPacketNotification)(data[offset++] & 0x1f); + Notification = (EpPacketNotification)(data[offset++] & 0x1f); } - else if (Method == IIPPacketMethod.Request) + else if (Method == EpPacketMethod.Request) { - Request = (IIPPacketRequest)(data[offset++] & 0x1f); + Request = (EpPacketRequest)(data[offset++] & 0x1f); if (NotEnough(offset, ends, 4)) return -dataLengthNeeded; @@ -104,9 +104,9 @@ class IIPPacket : Packet CallbackId = data.GetUInt32(offset, Endian.Little); offset += 4; } - else if (Method == IIPPacketMethod.Reply) + else if (Method == EpPacketMethod.Reply) { - Reply = (IIPPacketReply)(data[offset++] & 0x1f); + Reply = (EpPacketReply)(data[offset++] & 0x1f); if (NotEnough(offset, ends, 4)) return -dataLengthNeeded; @@ -114,7 +114,7 @@ class IIPPacket : Packet CallbackId = data.GetUInt32(offset, Endian.Little); offset += 4; } - else if (Method == IIPPacketMethod.Extension) + else if (Method == EpPacketMethod.Extension) { Extension = (byte)(data[offset++] & 0x1f); } diff --git a/Esiur/Net/Packets/IIPPacketAttachInfo.cs b/Esiur/Net/Packets/EpPacketAttachInfo.cs similarity index 74% rename from Esiur/Net/Packets/IIPPacketAttachInfo.cs rename to Esiur/Net/Packets/EpPacketAttachInfo.cs index 2e746e3..0494074 100644 --- a/Esiur/Net/Packets/IIPPacketAttachInfo.cs +++ b/Esiur/Net/Packets/EpPacketAttachInfo.cs @@ -5,14 +5,14 @@ using System.Text; namespace Esiur.Net.Packets; -struct IIPPacketAttachInfo +struct EpPacketAttachInfo { public string Link; public ulong Age; public byte[] Content; public UUID TypeId; - public IIPPacketAttachInfo(UUID typeId, ulong age, string link, byte[] content) + public EpPacketAttachInfo(UUID typeId, ulong age, string link, byte[] content) { TypeId = typeId; Age = age; diff --git a/Esiur/Net/Packets/IIPPacketCommand.cs b/Esiur/Net/Packets/EpPacketCommand.cs similarity index 83% rename from Esiur/Net/Packets/IIPPacketCommand.cs rename to Esiur/Net/Packets/EpPacketCommand.cs index 648a954..5c27dcd 100644 --- a/Esiur/Net/Packets/IIPPacketCommand.cs +++ b/Esiur/Net/Packets/EpPacketCommand.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPPacketMethod : byte + public enum EpPacketMethod : byte { Notification = 0, Request, diff --git a/Esiur/Net/Packets/IIPPacketNotification.cs b/Esiur/Net/Packets/EpPacketNotification.cs similarity index 88% rename from Esiur/Net/Packets/IIPPacketNotification.cs rename to Esiur/Net/Packets/EpPacketNotification.cs index 3e34cdf..8e664db 100644 --- a/Esiur/Net/Packets/IIPPacketNotification.cs +++ b/Esiur/Net/Packets/EpPacketNotification.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPPacketNotification : byte + public enum EpPacketNotification : byte { // Notification Invoke PropertyModified = 0x0, diff --git a/Esiur/Net/Packets/IIPPacketReply.cs b/Esiur/Net/Packets/EpPacketReply.cs similarity index 90% rename from Esiur/Net/Packets/IIPPacketReply.cs rename to Esiur/Net/Packets/EpPacketReply.cs index 7518b61..a3a7d2e 100644 --- a/Esiur/Net/Packets/IIPPacketReply.cs +++ b/Esiur/Net/Packets/EpPacketReply.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPPacketReply : byte + public enum EpPacketReply : byte { // Success Completed = 0x0, diff --git a/Esiur/Net/Packets/IIPPacketReport.cs b/Esiur/Net/Packets/EpPacketReport.cs similarity index 85% rename from Esiur/Net/Packets/IIPPacketReport.cs rename to Esiur/Net/Packets/EpPacketReport.cs index 846fb74..e6d42c0 100644 --- a/Esiur/Net/Packets/IIPPacketReport.cs +++ b/Esiur/Net/Packets/EpPacketReport.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPPacketReport : byte + public enum EpPacketReport : byte { ManagementError, ExecutionError, diff --git a/Esiur/Net/Packets/IIPPacketRequest.cs b/Esiur/Net/Packets/EpPacketRequest.cs similarity index 82% rename from Esiur/Net/Packets/IIPPacketRequest.cs rename to Esiur/Net/Packets/EpPacketRequest.cs index 73336f4..72a0b88 100644 --- a/Esiur/Net/Packets/IIPPacketRequest.cs +++ b/Esiur/Net/Packets/EpPacketRequest.cs @@ -4,7 +4,7 @@ using System.Text; namespace Esiur.Net.Packets { - public enum IIPPacketRequest : byte + public enum EpPacketRequest : byte { // Request Invoke InvokeFunction = 0x0, @@ -13,11 +13,11 @@ namespace Esiur.Net.Packets Unsubscribe = 0x3, // Request Inquire - SchemaFromClassName = 0x8, - SchemaFromClassId = 0x9, - SchemaFromResourceId = 0xA, + TypeDefByName = 0x8, + TypeDefById = 0x9, + TypeDefByResourceId = 0xA, Query = 0xB, - LinkSchemas = 0xC, + LinkTypeDefs = 0xC, Token = 0xD, GetResourceIdByLink = 0xE, diff --git a/Esiur/Net/UDP/UDPServer.cs b/Esiur/Net/UDP/UDPServer.cs index ec48d24..8fb1357 100644 --- a/Esiur/Net/UDP/UDPServer.cs +++ b/Esiur/Net/UDP/UDPServer.cs @@ -35,7 +35,7 @@ using Esiur.Core; namespace Esiur.Net.UDP; -/* public class IIPConnection +/* public class EPConnection { public EndPoint SenderPoint; public diff --git a/Esiur/Net/IIP/EntryPoint.cs b/Esiur/Protocol/EntryPoint.cs similarity index 86% rename from Esiur/Net/IIP/EntryPoint.cs rename to Esiur/Protocol/EntryPoint.cs index 122f546..667e354 100644 --- a/Esiur/Net/IIP/EntryPoint.cs +++ b/Esiur/Protocol/EntryPoint.cs @@ -27,13 +27,12 @@ using System.Text; using Esiur.Core; using Esiur.Data; using Esiur.Resource; -using Esiur.Data.Schema; +using Esiur.Data.Types; + +namespace Esiur.Protocol; -namespace Esiur.Net.IIP; - -public abstract class EntryPoint : Esiur.Resource.Resource +public abstract class EntryPoint : Resource.Resource { - - public abstract AsyncReply Query(string path, DistributedConnection sender); + public abstract AsyncReply Query(string path, EpConnection sender); protected abstract override bool Create(); } diff --git a/Esiur/Net/IIP/DistributedConnection.cs b/Esiur/Protocol/EpConnection.cs similarity index 74% rename from Esiur/Net/IIP/DistributedConnection.cs rename to Esiur/Protocol/EpConnection.cs index d25bf61..3e58eb3 100644 --- a/Esiur/Net/IIP/DistributedConnection.cs +++ b/Esiur/Protocol/EpConnection.cs @@ -24,8 +24,9 @@ SOFTWARE. using Esiur.Core; using Esiur.Data; -using Esiur.Data.Schema; +using Esiur.Data.Types; using Esiur.Misc; +using Esiur.Net; using Esiur.Net.HTTP; using Esiur.Net.Packets; using Esiur.Net.Packets.HTTP; @@ -46,19 +47,20 @@ using System.Text; using System.Threading.Tasks; using System.Timers; -namespace Esiur.Net.IIP; -public partial class DistributedConnection : NetworkConnection, IStore +namespace Esiur.Protocol; + +public partial class EpConnection : NetworkConnection, IStore { - public delegate void ProtocolGeneralHandler(DistributedConnection connection, ParsedTDU dataType, byte[] data); + public delegate void ProtocolGeneralHandler(EpConnection connection, ParsedTDU dataType, byte[] data); - public delegate void ProtocolRequestReplyHandler(DistributedConnection connection, uint callbackId, ParsedTDU dataType, byte[] data); + public delegate void ProtocolRequestReplyHandler(EpConnection connection, uint callbackId, ParsedTDU dataType, byte[] data); // Delegates - public delegate void ReadyEvent(DistributedConnection sender); - public delegate void ErrorEvent(DistributedConnection sender, byte errorCode, string errorMessage); - public delegate void ResumedEvent(DistributedConnection sender); + public delegate void ReadyEvent(EpConnection sender); + public delegate void ErrorEvent(EpConnection sender, byte errorCode, string errorMessage); + public delegate void ResumedEvent(EpConnection sender); // Events @@ -86,8 +88,8 @@ public partial class DistributedConnection : NetworkConnection, IStore DateTime? lastKeepAliveReceived; - IIPPacket packet = new IIPPacket(); - IIPAuthPacket authPacket = new IIPAuthPacket(); + EpPacket packet = new EpPacket(); + EpAuthPacket authPacket = new EpAuthPacket(); Session session; @@ -110,7 +112,7 @@ public partial class DistributedConnection : NetworkConnection, IStore /// /// Distributed server responsible for this connection, usually for incoming connections. /// - public DistributedServer Server { get; internal set; } + public EpServer Server { get; internal set; } /// @@ -119,7 +121,7 @@ public partial class DistributedConnection : NetworkConnection, IStore public Session Session => session; [Export] - public virtual ConnectionStatus Status { get; private set; } + public virtual EpConnectionStatus Status { get; private set; } [Export] public virtual uint Jitter { get; private set; } @@ -190,7 +192,7 @@ public partial class DistributedConnection : NetworkConnection, IStore { //Console.WriteLine("Client: {0}", Data.Length); - Global.Counters["IIP Sent Packets"]++; + Global.Counters["Ep Sent Packets"]++; base.Send(data); } @@ -212,11 +214,11 @@ public partial class DistributedConnection : NetworkConnection, IStore /// Assign a socket to the connection. /// /// Any socket that implements ISocket. - public override void Assign(Sockets.ISocket socket) + public override void Assign(ISocket socket) { base.Assign(socket); - session.LocalHeaders[IIPAuthPacketHeader.IPAddress] = socket.RemoteEndPoint.Address.GetAddressBytes(); + session.LocalHeaders[EpAuthPacketHeader.IPAddress] = socket.RemoteEndPoint.Address.GetAddressBytes(); if (socket.State == SocketState.Established && session.AuthenticationType == AuthenticationType.Client) @@ -232,7 +234,7 @@ public partial class DistributedConnection : NetworkConnection, IStore { // create key var key = session.KeyExchanger.GetPublicKey(); - session.LocalHeaders[IIPAuthPacketHeader.CipherKey] = key; + session.LocalHeaders[EpAuthPacketHeader.CipherKey] = key; } @@ -244,7 +246,7 @@ public partial class DistributedConnection : NetworkConnection, IStore // declare (Credentials -> No Auth, No Enctypt) SendParams() - .AddUInt8((byte)IIPAuthPacketInitialize.CredentialsNoAuth) + .AddUInt8((byte)EpAuthPacketInitialize.CredentialsNoAuth) .AddUInt8Array(headers) .Done(); @@ -256,7 +258,7 @@ public partial class DistributedConnection : NetworkConnection, IStore var headers = Codec.Compose(session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)), this.Instance.Warehouse, this); SendParams() - .AddUInt8((byte)IIPAuthPacketInitialize.TokenNoAuth) + .AddUInt8((byte)EpAuthPacketInitialize.TokenNoAuth) .AddUInt8Array(headers) .Done(); } @@ -268,7 +270,7 @@ public partial class DistributedConnection : NetworkConnection, IStore // @REVIEW: MITM Attack can still occur SendParams() - .AddUInt8((byte)IIPAuthPacketInitialize.NoAuthNoAuth) + .AddUInt8((byte)EpAuthPacketInitialize.NoAuthNoAuth) .AddUInt8Array(headers) .Done(); } @@ -286,13 +288,13 @@ public partial class DistributedConnection : NetworkConnection, IStore /// Working domain. /// Username. /// Password. - public DistributedConnection(Sockets.ISocket socket, string domain, string username, string password) + public EpConnection(ISocket socket, string domain, string username, string password) { this.session = new Session(); session.AuthenticationType = AuthenticationType.Client; - session.LocalHeaders[IIPAuthPacketHeader.Domain] = domain; - session.LocalHeaders[IIPAuthPacketHeader.Username] = username; + session.LocalHeaders[EpAuthPacketHeader.Domain] = domain; + session.LocalHeaders[EpAuthPacketHeader.Username] = username; session.LocalMethod = AuthenticationMethod.Credentials; session.RemoteMethod = AuthenticationMethod.None; @@ -304,14 +306,14 @@ public partial class DistributedConnection : NetworkConnection, IStore Assign(socket); } - public DistributedConnection(Sockets.ISocket socket, string domain, ulong tokenIndex, string token) + public EpConnection(ISocket socket, string domain, ulong tokenIndex, string token) { this.session = new Session(); session.AuthenticationType = AuthenticationType.Client; - session.LocalHeaders[IIPAuthPacketHeader.Domain] = domain; - session.LocalHeaders[IIPAuthPacketHeader.TokenIndex] = tokenIndex; + session.LocalHeaders[EpAuthPacketHeader.Domain] = domain; + session.LocalHeaders[EpAuthPacketHeader.TokenIndex] = tokenIndex; session.LocalMethod = AuthenticationMethod.Credentials; session.RemoteMethod = AuthenticationMethod.None; this.localPasswordOrToken = DC.ToBytes(token); @@ -325,7 +327,7 @@ public partial class DistributedConnection : NetworkConnection, IStore /// /// Create a new instance of a distributed connection /// - public DistributedConnection() + public EpConnection() { session = new Session(); session.AuthenticationType = AuthenticationType.Host; @@ -337,9 +339,9 @@ public partial class DistributedConnection : NetworkConnection, IStore public string Link(IResource resource) { - if (resource is DistributedResource) + if (resource is EpResource) { - var r = resource as DistributedResource; + var r = resource as EpResource; if (r.Instance.Store == this) return this.Instance.Name + "/" + r.DistributedResourceInstanceId; } @@ -348,7 +350,7 @@ public partial class DistributedConnection : NetworkConnection, IStore } - public List> GetFinishedQueue() + public List> GetFinishedQueue() { var l = queue.Processed.ToArray().ToList(); queue.Processed.Clear(); @@ -360,7 +362,7 @@ public partial class DistributedConnection : NetworkConnection, IStore //var q = queue; queue.Then((x) => { - if (x.Type == DistributedResourceQueueItem.DistributedResourceQueueItemType.Event) + if (x.Type == EpResourceQueueItem.DistributedResourceQueueItemType.Event) x.Resource._EmitEventByIndex(x.Index, x.Value); else x.Resource._UpdatePropertyByIndex(x.Index, x.Value); @@ -372,7 +374,7 @@ public partial class DistributedConnection : NetworkConnection, IStore }); // set local nonce - session.LocalHeaders[IIPAuthPacketHeader.Nonce] = Global.GenerateBytes(32); + session.LocalHeaders[EpAuthPacketHeader.Nonce] = Global.GenerateBytes(32); keepAliveTimer = new System.Timers.Timer(KeepAliveInterval * 1000); keepAliveTimer.Elapsed += KeepAliveTimer_Elapsed; ; @@ -393,7 +395,7 @@ public partial class DistributedConnection : NetworkConnection, IStore lastKeepAliveSent = now; - SendRequest(IIPPacketRequest.KeepAlive, now, interval) + SendRequest(EpPacketRequest.KeepAlive, now, interval) .Then(x => { Jitter =Convert.ToUInt32(((object[])x)[1]); @@ -443,7 +445,7 @@ public partial class DistributedConnection : NetworkConnection, IStore //Console.WriteLine("Incoming: " + packet + " " + packet.CallbackId); - if (packet.Method == IIPPacketMethod.Notification) + if (packet.Method == EpPacketMethod.Notification) { var dt = packet.DataType.Value; @@ -451,135 +453,135 @@ public partial class DistributedConnection : NetworkConnection, IStore switch (packet.Notification) { // Invoke - case IIPPacketNotification.PropertyModified: - IIPNotificationPropertyModified(dt); + case EpPacketNotification.PropertyModified: + EpNotificationPropertyModified(dt); break; - case IIPPacketNotification.EventOccurred: - IIPNotificationEventOccurred(dt, msg); + case EpPacketNotification.EventOccurred: + EpNotificationEventOccurred(dt, msg); break; // Manage - case IIPPacketNotification.ResourceDestroyed: - IIPNotificationResourceDestroyed(dt, msg); + case EpPacketNotification.ResourceDestroyed: + EpNotificationResourceDestroyed(dt, msg); break; - case IIPPacketNotification.ResourceReassigned: - IIPNotificationResourceReassigned(dt); + case EpPacketNotification.ResourceReassigned: + EpNotificationResourceReassigned(dt); break; - case IIPPacketNotification.ResourceMoved: - IIPNotificationResourceMoved(dt, msg); + case EpPacketNotification.ResourceMoved: + EpNotificationResourceMoved(dt, msg); break; - case IIPPacketNotification.SystemFailure: - IIPNotificationSystemFailure(dt, msg); + case EpPacketNotification.SystemFailure: + EpNotificationSystemFailure(dt, msg); break; } } - else if (packet.Method == IIPPacketMethod.Request) + else if (packet.Method == EpPacketMethod.Request) { var dt = packet.DataType.Value; switch (packet.Request) { // Invoke - case IIPPacketRequest.InvokeFunction: - IIPRequestInvokeFunction(packet.CallbackId, dt, msg); + case EpPacketRequest.InvokeFunction: + EpRequestInvokeFunction(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.SetProperty: - IIPRequestSetProperty(packet.CallbackId, dt, msg); + case EpPacketRequest.SetProperty: + EpRequestSetProperty(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.Subscribe: - IIPRequestSubscribe(packet.CallbackId, dt, msg); + case EpPacketRequest.Subscribe: + EpRequestSubscribe(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.Unsubscribe: - IIPRequestUnsubscribe(packet.CallbackId, dt, msg); + case EpPacketRequest.Unsubscribe: + EpRequestUnsubscribe(packet.CallbackId, dt, msg); break; // Inquire - case IIPPacketRequest.SchemaFromClassName: - IIPRequestTemplateFromClassName(packet.CallbackId, dt, msg); + case EpPacketRequest.TypeDefByName: + EpRequestTypeDefByName(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.SchemaFromClassId: - IIPRequestTemplateFromClassId(packet.CallbackId, dt, msg); + case EpPacketRequest.TypeDefById: + EpRequestTypeDefById(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.SchemaFromResourceId: - IIPRequestTemplateFromResourceId(packet.CallbackId, dt, msg); + case EpPacketRequest.TypeDefByResourceId: + EpRequestTypeDefByResourceId(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.Query: - IIPRequestQueryResources(packet.CallbackId, dt, msg); + case EpPacketRequest.Query: + EpRequestQueryResources(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.LinkSchemas: - IIPRequestLinkTemplates(packet.CallbackId, dt, msg); + case EpPacketRequest.LinkTypeDefs: + EpRequestLinkTypeDefs(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.Token: - IIPRequestToken(packet.CallbackId, dt, msg); + case EpPacketRequest.Token: + EpRequestToken(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.GetResourceIdByLink: - IIPRequestGetResourceIdByLink(packet.CallbackId, dt, msg); + case EpPacketRequest.GetResourceIdByLink: + EpRequestGetResourceIdByLink(packet.CallbackId, dt, msg); break; // Manage - case IIPPacketRequest.AttachResource: - IIPRequestAttachResource(packet.CallbackId, dt, msg); + case EpPacketRequest.AttachResource: + EpRequestAttachResource(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.ReattachResource: - IIPRequestReattachResource(packet.CallbackId, dt, msg); + case EpPacketRequest.ReattachResource: + EpRequestReattachResource(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.DetachResource: - IIPRequestDetachResource(packet.CallbackId, dt, msg); + case EpPacketRequest.DetachResource: + EpRequestDetachResource(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.CreateResource: - IIPRequestCreateResource(packet.CallbackId, dt, msg); + case EpPacketRequest.CreateResource: + EpRequestCreateResource(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.DeleteResource: - IIPRequestDeleteResource(packet.CallbackId, dt, msg); + case EpPacketRequest.DeleteResource: + EpRequestDeleteResource(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.MoveResource: - IIPRequestMoveResource(packet.CallbackId, dt, msg); + case EpPacketRequest.MoveResource: + EpRequestMoveResource(packet.CallbackId, dt, msg); break; // Static - case IIPPacketRequest.KeepAlive: - IIPRequestKeepAlive(packet.CallbackId, dt, msg); + case EpPacketRequest.KeepAlive: + EpRequestKeepAlive(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.ProcedureCall: - IIPRequestProcedureCall(packet.CallbackId, dt, msg); + case EpPacketRequest.ProcedureCall: + EpRequestProcedureCall(packet.CallbackId, dt, msg); break; - case IIPPacketRequest.StaticCall: - IIPRequestStaticCall(packet.CallbackId, dt, msg); + case EpPacketRequest.StaticCall: + EpRequestStaticCall(packet.CallbackId, dt, msg); break; } } - else if (packet.Method == IIPPacketMethod.Reply) + else if (packet.Method == EpPacketMethod.Reply) { var dt = packet.DataType.Value; switch (packet.Reply) { - case IIPPacketReply.Completed: - IIPReplyCompleted(packet.CallbackId, dt); + case EpPacketReply.Completed: + EpReplyCompleted(packet.CallbackId, dt); break; - case IIPPacketReply.Propagated: - IIPReplyPropagated(packet.CallbackId, dt, msg); + case EpPacketReply.Propagated: + EpReplyPropagated(packet.CallbackId, dt, msg); break; - case IIPPacketReply.PermissionError: - IIPReplyError(packet.CallbackId, dt, msg, ErrorType.Management); + case EpPacketReply.PermissionError: + EpReplyError(packet.CallbackId, dt, msg, ErrorType.Management); break; - case IIPPacketReply.ExecutionError: - IIPReplyError(packet.CallbackId, dt, msg, ErrorType.Exception); + case EpPacketReply.ExecutionError: + EpReplyError(packet.CallbackId, dt, msg, ErrorType.Exception); break; - case IIPPacketReply.Progress: - IIPReplyProgress(packet.CallbackId, dt, msg); + case EpPacketReply.Progress: + EpReplyProgress(packet.CallbackId, dt, msg); break; - case IIPPacketReply.Chunk: - IIPReplyChunk(packet.CallbackId, dt); + case EpPacketReply.Chunk: + EpReplyChunk(packet.CallbackId, dt); break; - case IIPPacketReply.Warning: - IIPReplyWarning(packet.Extension, dt, msg); + case EpPacketReply.Warning: + EpReplyWarning(packet.Extension, dt, msg); break; } } - else if (packet.Method == IIPPacketMethod.Extension) + else if (packet.Method == EpPacketMethod.Extension) { - IIPExtensionAction(packet.Extension, packet.DataType, msg); + EpExtensionAction(packet.Extension, packet.DataType, msg); } } } @@ -665,7 +667,7 @@ public partial class DistributedConnection : NetworkConnection, IStore private void ProcessClientAuth(byte[] data) { - if (authPacket.Command == IIPAuthPacketCommand.Acknowledge) + if (authPacket.Command == EpAuthPacketCommand.Acknowledge) { // if there is a mismatch in authentication if (session.LocalMethod != authPacket.RemoteMethod @@ -683,20 +685,20 @@ public partial class DistributedConnection : NetworkConnection, IStore var rt = (Map)parsed; - session.RemoteHeaders = rt.Select(x => new KeyValuePair((IIPAuthPacketHeader)x.Key, x.Value)); + session.RemoteHeaders = rt.Select(x => new KeyValuePair((EpAuthPacketHeader)x.Key, x.Value)); if (session.LocalMethod == AuthenticationMethod.None) { // send establish SendParams() - .AddUInt8((byte)IIPAuthPacketAction.EstablishNewSession) + .AddUInt8((byte)EpAuthPacketAction.EstablishNewSession) .Done(); } else if (session.LocalMethod == AuthenticationMethod.Credentials || session.LocalMethod == AuthenticationMethod.Token) { - var remoteNonce = (byte[])session.RemoteHeaders[IIPAuthPacketHeader.Nonce]; - var localNonce = (byte[])session.LocalHeaders[IIPAuthPacketHeader.Nonce]; + var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; + var localNonce = (byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]; // send our hash var hashFunc = SHA256.Create(); @@ -708,20 +710,20 @@ public partial class DistributedConnection : NetworkConnection, IStore .ToArray()); SendParams() - .AddUInt8((byte)IIPAuthPacketAction.AuthenticateHash) - .AddUInt8((byte)IIPAuthPacketHashAlgorithm.SHA256) + .AddUInt8((byte)EpAuthPacketAction.AuthenticateHash) + .AddUInt8((byte)EpAuthPacketHashAlgorithm.SHA256) .AddUInt16((ushort)challenge.Length) .AddUInt8Array(challenge) .Done(); } } - else if (authPacket.Command == IIPAuthPacketCommand.Action) + else if (authPacket.Command == EpAuthPacketCommand.Action) { - if (authPacket.Action == IIPAuthPacketAction.AuthenticateHash) + if (authPacket.Action == EpAuthPacketAction.AuthenticateHash) { - var remoteNonce = (byte[])session.RemoteHeaders[IIPAuthPacketHeader.Nonce]; - var localNonce = (byte[])session.LocalHeaders[IIPAuthPacketHeader.Nonce]; + var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; + var localNonce = (byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]; // check if the server knows my password var hashFunc = SHA256.Create(); @@ -737,13 +739,13 @@ public partial class DistributedConnection : NetworkConnection, IStore { // send establish request SendParams() - .AddUInt8((byte)IIPAuthPacketAction.EstablishNewSession) + .AddUInt8((byte)EpAuthPacketAction.EstablishNewSession) .Done(); } else { SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.ChallengeFailed) .AddUInt16(16) .AddString("Challenge Failed") @@ -752,11 +754,11 @@ public partial class DistributedConnection : NetworkConnection, IStore } } } - else if (authPacket.Command == IIPAuthPacketCommand.Event) + else if (authPacket.Command == EpAuthPacketCommand.Event) { - if (authPacket.Event == IIPAuthPacketEvent.ErrorTerminate - || authPacket.Event == IIPAuthPacketEvent.ErrorMustEncrypt - || authPacket.Event == IIPAuthPacketEvent.ErrorRetry) + if (authPacket.Event == EpAuthPacketEvent.ErrorTerminate + || authPacket.Event == EpAuthPacketEvent.ErrorMustEncrypt + || authPacket.Event == EpAuthPacketEvent.ErrorRetry) { invalidCredentials = true; openReply?.TriggerError(new AsyncException(ErrorType.Management, authPacket.ErrorCode, authPacket.Message)); @@ -764,13 +766,13 @@ public partial class DistributedConnection : NetworkConnection, IStore OnError?.Invoke(this, authPacket.ErrorCode, authPacket.Message); Close(); } - else if (authPacket.Event == IIPAuthPacketEvent.IndicationEstablished) + else if (authPacket.Event == EpAuthPacketEvent.IndicationEstablished) { session.Id = authPacket.SessionId; session.AuthorizedAccount = authPacket.AccountId.GetString(0, (uint)authPacket.AccountId.Length); ready = true; - Status = ConnectionStatus.Connected; + Status = EpConnectionStatus.Connected; // put it in the warehouse @@ -803,19 +805,19 @@ public partial class DistributedConnection : NetworkConnection, IStore keepAliveTimer.Start(); } - else if (authPacket.Event == IIPAuthPacketEvent.IAuthPlain) + else if (authPacket.Event == EpAuthPacketEvent.IAuthPlain) { var dataType = authPacket.DataType.Value; var (_, parsed) = Codec.ParseSync(dataType, Instance.Warehouse); var rt = (Map)parsed; - var headers = rt.Select(x => new KeyValuePair((IIPAuthPacketIAuthHeader)x.Key, x.Value)); + var headers = rt.Select(x => new KeyValuePair((EpAuthPacketIAuthHeader)x.Key, x.Value)); var iAuthRequest = new AuthorizationRequest(headers); if (Authenticator == null) { SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.NotSupported) .AddUInt16(13) .AddString("Not supported") @@ -826,8 +828,8 @@ public partial class DistributedConnection : NetworkConnection, IStore Authenticator(iAuthRequest).Then(response => { SendParams() - .AddUInt8((byte)IIPAuthPacketAction.IAuthPlain) - .AddUInt32((uint)headers[IIPAuthPacketIAuthHeader.Reference]) + .AddUInt8((byte)EpAuthPacketAction.IAuthPlain) + .AddUInt32((uint)headers[EpAuthPacketIAuthHeader.Reference]) .AddUInt8Array(Codec.Compose(response, this.Instance.Warehouse, this)) .Done(); }) @@ -835,7 +837,7 @@ public partial class DistributedConnection : NetworkConnection, IStore () => { SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.Timeout) .AddUInt16(7) .AddString("Timeout") @@ -843,20 +845,20 @@ public partial class DistributedConnection : NetworkConnection, IStore }); } } - else if (authPacket.Event == IIPAuthPacketEvent.IAuthHashed) + else if (authPacket.Event == EpAuthPacketEvent.IAuthHashed) { var dataType = authPacket.DataType.Value; var (_, parsed) = Codec.ParseSync(dataType, Instance.Warehouse); var rt = (Map)parsed; - var headers = rt.Select(x => new KeyValuePair((IIPAuthPacketIAuthHeader)x.Key, x.Value)); + var headers = rt.Select(x => new KeyValuePair((EpAuthPacketIAuthHeader)x.Key, x.Value)); var iAuthRequest = new AuthorizationRequest(headers); if (Authenticator == null) { SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.NotSupported) .AddUInt16(13) .AddString("Not supported") @@ -869,15 +871,15 @@ public partial class DistributedConnection : NetworkConnection, IStore { var sha = SHA256.Create(); var hash = sha.ComputeHash(new BinaryList() - .AddUInt8Array((byte[])session.LocalHeaders[IIPAuthPacketHeader.Nonce]) + .AddUInt8Array((byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]) .AddUInt8Array(Codec.Compose(response, this.Instance.Warehouse, this)) - .AddUInt8Array((byte[])session.RemoteHeaders[IIPAuthPacketHeader.Nonce]) + .AddUInt8Array((byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]) .ToArray()); SendParams() - .AddUInt8((byte)IIPAuthPacketAction.IAuthHashed) - .AddUInt32((uint)headers[IIPAuthPacketIAuthHeader.Reference]) - .AddUInt8((byte)IIPAuthPacketHashAlgorithm.SHA256) + .AddUInt8((byte)EpAuthPacketAction.IAuthHashed) + .AddUInt32((uint)headers[EpAuthPacketIAuthHeader.Reference]) + .AddUInt8((byte)EpAuthPacketHashAlgorithm.SHA256) .AddUInt16((ushort)hash.Length) .AddUInt8Array(hash) .Done(); @@ -886,7 +888,7 @@ public partial class DistributedConnection : NetworkConnection, IStore () => { SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.Timeout) .AddUInt16(7) .AddString("Timeout") @@ -894,7 +896,7 @@ public partial class DistributedConnection : NetworkConnection, IStore }); } } - else if (authPacket.Event == IIPAuthPacketEvent.IAuthEncrypted) + else if (authPacket.Event == EpAuthPacketEvent.IAuthEncrypted) { throw new NotImplementedException("IAuthEncrypted not implemented."); } @@ -903,7 +905,7 @@ public partial class DistributedConnection : NetworkConnection, IStore private void ProcessHostAuth(byte[] data) { - if (authPacket.Command == IIPAuthPacketCommand.Initialize) + if (authPacket.Command == EpAuthPacketCommand.Initialize) { // Parse headers @@ -913,26 +915,26 @@ public partial class DistributedConnection : NetworkConnection, IStore var rt = (Map)parsed; - session.RemoteHeaders = rt.Select(x => new KeyValuePair((IIPAuthPacketHeader)x.Key, x.Value)); + session.RemoteHeaders = rt.Select(x => new KeyValuePair((EpAuthPacketHeader)x.Key, x.Value)); session.RemoteMethod = authPacket.LocalMethod; - if (authPacket.Initialization == IIPAuthPacketInitialize.CredentialsNoAuth) + if (authPacket.Initialization == EpAuthPacketInitialize.CredentialsNoAuth) { try { - var username = (string)session.RemoteHeaders[IIPAuthPacketHeader.Username]; - var domain = (string)session.RemoteHeaders[IIPAuthPacketHeader.Domain]; - //var remoteNonce = (byte[])session.RemoteHeaders[IIPAuthPacketHeader.Nonce]; + var username = (string)session.RemoteHeaders[EpAuthPacketHeader.Username]; + var domain = (string)session.RemoteHeaders[EpAuthPacketHeader.Domain]; + //var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; if (Server.Membership == null) { var errMsg = DC.ToBytes("Membership not set."); SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.GeneralFailure) .AddUInt16((ushort)errMsg.Length) .AddUInt8Array(errMsg) @@ -947,7 +949,7 @@ public partial class DistributedConnection : NetworkConnection, IStore var localHeaders = session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)); SendParams() - .AddUInt8((byte)IIPAuthPacketAcknowledge.NoAuthCredentials) + .AddUInt8((byte)EpAuthPacketAcknowledge.NoAuthCredentials) .AddUInt8Array(Codec.Compose(localHeaders, Server.Instance.Warehouse, this)) .Done(); } @@ -955,7 +957,7 @@ public partial class DistributedConnection : NetworkConnection, IStore { // Send user not found error SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.UserOrTokenNotFound) .AddUInt16(14) .AddString("User not found") @@ -969,21 +971,21 @@ public partial class DistributedConnection : NetworkConnection, IStore var errMsg = DC.ToBytes(ex.Message); SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.GeneralFailure) .AddUInt16((ushort)errMsg.Length) .AddUInt8Array(errMsg) .Done(); } } - else if (authPacket.Initialization == IIPAuthPacketInitialize.TokenNoAuth) + else if (authPacket.Initialization == EpAuthPacketInitialize.TokenNoAuth) { try { if (Server.Membership == null) { SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.UserOrTokenNotFound) .AddUInt16(15) .AddString("Token not found") @@ -992,9 +994,9 @@ public partial class DistributedConnection : NetworkConnection, IStore // Check if user and token exists else { - var tokenIndex = (ulong)session.RemoteHeaders[IIPAuthPacketHeader.TokenIndex]; - var domain = (string)session.RemoteHeaders[IIPAuthPacketHeader.Domain]; - //var nonce = (byte[])session.RemoteHeaders[IIPAuthPacketHeader.Nonce]; + var tokenIndex = (ulong)session.RemoteHeaders[EpAuthPacketHeader.TokenIndex]; + var domain = (string)session.RemoteHeaders[EpAuthPacketHeader.Domain]; + //var nonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; Server.Membership.TokenExists(tokenIndex, domain).Then(x => { @@ -1005,7 +1007,7 @@ public partial class DistributedConnection : NetworkConnection, IStore var localHeaders = session.LocalHeaders.Select(x => new KeyValuePair((byte)x.Key, x.Value)); SendParams() - .AddUInt8((byte)IIPAuthPacketAcknowledge.NoAuthToken) + .AddUInt8((byte)EpAuthPacketAcknowledge.NoAuthToken) .AddUInt8Array(Codec.Compose(localHeaders, this.Instance.Warehouse, this)) .Done(); @@ -1014,7 +1016,7 @@ public partial class DistributedConnection : NetworkConnection, IStore { // Send token not found error. SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.UserOrTokenNotFound) .AddUInt16(15) .AddString("Token not found") @@ -1030,14 +1032,14 @@ public partial class DistributedConnection : NetworkConnection, IStore var errMsg = DC.ToBytes(ex.Message); SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.GeneralFailure) .AddUInt16((ushort)errMsg.Length) .AddUInt8Array(errMsg) .Done(); } } - else if (authPacket.Initialization == IIPAuthPacketInitialize.NoAuthNoAuth) + else if (authPacket.Initialization == EpAuthPacketInitialize.NoAuthNoAuth) { try { @@ -1051,7 +1053,7 @@ public partial class DistributedConnection : NetworkConnection, IStore readyToEstablish = true; SendParams() - .AddUInt8((byte)IIPAuthPacketAcknowledge.NoAuthNoAuth) + .AddUInt8((byte)EpAuthPacketAcknowledge.NoAuthNoAuth) .AddUInt8Array(Codec.Compose(localHeaders,Server.Instance.Warehouse, this)) .Done(); } @@ -1059,7 +1061,7 @@ public partial class DistributedConnection : NetworkConnection, IStore { // Send access denied error because the server does not allow guests. SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.AccessDenied) .AddUInt16(18) .AddString("Guests not allowed") @@ -1072,7 +1074,7 @@ public partial class DistributedConnection : NetworkConnection, IStore var errMsg = DC.ToBytes(ex.Message); SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.GeneralFailure) .AddUInt16((ushort)errMsg.Length) .AddUInt8Array(errMsg) @@ -1081,9 +1083,9 @@ public partial class DistributedConnection : NetworkConnection, IStore } } - else if (authPacket.Command == IIPAuthPacketCommand.Action) + else if (authPacket.Command == EpAuthPacketCommand.Action) { - if (authPacket.Action == IIPAuthPacketAction.AuthenticateHash) + if (authPacket.Action == EpAuthPacketAction.AuthenticateHash) { var remoteHash = authPacket.Challenge; AsyncReply reply = null; @@ -1092,13 +1094,13 @@ public partial class DistributedConnection : NetworkConnection, IStore { if (session.RemoteMethod == AuthenticationMethod.Credentials) { - reply = Server.Membership.GetPassword((string)session.RemoteHeaders[IIPAuthPacketHeader.Username], - (string)session.RemoteHeaders[IIPAuthPacketHeader.Domain]); + reply = Server.Membership.GetPassword((string)session.RemoteHeaders[EpAuthPacketHeader.Username], + (string)session.RemoteHeaders[EpAuthPacketHeader.Domain]); } else if (session.RemoteMethod == AuthenticationMethod.Token) { - reply = Server.Membership.GetToken((ulong)session.RemoteHeaders[IIPAuthPacketHeader.TokenIndex], - (string)session.RemoteHeaders[IIPAuthPacketHeader.Domain]); + reply = Server.Membership.GetToken((ulong)session.RemoteHeaders[EpAuthPacketHeader.TokenIndex], + (string)session.RemoteHeaders[EpAuthPacketHeader.Domain]); } else { @@ -1109,8 +1111,8 @@ public partial class DistributedConnection : NetworkConnection, IStore { if (pw != null) { - var localNonce = (byte[])session.LocalHeaders[IIPAuthPacketHeader.Nonce]; - var remoteNonce = (byte[])session.RemoteHeaders[IIPAuthPacketHeader.Nonce]; + var localNonce = (byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]; + var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; var hashFunc = SHA256.Create(); var hash = hashFunc.ComputeHash((new BinaryList()) @@ -1129,8 +1131,8 @@ public partial class DistributedConnection : NetworkConnection, IStore .ToArray()); SendParams() - .AddUInt8((byte)IIPAuthPacketAction.AuthenticateHash) - .AddUInt8((byte)IIPAuthPacketHashAlgorithm.SHA256) + .AddUInt8((byte)EpAuthPacketAction.AuthenticateHash) + .AddUInt8((byte)EpAuthPacketHashAlgorithm.SHA256) .AddUInt16((ushort)localHash.Length) .AddUInt8Array(localHash) .Done(); @@ -1141,7 +1143,7 @@ public partial class DistributedConnection : NetworkConnection, IStore { //Global.Log("auth", LogType.Warning, "U:" + RemoteUsername + " IP:" + Socket.RemoteEndPoint.Address.ToString() + " S:DENIED"); SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.AccessDenied) .AddUInt16(13) .AddString("Access Denied") @@ -1155,14 +1157,14 @@ public partial class DistributedConnection : NetworkConnection, IStore var errMsg = DC.ToBytes(ex.Message); SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.GeneralFailure) .AddUInt16((ushort)errMsg.Length) .AddUInt8Array(errMsg) .Done(); } } - else if (authPacket.Action == IIPAuthPacketAction.IAuthPlain) + else if (authPacket.Action == EpAuthPacketAction.IAuthPlain) { var reference = authPacket.Reference; var dataType = authPacket.DataType.Value; @@ -1174,7 +1176,7 @@ public partial class DistributedConnection : NetworkConnection, IStore } - else if (authPacket.Action == IIPAuthPacketAction.IAuthHashed) + else if (authPacket.Action == EpAuthPacketAction.IAuthHashed) { var reference = authPacket.Reference; var value = authPacket.Challenge; @@ -1184,7 +1186,7 @@ public partial class DistributedConnection : NetworkConnection, IStore .Then(x => ProcessAuthorization(x)); } - else if (authPacket.Action == IIPAuthPacketAction.IAuthEncrypted) + else if (authPacket.Action == EpAuthPacketAction.IAuthEncrypted) { var reference = authPacket.Reference; var value = authPacket.Challenge; @@ -1193,7 +1195,7 @@ public partial class DistributedConnection : NetworkConnection, IStore Server.Membership.AuthorizeEncrypted(session, reference, algorithm, value) .Then(x => ProcessAuthorization(x)); } - else if (authPacket.Action == IIPAuthPacketAction.EstablishNewSession) + else if (authPacket.Action == EpAuthPacketAction.EstablishNewSession) { if (readyToEstablish) { @@ -1216,7 +1218,7 @@ public partial class DistributedConnection : NetworkConnection, IStore else { SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.GeneralFailure) .AddUInt16(9) .AddString("Not ready") @@ -1236,7 +1238,7 @@ public partial class DistributedConnection : NetworkConnection, IStore var accountId = session.AuthorizedAccount.ToBytes(); SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.IndicationEstablished) + .AddUInt8((byte)EpAuthPacketEvent.IndicationEstablished) .AddUInt8((byte)session.Id.Length) .AddUInt8Array(session.Id) .AddUInt8((byte)accountId.Length) @@ -1250,7 +1252,7 @@ public partial class DistributedConnection : NetworkConnection, IStore .Then(x => { ready = true; - Status = ConnectionStatus.Connected; + Status = EpConnectionStatus.Connected; openReply?.Trigger(true); openReply = null; OnReady?.Invoke(this); @@ -1268,7 +1270,7 @@ public partial class DistributedConnection : NetworkConnection, IStore else { ready = true; - Status = ConnectionStatus.Connected; + Status = EpConnectionStatus.Connected; openReply?.Trigger(true); openReply = null; @@ -1280,7 +1282,7 @@ public partial class DistributedConnection : NetworkConnection, IStore else if (results.Response == Security.Membership.AuthorizationResultsResponse.Failed) { SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.ChallengeFailed) .AddUInt16(21) .AddString("Authentication failed") @@ -1289,7 +1291,7 @@ public partial class DistributedConnection : NetworkConnection, IStore else if (results.Response == Security.Membership.AuthorizationResultsResponse.Expired) { SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.Timeout) .AddUInt16(22) .AddString("Authentication expired") @@ -1298,7 +1300,7 @@ public partial class DistributedConnection : NetworkConnection, IStore else if (results.Response == Security.Membership.AuthorizationResultsResponse.ServiceUnavailable) { SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.ErrorTerminate) + .AddUInt8((byte)EpAuthPacketEvent.ErrorTerminate) .AddUInt8((byte)ExceptionCode.GeneralFailure) .AddUInt16(19) .AddString("Service unavailable") @@ -1306,51 +1308,51 @@ public partial class DistributedConnection : NetworkConnection, IStore } else if (results.Response == Security.Membership.AuthorizationResultsResponse.IAuthPlain) { - var args = new Map() + var args = new Map() { - [IIPAuthPacketIAuthHeader.Reference] = results.Reference, - [IIPAuthPacketIAuthHeader.Destination] = results.Destination, - [IIPAuthPacketIAuthHeader.Trials] = results.Trials, - [IIPAuthPacketIAuthHeader.Clue] = results.Clue, - [IIPAuthPacketIAuthHeader.RequiredFormat] = results.RequiredFormat, + [EpAuthPacketIAuthHeader.Reference] = results.Reference, + [EpAuthPacketIAuthHeader.Destination] = results.Destination, + [EpAuthPacketIAuthHeader.Trials] = results.Trials, + [EpAuthPacketIAuthHeader.Clue] = results.Clue, + [EpAuthPacketIAuthHeader.RequiredFormat] = results.RequiredFormat, }.Select(m => new KeyValuePair((byte)m.Key, m.Value)); SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.IAuthPlain) + .AddUInt8((byte)EpAuthPacketEvent.IAuthPlain) .AddUInt8Array(Codec.Compose(args, this.Instance.Warehouse, this)) .Done(); } else if (results.Response == Security.Membership.AuthorizationResultsResponse.IAuthHashed) { - var args = new Map() + var args = new Map() { - [IIPAuthPacketIAuthHeader.Reference] = results.Reference, - [IIPAuthPacketIAuthHeader.Destination] = results.Destination, - [IIPAuthPacketIAuthHeader.Expire] = results.Expire, - //[IIPAuthPacketIAuthHeader.Issue] = results.Issue, - [IIPAuthPacketIAuthHeader.Clue] = results.Clue, - [IIPAuthPacketIAuthHeader.RequiredFormat] = results.RequiredFormat, + [EpAuthPacketIAuthHeader.Reference] = results.Reference, + [EpAuthPacketIAuthHeader.Destination] = results.Destination, + [EpAuthPacketIAuthHeader.Expire] = results.Expire, + //[EpAuthPacketIAuthHeader.Issue] = results.Issue, + [EpAuthPacketIAuthHeader.Clue] = results.Clue, + [EpAuthPacketIAuthHeader.RequiredFormat] = results.RequiredFormat, }.Select(m => new KeyValuePair((byte)m.Key, m.Value)); SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.IAuthHashed) + .AddUInt8((byte)EpAuthPacketEvent.IAuthHashed) .AddUInt8Array(Codec.Compose(args, Server.Instance.Warehouse, this)) .Done(); } else if (results.Response == Security.Membership.AuthorizationResultsResponse.IAuthEncrypted) { - var args = new Map() + var args = new Map() { - [IIPAuthPacketIAuthHeader.Destination] = results.Destination, - [IIPAuthPacketIAuthHeader.Expire] = results.Expire, - [IIPAuthPacketIAuthHeader.Clue] = results.Clue, - [IIPAuthPacketIAuthHeader.RequiredFormat] = results.RequiredFormat, + [EpAuthPacketIAuthHeader.Destination] = results.Destination, + [EpAuthPacketIAuthHeader.Expire] = results.Expire, + [EpAuthPacketIAuthHeader.Clue] = results.Clue, + [EpAuthPacketIAuthHeader.RequiredFormat] = results.RequiredFormat, }.Select(m => new KeyValuePair((byte)m.Key, m.Value)); SendParams() - .AddUInt8((byte)IIPAuthPacketEvent.IAuthEncrypted) + .AddUInt8((byte)EpAuthPacketEvent.IAuthEncrypted) .AddUInt8Array(Codec.Compose(args, this.Instance.Warehouse, this)) .Done(); } @@ -1428,12 +1430,12 @@ public partial class DistributedConnection : NetworkConnection, IStore - public AsyncReply Connect(AuthenticationMethod method = AuthenticationMethod.Certificate, Sockets.ISocket socket = null, string hostname = null, ushort port = 0, string username = null, ulong tokenIndex = 0, byte[] passwordOrToken = null, string domain = null) + public AsyncReply Connect(AuthenticationMethod method = AuthenticationMethod.Certificate, ISocket socket = null, string hostname = null, ushort port = 0, string username = null, ulong tokenIndex = 0, byte[] passwordOrToken = null, string domain = null) { if (openReply != null) throw new AsyncException(ErrorType.Exception, 0, "Connection in progress"); - Status = ConnectionStatus.Connecting; + Status = EpConnectionStatus.Connecting; openReply = new AsyncReply(); @@ -1444,16 +1446,16 @@ public partial class DistributedConnection : NetworkConnection, IStore session.LocalMethod = method; session.RemoteMethod = AuthenticationMethod.None; - session.LocalHeaders[IIPAuthPacketHeader.Domain] = domain; - session.LocalHeaders[IIPAuthPacketHeader.Nonce] = Global.GenerateBytes(32); + session.LocalHeaders[EpAuthPacketHeader.Domain] = domain; + session.LocalHeaders[EpAuthPacketHeader.Nonce] = Global.GenerateBytes(32); if (method == AuthenticationMethod.Credentials) { - session.LocalHeaders[IIPAuthPacketHeader.Username] = username; + session.LocalHeaders[EpAuthPacketHeader.Username] = username; } else if (method == AuthenticationMethod.Token) { - session.LocalHeaders[IIPAuthPacketHeader.TokenIndex] = tokenIndex; + session.LocalHeaders[EpAuthPacketHeader.TokenIndex] = tokenIndex; } else if (method == AuthenticationMethod.Certificate) { @@ -1495,7 +1497,7 @@ public partial class DistributedConnection : NetworkConnection, IStore { if (AutoReconnect) { - Global.Log("DistributedConnection", LogType.Debug, "Reconnecting socket..."); + Global.Log("EpConnection", LogType.Debug, "Reconnecting socket..."); Task.Delay((int)ReconnectInterval).ContinueWith((x) => connectSocket(socket)); } else @@ -1517,10 +1519,10 @@ public partial class DistributedConnection : NetworkConnection, IStore try { - var toBeRestored = new List(); - foreach (KeyValuePair> kv in suspendedResources) + var toBeRestored = new List(); + foreach (KeyValuePair> kv in suspendedResources) { - DistributedResource r; + EpResource r; if (kv.Value.TryGetTarget(out r)) toBeRestored.Add(r); } @@ -1530,11 +1532,11 @@ public partial class DistributedConnection : NetworkConnection, IStore var link = DC.ToBytes(r.DistributedResourceLink); - Global.Log("DistributedConnection", LogType.Debug, "Restoreing " + r.DistributedResourceLink); + Global.Log("EpConnection", LogType.Debug, "Restoreing " + r.DistributedResourceLink); try { - var id = (uint)await SendRequest(IIPPacketRequest.GetResourceIdByLink, link); + var id = (uint)await SendRequest(EpPacketRequest.GetResourceIdByLink, link); // remove from suspended. @@ -1548,7 +1550,7 @@ public partial class DistributedConnection : NetworkConnection, IStore await Fetch(id, null); - Global.Log("DistributedConnection", LogType.Debug, "Restored " + id); + Global.Log("EpConnection", LogType.Debug, "Restored " + id); } catch (AsyncException ex) @@ -1589,7 +1591,7 @@ public partial class DistributedConnection : NetworkConnection, IStore public AsyncReply Put(IResource resource, string path) { if (Codec.IsLocalResource(resource, this)) - neededResources.Add((resource as DistributedResource).DistributedResourceInstanceId, (DistributedResource)resource); + neededResources.Add((resource as EpResource).DistributedResourceInstanceId, (EpResource)resource); // else ... send it to the peer return new AsyncReply(true); } @@ -1600,7 +1602,7 @@ public partial class DistributedConnection : NetworkConnection, IStore return true; } - public bool Modify(IResource resource, string propertyName, object value, ulong? age, DateTime? dateTime) + public bool Modify(IResource resource, PropertyDef propertyDef, object value, ulong? age, DateTime? dateTime) { // nothing to do return true; @@ -1624,7 +1626,7 @@ public partial class DistributedConnection : NetworkConnection, IStore // clean up ready = false; readyToEstablish = false; - Status = ConnectionStatus.Closed; + Status = EpConnectionStatus.Closed; keepAliveTimer.Stop(); @@ -1654,7 +1656,7 @@ public partial class DistributedConnection : NetworkConnection, IStore } } - foreach (var x in templateRequests.Values) + foreach (var x in typeDefsByIdRequests.Values) { try { @@ -1666,14 +1668,28 @@ public partial class DistributedConnection : NetworkConnection, IStore } } + foreach (var x in typeDefsByNameRequests.Values) + { + try + { + x.TriggerError(new AsyncException(ErrorType.Management, 0, "Connection closed")); + } + catch (Exception ex) + { + Global.Log(ex); + } + } + + requests.Clear(); resourceRequests.Clear(); - templateRequests.Clear(); + typeDefsByIdRequests.Clear(); + typeDefsByNameRequests.Clear(); foreach (var x in attachedResources.Values) { - DistributedResource r; + EpResource r; if (x.TryGetTarget(out r)) { r.Suspend(); @@ -1712,7 +1728,7 @@ public partial class DistributedConnection : NetworkConnection, IStore throw new NotImplementedException(); } - public AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate) + public AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate) { throw new NotImplementedException(); } diff --git a/Esiur/Protocol/EpConnectionConfig.cs b/Esiur/Protocol/EpConnectionConfig.cs new file mode 100644 index 0000000..cac0576 --- /dev/null +++ b/Esiur/Protocol/EpConnectionConfig.cs @@ -0,0 +1,35 @@ +using Esiur.Core; +using Esiur.Data; +using Esiur.Net.Packets; +using Esiur.Security.Membership; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Protocol; + +public class EpConnectionConfig +{ + public ExceptionLevel ExceptionLevel { get; set; } + = ExceptionLevel.Code | ExceptionLevel.Message | ExceptionLevel.Source | ExceptionLevel.Trace; + + public Func> Authenticator { get; set; } + + public bool AutoReconnect { get; set; } = false; + + public uint ReconnectInterval { get; set; } = 5; + + public string Username { get; set; } + + public bool UseWebSocket { get; set; } + + public bool SecureWebSocket { get; set; } + + public string Password { get; set; } + + public string Token { get; set; } + + public ulong TokenIndex { get; set; } + + public string Domain { get; set; } +} diff --git a/Esiur/Net/IIP/DistributedConnectionProtocol.cs b/Esiur/Protocol/EpConnectionProtocol.cs similarity index 83% rename from Esiur/Net/IIP/DistributedConnectionProtocol.cs rename to Esiur/Protocol/EpConnectionProtocol.cs index 6c956f2..6b90907 100644 --- a/Esiur/Net/IIP/DistributedConnectionProtocol.cs +++ b/Esiur/Protocol/EpConnectionProtocol.cs @@ -41,15 +41,15 @@ using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; -namespace Esiur.Net.IIP; +namespace Esiur.Protocol; -partial class DistributedConnection +partial class EpConnection { - KeyList neededResources = new KeyList(); - KeyList> attachedResources = new KeyList>(); - KeyList> suspendedResources = new KeyList>(); + KeyList neededResources = new KeyList(); + KeyList> attachedResources = new KeyList>(); + KeyList> suspendedResources = new KeyList>(); - KeyList resourceRequests = new KeyList(); + KeyList resourceRequests = new KeyList(); KeyList> typeDefsByIdRequests = new KeyList>(); KeyList> typeDefsByNameRequests = new KeyList>(); @@ -68,7 +68,7 @@ partial class DistributedConnection object subscriptionsLock = new object(); - AsyncQueue queue = new(); + AsyncQueue queue = new(); @@ -78,7 +78,7 @@ partial class DistributedConnection /// Packet action. /// Arguments to send. /// - AsyncReply SendRequest(IIPPacketRequest action, params object[] args) + AsyncReply SendRequest(EpPacketRequest action, params object[] args) { var reply = new AsyncReply(); var c = callbackCounter++; // avoid thread racing @@ -117,7 +117,7 @@ partial class DistributedConnection /// Packet action. /// Arguments to send. /// - AsyncReply SendNotification(IIPPacketNotification action, params object[] args) + AsyncReply SendNotification(EpPacketNotification action, params object[] args) { var reply = new AsyncReply(); @@ -144,7 +144,7 @@ partial class DistributedConnection return reply; } - void SendReply(IIPPacketReply action, uint callbackId, params object[] args) + void SendReply(EpPacketReply action, uint callbackId, params object[] args) { if (Instance == null) return; @@ -177,18 +177,18 @@ partial class DistributedConnection internal AsyncReply SendSubscribeRequest(uint instanceId, byte index) { - return SendRequest(IIPPacketRequest.Subscribe, instanceId, index); + return SendRequest(EpPacketRequest.Subscribe, instanceId, index); } internal AsyncReply SendUnsubscribeRequest(uint instanceId, byte index) { - return SendRequest(IIPPacketRequest.Unsubscribe, instanceId, index); + return SendRequest(EpPacketRequest.Unsubscribe, instanceId, index); } public AsyncReply StaticCall(UUID classId, byte index, object parameters) { - return SendRequest(IIPPacketRequest.StaticCall, classId, index, parameters); + return SendRequest(EpPacketRequest.StaticCall, classId, index, parameters); } public AsyncReply Call(string procedureCall, params object[] parameters) @@ -198,22 +198,22 @@ partial class DistributedConnection // args.Add(i, parameters[i]); // return Call(procedureCall, parameters); - return SendRequest(IIPPacketRequest.ProcedureCall, procedureCall, parameters); + return SendRequest(EpPacketRequest.ProcedureCall, procedureCall, parameters); } public AsyncReply Call(string procedureCall, Map parameters) { - return SendRequest(IIPPacketRequest.ProcedureCall, procedureCall, parameters); + return SendRequest(EpPacketRequest.ProcedureCall, procedureCall, parameters); } internal AsyncReply SendInvoke(uint instanceId, byte index, object parameters) { - return SendRequest(IIPPacketRequest.InvokeFunction, instanceId, index, parameters); + return SendRequest(EpPacketRequest.InvokeFunction, instanceId, index, parameters); } internal AsyncReply SendSetProperty(uint instanceId, byte index, object value) { - return SendRequest(IIPPacketRequest.SetProperty, instanceId, index, value); + return SendRequest(EpPacketRequest.SetProperty, instanceId, index, value); } internal AsyncReply SendDetachRequest(uint instanceId) @@ -235,7 +235,7 @@ partial class DistributedConnection } if (sendDetach) - return SendRequest(IIPPacketRequest.DetachResource, instanceId); + return SendRequest(EpPacketRequest.DetachResource, instanceId); return null; // no one is waiting for this } @@ -248,29 +248,29 @@ partial class DistributedConnection void SendError(ErrorType type, uint callbackId, ushort errorCodeOrWarningLevel, string message = "") { if (type == ErrorType.Management) - SendReply(IIPPacketReply.PermissionError, callbackId, errorCodeOrWarningLevel, message); + SendReply(EpPacketReply.PermissionError, callbackId, errorCodeOrWarningLevel, message); else if (type == ErrorType.Exception) - SendReply(IIPPacketReply.ExecutionError, callbackId, errorCodeOrWarningLevel, message); + SendReply(EpPacketReply.ExecutionError, callbackId, errorCodeOrWarningLevel, message); else if (type == ErrorType.Warning) - SendReply(IIPPacketReply.Warning, callbackId, (byte)errorCodeOrWarningLevel, message); + SendReply(EpPacketReply.Warning, callbackId, (byte)errorCodeOrWarningLevel, message); } internal void SendProgress(uint callbackId, uint value, uint max) { - SendReply(IIPPacketReply.Progress, callbackId, value, max); + SendReply(EpPacketReply.Progress, callbackId, value, max); } internal void SendWarning(uint callbackId, byte level, string message) { - SendReply(IIPPacketReply.Warning, callbackId, level, message); + SendReply(EpPacketReply.Warning, callbackId, level, message); } internal void SendChunk(uint callbackId, object chunk) { - SendReply(IIPPacketReply.Chunk, callbackId, chunk); + SendReply(EpPacketReply.Chunk, callbackId, chunk); } - void IIPReplyCompleted(uint callbackId, ParsedTDU dataType) + void EpReplyCompleted(uint callbackId, ParsedTDU dataType) { var req = requests.Take(callbackId); @@ -301,12 +301,12 @@ partial class DistributedConnection } } - void IIPExtensionAction(byte actionId, ParsedTDU? dataType, byte[] data) + void EpExtensionAction(byte actionId, ParsedTDU? dataType, byte[] data) { // nothing is supported now } - void IIPReplyPropagated(uint callbackId, ParsedTDU dataType, byte[] data) + void EpReplyPropagated(uint callbackId, ParsedTDU dataType, byte[] data) { var req = requests[callbackId]; @@ -330,7 +330,7 @@ partial class DistributedConnection } } - void IIPReplyError(uint callbackId, ParsedTDU dataType, byte[] data, ErrorType type) + void EpReplyError(uint callbackId, ParsedTDU dataType, byte[] data, ErrorType type) { var req = requests.Take(callbackId); @@ -349,7 +349,7 @@ partial class DistributedConnection req.TriggerError(new AsyncException(type, errorCode, errorMsg)); } - void IIPReplyProgress(uint callbackId, ParsedTDU dataType, byte[] data) + void EpReplyProgress(uint callbackId, ParsedTDU dataType, byte[] data) { var req = requests[callbackId]; @@ -368,7 +368,7 @@ partial class DistributedConnection req.TriggerProgress(ProgressType.Execution, current, total); } - void IIPReplyWarning(uint callbackId, ParsedTDU dataType, byte[] data) + void EpReplyWarning(uint callbackId, ParsedTDU dataType, byte[] data) { var req = requests[callbackId]; @@ -389,7 +389,7 @@ partial class DistributedConnection - void IIPReplyChunk(uint callbackId, ParsedTDU dataType) + void EpReplyChunk(uint callbackId, ParsedTDU dataType) { var req = requests[callbackId]; @@ -404,16 +404,16 @@ partial class DistributedConnection req.TriggerChunk(parsed); } - void IIPNotificationResourceReassigned(ParsedTDU dataType) + void EpNotificationResourceReassigned(ParsedTDU dataType) { // uint resourceId, uint newResourceId } - void IIPNotificationResourceMoved(ParsedTDU dataType, byte[] data) { } + void EpNotificationResourceMoved(ParsedTDU dataType, byte[] data) { } - void IIPNotificationSystemFailure(ParsedTDU dataType, byte[] data) { } + void EpNotificationSystemFailure(ParsedTDU dataType, byte[] data) { } - void IIPNotificationResourceDestroyed(ParsedTDU dataType, byte[] data) + void EpNotificationResourceDestroyed(ParsedTDU dataType, byte[] data) { var (size, rt) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -421,7 +421,7 @@ partial class DistributedConnection if (attachedResources.Contains(resourceId)) { - DistributedResource r; + EpResource r; if (attachedResources[resourceId].TryGetTarget(out r)) { @@ -444,7 +444,7 @@ partial class DistributedConnection } - void IIPNotificationPropertyModified(ParsedTDU dataType) + void EpNotificationPropertyModified(ParsedTDU dataType) { // resourceId, index, value var (valueOffset, valueSize, args) = @@ -464,20 +464,20 @@ partial class DistributedConnection if (parsed is AsyncReply) { - var item = new AsyncReply(); + var item = new AsyncReply(); queue.Add(item); (parsed as AsyncReply).Then((result) => { - item.Trigger(new DistributedResourceQueueItem((DistributedResource)r, - DistributedResourceQueueItem.DistributedResourceQueueItemType.Propery, + item.Trigger(new EpResourceQueueItem((EpResource)r, + EpResourceQueueItem.DistributedResourceQueueItemType.Propery, result, index)); }); } else { - queue.Add(new AsyncReply(new DistributedResourceQueueItem((DistributedResource)r, - DistributedResourceQueueItem.DistributedResourceQueueItemType.Propery, + queue.Add(new AsyncReply(new EpResourceQueueItem((EpResource)r, + EpResourceQueueItem.DistributedResourceQueueItemType.Propery, parsed, index))); //item.Trigger(new DistributedResourceQueueItem((DistributedResource)r, @@ -488,7 +488,7 @@ partial class DistributedConnection } - void IIPNotificationEventOccurred(ParsedTDU dataType, byte[] data) + void EpNotificationEventOccurred(ParsedTDU dataType, byte[] data) { // resourceId, index, value var (valueOffset, valueSize, args) = @@ -506,7 +506,7 @@ partial class DistributedConnection return; // push to the queue to guarantee serialization - var item = new AsyncReply(); + var item = new AsyncReply(); queue.Add(item); @@ -516,20 +516,20 @@ partial class DistributedConnection { (parsed as AsyncReply).Then((result) => { - item.Trigger(new DistributedResourceQueueItem((DistributedResource)r, - DistributedResourceQueueItem.DistributedResourceQueueItemType.Event, result, index)); + item.Trigger(new EpResourceQueueItem((EpResource)r, + EpResourceQueueItem.DistributedResourceQueueItemType.Event, result, index)); }); } else { - item.Trigger(new DistributedResourceQueueItem((DistributedResource)r, - DistributedResourceQueueItem.DistributedResourceQueueItemType.Event, parsed, index)); + item.Trigger(new EpResourceQueueItem((EpResource)r, + EpResourceQueueItem.DistributedResourceQueueItemType.Event, parsed, index)); } }); } - void IIPEventRenamed(uint resourceId, string name) + void EpEventRenamed(uint resourceId, string name) { Fetch(resourceId, null).Then(resource => { @@ -537,7 +537,7 @@ partial class DistributedConnection }); } - void IIPRequestAttachResource(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestAttachResource(uint callback, ParsedTDU dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -560,8 +560,8 @@ partial class DistributedConnection Unsubscribe(r); // reply ok - SendReply(IIPPacketReply.Completed, callback, - r.Instance.Definition.TypeId, + SendReply(EpPacketReply.Completed, callback, + r.Instance.Definition.Id, r.Instance.Age, r.Instance.Link, r.Instance.Hops, @@ -573,13 +573,13 @@ partial class DistributedConnection else { // reply failed - Global.Log("DistributedConnection", LogType.Debug, "Not found " + resourceId); + Global.Log("EpConnection", LogType.Debug, "Not found " + resourceId); SendError(ErrorType.Management, callback, (ushort)ExceptionCode.ResourceNotFound); } }); } - void IIPRequestReattachResource(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestReattachResource(uint callback, ParsedTDU dataType, byte[] data) { // resourceId, index, value var (valueOffset, valueSize, args) = @@ -607,8 +607,8 @@ partial class DistributedConnection // reply ok - SendReply(IIPPacketReply.Completed, callback, - r.Instance.Definition.TypeId, + SendReply(EpPacketReply.Completed, callback, + r.Instance.Definition.Id, r.Instance.Age, r.Instance.Link, r.Instance.Hops, @@ -621,13 +621,13 @@ partial class DistributedConnection else { // reply failed - Global.Log("DistributedConnection", LogType.Debug, "Not found " + resourceId); + Global.Log("EpConnection", LogType.Debug, "Not found " + resourceId); SendError(ErrorType.Management, callback, (ushort)ExceptionCode.ResourceNotFound); } }); } - void IIPRequestDetachResource(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestDetachResource(uint callback, ParsedTDU dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -648,7 +648,7 @@ partial class DistributedConnection //attachedResources.Remove(res); // reply ok - SendReply(IIPPacketReply.Completed, callback); + SendReply(EpPacketReply.Completed, callback); } else { @@ -658,7 +658,7 @@ partial class DistributedConnection }); } - void IIPRequestCreateResource(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestCreateResource(uint callback, ParsedTDU dataType, byte[] data) { var (_, parsed) = Codec.ParseAsync(dataType, this, null); @@ -671,7 +671,7 @@ partial class DistributedConnection if (args[1] is UUID) type = Instance.Warehouse.GetTypeDefById((UUID)args[1]); else if (args[1] is string) - type = Instance.Warehouse.GetTypeByName((string)args[1]); + type = Instance.Warehouse.GetTypeDefByName((string)args[1]); if (type == null) { @@ -705,7 +705,7 @@ partial class DistributedConnection Instance.Warehouse.New(type.DefinedType, path, null, attrs, props).Then(resource => { - SendReply(IIPPacketReply.Completed, callback, resource.Instance.Id); + SendReply(EpPacketReply.Completed, callback, resource.Instance.Id); }).Error(e => { @@ -719,7 +719,7 @@ partial class DistributedConnection } - void IIPRequestDeleteResource(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestDeleteResource(uint callback, ParsedTDU dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -741,14 +741,14 @@ partial class DistributedConnection } if (Instance.Warehouse.Remove(r)) - SendReply(IIPPacketReply.Completed, callback); + SendReply(EpPacketReply.Completed, callback); else SendError(ErrorType.Management, callback, (ushort)ExceptionCode.DeleteFailed); }); } - void IIPRequestMoveResource(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestMoveResource(uint callback, ParsedTDU dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, @@ -781,7 +781,7 @@ partial class DistributedConnection resource.Instance.Name = name; - SendReply(IIPPacketReply.Completed, callback); + SendReply(EpPacketReply.Completed, callback); }); } @@ -789,12 +789,12 @@ partial class DistributedConnection - void IIPRequestToken(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestToken(uint callback, ParsedTDU dataType, byte[] data) { // @TODO: To be implemented } - void IIPRequestLinkTemplates(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestLinkTypeDefs(uint callback, ParsedTDU dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -817,7 +817,7 @@ partial class DistributedConnection var templates = TypeDef.GetDependencies(r.Instance.Definition, Instance.Warehouse); // Send - SendReply(IIPPacketReply.Completed, callback, templates.Select(x => x.Content).ToArray()); + SendReply(EpPacketReply.Completed, callback, templates.Select(x => x.Content).ToArray()); }; @@ -827,17 +827,17 @@ partial class DistributedConnection Instance.Warehouse.Query(resourceLink).Then(queryCallback); } - void IIPRequestTemplateFromClassName(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestTypeDefByName(uint callback, ParsedTDU dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); var className = (string)value; - var t = Instance.Warehouse.GetTemplateByClassName(className); + var t = Instance.Warehouse.GetTypeDefByName(className); if (t != null) { - SendReply(IIPPacketReply.Completed, callback, t.Content); + SendReply(EpPacketReply.Completed, callback, t.Content); } else { @@ -846,7 +846,7 @@ partial class DistributedConnection } } - void IIPRequestTypeDefById(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestTypeDefById(uint callback, ParsedTDU dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -857,7 +857,7 @@ partial class DistributedConnection if (t != null) { - SendReply(IIPPacketReply.Completed, callback, t.Content); + SendReply(EpPacketReply.Completed, callback, t.Content); } else { @@ -868,7 +868,7 @@ partial class DistributedConnection - void IIPRequestTemplateFromResourceId(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestTypeDefByResourceId(uint callback, ParsedTDU dataType, byte[] data) { var (_, value) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -879,7 +879,7 @@ partial class DistributedConnection { if (r != null) { - SendReply(IIPPacketReply.Completed, callback, r.Instance.Definition.Content); + SendReply(EpPacketReply.Completed, callback, r.Instance.Definition.Content); } else { @@ -891,7 +891,7 @@ partial class DistributedConnection - void IIPRequestGetResourceIdByLink(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestGetResourceIdByLink(uint callback, ParsedTDU dataType, byte[] data) { var (_, parsed) = Codec.ParseSync(dataType, Instance.Warehouse); var resourceLink = (string)parsed; @@ -908,7 +908,7 @@ partial class DistributedConnection return; } - SendReply(IIPPacketReply.Completed, callback, r); + SendReply(EpPacketReply.Completed, callback, r); } }; @@ -919,7 +919,7 @@ partial class DistributedConnection } - void IIPRequestQueryResources(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestQueryResources(uint callback, ParsedTDU dataType, byte[] data) { var (_, parsed) = Codec.ParseSync(dataType, Instance.Warehouse); @@ -940,7 +940,7 @@ partial class DistributedConnection r.Instance.Children().Then(children => { var list = children.Where(x => x.Instance.Applicable(session, ActionType.Attach, null) != Ruling.Denied).ToArray(); - SendReply(IIPPacketReply.Completed, callback, list); + SendReply(EpPacketReply.Completed, callback, list); }).Error(e => { SendError(e.Type, callback, (ushort)e.Code, e.Message); @@ -958,7 +958,7 @@ partial class DistributedConnection .Error(e => SendError(e.Type, callback, (ushort)e.Code, e.Message)); } - void IIPRequestResourceAttribute(uint callback, uint resourceId) + void EpRequestResourceAttribute(uint callback, uint resourceId) { } @@ -977,7 +977,7 @@ partial class DistributedConnection } - void IIPRequestProcedureCall(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestProcedureCall(uint callback, ParsedTDU dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, dataType.ContentLength, Instance.Warehouse, 1); @@ -1018,7 +1018,7 @@ partial class DistributedConnection // return; //} - InvokeFunction(call.Value.Template, callback, results, IIPPacketRequest.ProcedureCall, call.Value.Delegate.Target); + InvokeFunction(call.Value.Template, callback, results, EpPacketRequest.ProcedureCall, call.Value.Delegate.Target); }).Error(x => { @@ -1033,11 +1033,11 @@ partial class DistributedConnection this.Socket.Unhold(); // @TODO: Make managers for procedure calls - InvokeFunction(call.Value.Template, callback, parsed, IIPPacketRequest.ProcedureCall, call.Value.Delegate.Target); + InvokeFunction(call.Value.Template, callback, parsed, EpPacketRequest.ProcedureCall, call.Value.Delegate.Target); } } - void IIPRequestStaticCall(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestStaticCall(uint callback, ParsedTDU dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, dataType.ContentLength, Instance.Warehouse, 2); @@ -1093,7 +1093,7 @@ partial class DistributedConnection // return; //} - InvokeFunction(ft, callback, results, IIPPacketRequest.StaticCall, null); + InvokeFunction(ft, callback, results, EpPacketRequest.StaticCall, null); }).Error(x => { @@ -1110,11 +1110,11 @@ partial class DistributedConnection // @TODO: Make managers for static calls - InvokeFunction(ft, callback, parsed, IIPPacketRequest.StaticCall, null); + InvokeFunction(ft, callback, parsed, EpPacketRequest.StaticCall, null); } } - void IIPRequestInvokeFunction(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestInvokeFunction(uint callback, ParsedTDU dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, dataType.ContentLength, Instance.Warehouse, 2); @@ -1151,14 +1151,14 @@ partial class DistributedConnection // un hold the socket to send data immediately this.Socket.Unhold(); - if (r is DistributedResource) + if (r is EpResource) { - var rt = (r as DistributedResource)._Invoke(index, result); + var rt = (r as EpResource)._Invoke(index, result); if (rt != null) { rt.Then(res => { - SendReply(IIPPacketReply.Completed, callback, res); + SendReply(EpPacketReply.Completed, callback, res); }); } else @@ -1176,7 +1176,7 @@ partial class DistributedConnection return; } - InvokeFunction(ft, callback, result, IIPPacketRequest.InvokeFunction, r); + InvokeFunction(ft, callback, result, EpPacketRequest.InvokeFunction, r); } }); } @@ -1187,14 +1187,14 @@ partial class DistributedConnection // un hold the socket to send data immediately this.Socket.Unhold(); - if (r is DistributedResource) + if (r is EpResource) { - var rt = (r as DistributedResource)._Invoke(index, parsed); + var rt = (r as EpResource)._Invoke(index, parsed); if (rt != null) { rt.Then(res => { - SendReply(IIPPacketReply.Completed, callback, res); + SendReply(EpPacketReply.Completed, callback, res); }); } else @@ -1212,7 +1212,7 @@ partial class DistributedConnection return; } - InvokeFunction(ft, callback, parsed, IIPPacketRequest.InvokeFunction, r); + InvokeFunction(ft, callback, parsed, EpPacketRequest.InvokeFunction, r); } } @@ -1221,7 +1221,7 @@ partial class DistributedConnection - void InvokeFunction(FunctionDef ft, uint callback, object arguments, IIPPacketRequest actionType, object target = null) + void InvokeFunction(FunctionDef ft, uint callback, object arguments, EpPacketRequest actionType, object target = null) { // cast arguments @@ -1233,7 +1233,7 @@ partial class DistributedConnection if (pis.Length > 0) { - if (pis.Last().ParameterType == typeof(DistributedConnection)) + if (pis.Last().ParameterType == typeof(EpConnection)) { if (arguments is Map indexedArguments) { @@ -1376,7 +1376,7 @@ partial class DistributedConnection SendChunk(callback, v); } - SendReply(IIPPacketReply.Completed, callback); + SendReply(EpPacketReply.Completed, callback); if (context != null) context.Ended = true; @@ -1400,7 +1400,7 @@ partial class DistributedConnection foreach (var v in enu) SendChunk(callback, v); - SendReply(IIPPacketReply.Completed, callback); + SendReply(EpPacketReply.Completed, callback); if (context != null) context.Ended = true; @@ -1429,7 +1429,7 @@ partial class DistributedConnection var res = t.GetType().GetProperty("Result").GetValue(t); #endif - SendReply(IIPPacketReply.Completed, callback, res); + SendReply(EpPacketReply.Completed, callback, res); }); } @@ -1440,7 +1440,7 @@ partial class DistributedConnection if (context != null) context.Ended = true; - SendReply(IIPPacketReply.Completed, callback, res); + SendReply(EpPacketReply.Completed, callback, res); }).Error(ex => { @@ -1462,11 +1462,11 @@ partial class DistributedConnection if (context != null) context.Ended = true; - SendReply(IIPPacketReply.Completed, callback, rt); + SendReply(EpPacketReply.Completed, callback, rt); } } - void IIPRequestSubscribe(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestSubscribe(uint callback, ParsedTDU dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, @@ -1493,11 +1493,11 @@ partial class DistributedConnection return; } - if (r is DistributedResource) + if (r is EpResource) { - (r as DistributedResource).Subscribe(et).Then(x => + (r as EpResource).Subscribe(et).Then(x => { - SendReply(IIPPacketReply.Completed, callback); + SendReply(EpPacketReply.Completed, callback); }).Error(x => SendError(ErrorType.Exception, callback, (ushort)ExceptionCode.GeneralFailure)); } else @@ -1518,14 +1518,14 @@ partial class DistributedConnection subscriptions[r].Add(index); - SendReply(IIPPacketReply.Completed, callback); + SendReply(EpPacketReply.Completed, callback); } } }); } - void IIPRequestUnsubscribe(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestUnsubscribe(uint callback, ParsedTDU dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, @@ -1552,11 +1552,11 @@ partial class DistributedConnection return; } - if (r is DistributedResource) + if (r is EpResource) { - (r as DistributedResource).Unsubscribe(et).Then(x => + (r as EpResource).Unsubscribe(et).Then(x => { - SendReply(IIPPacketReply.Completed, callback); + SendReply(EpPacketReply.Completed, callback); }).Error(x => SendError(ErrorType.Exception, callback, (ushort)ExceptionCode.GeneralFailure)); } else @@ -1577,7 +1577,7 @@ partial class DistributedConnection subscriptions[r].Remove(index); - SendReply(IIPPacketReply.Completed, callback); + SendReply(EpPacketReply.Completed, callback); } } }); @@ -1586,7 +1586,7 @@ partial class DistributedConnection - void IIPRequestSetProperty(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestSetProperty(uint callback, ParsedTDU dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, @@ -1627,7 +1627,7 @@ partial class DistributedConnection // propagation (r as IDynamicResource).SetResourcePropertyAsync(index, value).Then((x) => { - SendReply(IIPPacketReply.Completed, callback); + SendReply(EpPacketReply.Completed, callback); }).Error(x => { SendError(x.Type, callback, (ushort)x.Code, x.Message); @@ -1677,7 +1677,7 @@ partial class DistributedConnection try { pi.SetValue(r, value); - SendReply(IIPPacketReply.Completed, callback); + SendReply(EpPacketReply.Completed, callback); } catch (Exception ex) { @@ -1702,7 +1702,7 @@ partial class DistributedConnection try { pi.SetValue(r, parsed); - SendReply(IIPPacketReply.Completed, callback); + SendReply(EpPacketReply.Completed, callback); } catch (Exception ex) { @@ -1719,23 +1719,23 @@ partial class DistributedConnection /// /// Class GUID. /// TypeSchema. - public AsyncReply GetTypeDefById(UUID classId) + public AsyncReply GetTypeDefById(UUID typeId) { - if (typeDefs.ContainsKey(classId)) - return new AsyncReply(typeDefs[classId]); - else if (typeDefsByIdRequests.ContainsKey(classId)) - return typeDefsByIdRequests[classId]; + if (typeDefs.ContainsKey(typeId)) + return new AsyncReply(typeDefs[typeId]); + else if (typeDefsByIdRequests.ContainsKey(typeId)) + return typeDefsByIdRequests[typeId]; var reply = new AsyncReply(); - typeDefsByIdRequests.Add(classId, reply); + typeDefsByIdRequests.Add(typeId, reply); - SendRequest(IIPPacketRequest.SchemaFromClassId, classId) + SendRequest(EpPacketRequest.TypeDefById, typeId) .Then((result) => { var tt = TypeDef.Parse((byte[])result); - typeDefsByIdRequests.Remove(classId); - typeDefs.Add(tt.ClassId, tt); - Instance.Warehouse.RegisterSchema(tt); + typeDefsByIdRequests.Remove(typeId); + typeDefs.Add(tt.Id, tt); + Instance.Warehouse.RegisterTypeDef(tt); reply.Trigger(tt); }).Error((ex) => @@ -1747,27 +1747,27 @@ partial class DistributedConnection } - public AsyncReply GetTypeDefByClassName(string className) + public AsyncReply GetTypeDefByName(string typeName) { - var template = typeDefs.Values.FirstOrDefault(x => x.ClassName == className); + var template = typeDefs.Values.FirstOrDefault(x => x.Name == typeName); if (template != null) return new AsyncReply(template); - if (typeDefsByNameRequests.ContainsKey(className)) - return typeDefsByNameRequests[className]; + if (typeDefsByNameRequests.ContainsKey(typeName)) + return typeDefsByNameRequests[typeName]; var reply = new AsyncReply(); - typeDefsByNameRequests.Add(className, reply); + typeDefsByNameRequests.Add(typeName, reply); - SendRequest(IIPPacketRequest.SchemaFromClassName, className) + SendRequest(EpPacketRequest.TypeDefByName, typeName) .Then((result) => { var tt = TypeDef.Parse((byte[])result); - typeDefsByNameRequests.Remove(className); - typeDefs.Add(tt.ClassId, tt); - Instance.Warehouse.RegisterSchema(tt); + typeDefsByNameRequests.Remove(typeName); + typeDefs.Add(tt.Id, tt); + Instance.Warehouse.RegisterTypeDef(tt); reply.Trigger(tt); }).Error((ex) => { @@ -1788,7 +1788,7 @@ partial class DistributedConnection var rt = new AsyncReply(); - var req = SendRequest(IIPPacketRequest.GetResourceIdByLink, path); + var req = SendRequest(EpPacketRequest.GetResourceIdByLink, path); req.Then(result => @@ -1820,7 +1820,7 @@ partial class DistributedConnection var reply = new AsyncReply(); - SendRequest(IIPPacketRequest.LinkSchemas, link) + SendRequest(EpPacketRequest.LinkTypeDefs, link) .Then((result) => { @@ -1847,15 +1847,15 @@ partial class DistributedConnection /// Class GUID /// Resource IdGuid classId /// DistributedResource - public AsyncReply Fetch(uint id, uint[] requestSequence) + public AsyncReply Fetch(uint id, uint[] requestSequence) { - DistributedResource resource = null; + EpResource resource = null; attachedResources[id]?.TryGetTarget(out resource); if (resource != null) - return new AsyncReply(resource); + return new AsyncReply(resource); resource = neededResources[id]; @@ -1866,12 +1866,12 @@ partial class DistributedConnection if (resource != null && (requestSequence?.Contains(id) ?? false)) { // dead lock avoidance for loop reference. - return new AsyncReply(resource); + return new AsyncReply(resource); } else if (resource != null && requestInfo.RequestSequence.Contains(id)) { // dead lock avoidance for dependent reference. - return new AsyncReply(resource); + return new AsyncReply(resource); } else { @@ -1882,16 +1882,16 @@ partial class DistributedConnection { // @REVIEW: this should never happen Global.Log("DCON", LogType.Error, "Resource not moved to attached."); - return new AsyncReply(resource); + return new AsyncReply(resource); } var newSequence = requestSequence != null ? requestSequence.Concat(new uint[] { id }).ToArray() : new uint[] { id }; - var reply = new AsyncReply(); - resourceRequests.Add(id, new DistributedResourceAttachRequestInfo(reply, newSequence)); + var reply = new AsyncReply(); + resourceRequests.Add(id, new EpResourceAttachRequestInfo(reply, newSequence)); - SendRequest(IIPPacketRequest.AttachResource, id) + SendRequest(EpPacketRequest.AttachResource, id) .Then((result) => { if (result == null) @@ -1910,16 +1910,16 @@ partial class DistributedConnection var pvData = (byte[])args[4]; - DistributedResource dr; + EpResource dr; TypeDef typeDef = null; if (resource == null) { - typeDef = Instance.Warehouse.GetTypeDefByClassId(typeId, TypeDefKind.Resource); + typeDef = Instance.Warehouse.GetTypeDefById(typeId, TypeDefKind.Resource); if (typeDef?.DefinedType != null && typeDef.IsWrapper) - dr = Activator.CreateInstance(typeDef.DefinedType, this, id, Convert.ToUInt64(args[1]), (string)args[2]) as DistributedResource; + dr = Activator.CreateInstance(typeDef.DefinedType, this, id, Convert.ToUInt64(args[1]), (string)args[2]) as EpResource; else - dr = new DistributedResource(this, id, Convert.ToUInt64(args[1]), (string)args[2]); + dr = new EpResource(this, id, Convert.ToUInt64(args[1]), (string)args[2]); } else { @@ -1928,7 +1928,7 @@ partial class DistributedConnection } - var initResource = (DistributedResource ok) => + var initResource = (EpResource ok) => { var parsedReply = DataDeserializer.PropertyValueArrayParserAsync(pvData, 0, (uint)pvData.Length, this, newSequence);// Codec.proper (content, 0, this, newSequence, transmissionType); @@ -1946,7 +1946,7 @@ partial class DistributedConnection resourceRequests.Remove(id); // move from needed to attached. neededResources.Remove(id); - attachedResources[id] = new WeakReference(dr); + attachedResources[id] = new WeakReference(dr); reply.Trigger(dr); }).Error(ex => reply.TriggerError(ex)); @@ -2010,7 +2010,7 @@ partial class DistributedConnection var str = DC.ToBytes(path); var reply = new AsyncReply(); - SendRequest(IIPPacketRequest.Query, path) + SendRequest(EpPacketRequest.Query, path) .Then(result => { reply.Trigger((IResource[])result); @@ -2028,12 +2028,12 @@ partial class DistributedConnection /// Values for the resource properties. /// Resource attributes. /// New resource instance - public AsyncReply Create(string path, TypeDef type, Map properties, Map attributes) + public AsyncReply Create(string path, TypeDef type, Map properties, Map attributes) { - var reply = new AsyncReply(); + var reply = new AsyncReply(); - SendRequest(IIPPacketRequest.CreateResource, path, type.ClassId, type.CastProperties(properties), attributes) - .Then(r => reply.Trigger((DistributedResource)r)) + SendRequest(EpPacketRequest.CreateResource, path, type.Id, type.CastProperties(properties), attributes) + .Then(r => reply.Trigger((EpResource)r)) .Error(e => reply.TriggerError(e)) .Warning((l, m) => reply.TriggerWarning(l, m)); @@ -2090,12 +2090,12 @@ partial class DistributedConnection Unsubscribe(resource); // compose the packet - SendNotification(IIPPacketNotification.ResourceDestroyed, resource.Instance.Id); + SendNotification(EpPacketNotification.ResourceDestroyed, resource.Instance.Id); } private void Instance_PropertyModified(PropertyModificationInfo info) { - SendNotification(IIPPacketNotification.PropertyModified, + SendNotification(EpPacketNotification.PropertyModified, info.Resource.Instance.Id, info.PropertyTemplate.Index, info.Value); @@ -2124,7 +2124,7 @@ partial class DistributedConnection // compose the packet - SendNotification(IIPPacketNotification.EventOccurred, + SendNotification(EpPacketNotification.EventOccurred, info.Resource.Instance.Id, info.EventTemplate.Index, info.Value); @@ -2149,7 +2149,7 @@ partial class DistributedConnection return; // compose the packet - SendNotification(IIPPacketNotification.EventOccurred, + SendNotification(EpPacketNotification.EventOccurred, info.Resource.Instance.Id, info.Definition.Index, info.Value); @@ -2157,7 +2157,7 @@ partial class DistributedConnection - void IIPRequestKeepAlive(uint callback, ParsedTDU dataType, byte[] data) + void EpRequestKeepAlive(uint callback, ParsedTDU dataType, byte[] data) { var (offset, length, args) = DataDeserializer.LimitedCountListParser(data, dataType.Offset, @@ -2176,7 +2176,7 @@ partial class DistributedConnection jitter = (uint)Math.Abs((int)diff - (int)interval); } - SendReply(IIPPacketReply.Completed, callback, now, jitter); + SendReply(EpPacketReply.Completed, callback, now, jitter); lastKeepAliveReceived = now; } diff --git a/Esiur/Net/IIP/ConnectionStatus.cs b/Esiur/Protocol/EpConnectionStatus.cs similarity index 70% rename from Esiur/Net/IIP/ConnectionStatus.cs rename to Esiur/Protocol/EpConnectionStatus.cs index 0178277..43c17cf 100644 --- a/Esiur/Net/IIP/ConnectionStatus.cs +++ b/Esiur/Protocol/EpConnectionStatus.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.Text; -namespace Esiur.Net.IIP +namespace Esiur.Protocol { - public enum ConnectionStatus + public enum EpConnectionStatus { Closed, Connecting, diff --git a/Esiur/Net/IIP/DistributedResource.cs b/Esiur/Protocol/EpResource.cs similarity index 94% rename from Esiur/Net/IIP/DistributedResource.cs rename to Esiur/Protocol/EpResource.cs index dea846f..4b5e643 100644 --- a/Esiur/Net/IIP/DistributedResource.cs +++ b/Esiur/Protocol/EpResource.cs @@ -43,10 +43,10 @@ using Esiur.Resource; using Esiur.Net.Packets; using Esiur.Data.Types; -namespace Esiur.Net.IIP; +namespace Esiur.Protocol; //[System.Runtime.InteropServices.ComVisible(true)] -public class DistributedResource : DynamicObject, IResource, INotifyPropertyChanged, IDynamicResource +public class EpResource : DynamicObject, IResource, INotifyPropertyChanged, IDynamicResource { /// @@ -58,7 +58,7 @@ public class DistributedResource : DynamicObject, IResource, INotifyPropertyChan uint instanceId; TypeDef typeDef; - DistributedConnection connection; + EpConnection connection; bool attached = false; @@ -71,17 +71,17 @@ public class DistributedResource : DynamicObject, IResource, INotifyPropertyChan ulong age; protected object[] properties; - internal List parents = new List(); - internal List children = new List(); + internal List parents = new List(); + internal List children = new List(); - DistributedResourceEvent[] events; + EpResourceEvent[] events; /// /// Connection responsible for the distributed resource. /// - public DistributedConnection DistributedResourceConnection + public EpConnection DistributedResourceConnection { get { return connection; } } @@ -145,7 +145,7 @@ public class DistributedResource : DynamicObject, IResource, INotifyPropertyChan /// Resource template. /// Instance Id given by the other end. /// Resource age. - public DistributedResource(DistributedConnection connection, uint instanceId, ulong age, string link) + public EpResource(EpConnection connection, uint instanceId, ulong age, string link) { this.link = link; this.connection = connection; @@ -163,7 +163,7 @@ public class DistributedResource : DynamicObject, IResource, INotifyPropertyChan this.properties = new object[properties.Length]; - this.events = new DistributedResourceEvent[Instance.Definition.Events.Length]; + this.events = new EpResourceEvent[Instance.Definition.Events.Length]; for (byte i = 0; i < properties.Length; i++) { @@ -209,7 +209,7 @@ public class DistributedResource : DynamicObject, IResource, INotifyPropertyChan throw new Exception("Function template not found."); if (ft.IsStatic) - return connection.StaticCall(Instance.Definition.ClassId, index, args); + return connection.StaticCall(Instance.Definition.Id, index, args); else return connection.SendInvoke(instanceId, index, args); } @@ -416,7 +416,7 @@ public class DistributedResource : DynamicObject, IResource, INotifyPropertyChan if (et == null) return false; - events[et.Index] = (DistributedResourceEvent)value; + events[et.Index] = (EpResourceEvent)value; return true; } @@ -448,7 +448,7 @@ public class DistributedResource : DynamicObject, IResource, INotifyPropertyChan /// /// Create a new instance of distributed resource. /// - public DistributedResource() + public EpResource() { //stack = new DistributedResourceStack(this); //this.Instance.ResourceModified += this.OnModified; @@ -553,7 +553,7 @@ public class DistributedResource : DynamicObject, IResource, INotifyPropertyChan return; } - ~DistributedResource() + ~EpResource() { Destroy(); } diff --git a/Esiur/Protocol/EpResourceAttachRequestInfo.cs b/Esiur/Protocol/EpResourceAttachRequestInfo.cs new file mode 100644 index 0000000..ada422c --- /dev/null +++ b/Esiur/Protocol/EpResourceAttachRequestInfo.cs @@ -0,0 +1,19 @@ +using Esiur.Core; +using Esiur.Resource; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Protocol; + +internal class EpResourceAttachRequestInfo +{ + public AsyncReply Reply { get; set; } + public uint[] RequestSequence { get; set; } + + public EpResourceAttachRequestInfo(AsyncReply reply, uint[] requestSequence) + { + Reply = reply; + RequestSequence = requestSequence; + } +} diff --git a/Esiur/Net/IIP/DistributedResourceEvent.cs b/Esiur/Protocol/EpResourceEvent.cs similarity index 91% rename from Esiur/Net/IIP/DistributedResourceEvent.cs rename to Esiur/Protocol/EpResourceEvent.cs index fc16eb0..c325d80 100644 --- a/Esiur/Net/IIP/DistributedResourceEvent.cs +++ b/Esiur/Protocol/EpResourceEvent.cs @@ -28,6 +28,6 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Esiur.Net.IIP; +namespace Esiur.Protocol; -public delegate void DistributedResourceEvent(DistributedResource sender, object argument); +public delegate void EpResourceEvent(EpResource sender, object argument); diff --git a/Esiur/Net/IIP/DistributedResourceQueueItem.cs b/Esiur/Protocol/EpResourceQueueItem.cs similarity index 86% rename from Esiur/Net/IIP/DistributedResourceQueueItem.cs rename to Esiur/Protocol/EpResourceQueueItem.cs index 1e3250d..da7c1c8 100644 --- a/Esiur/Net/IIP/DistributedResourceQueueItem.cs +++ b/Esiur/Protocol/EpResourceQueueItem.cs @@ -28,8 +28,8 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Esiur.Net.IIP; -public class DistributedResourceQueueItem +namespace Esiur.Protocol; +public class EpResourceQueueItem { public enum DistributedResourceQueueItemType { @@ -40,9 +40,9 @@ public class DistributedResourceQueueItem DistributedResourceQueueItemType type; byte index; object value; - DistributedResource resource; + EpResource resource; - public DistributedResourceQueueItem(DistributedResource resource, DistributedResourceQueueItemType type, object value, byte index) + public EpResourceQueueItem(EpResource resource, DistributedResourceQueueItemType type, object value, byte index) { this.resource = resource; this.index = index; @@ -50,7 +50,7 @@ public class DistributedResourceQueueItem this.value = value; } - public DistributedResource Resource + public EpResource Resource { get { return resource; } } diff --git a/Esiur/Net/IIP/DistributedServer.cs b/Esiur/Protocol/EpServer.cs similarity index 87% rename from Esiur/Net/IIP/DistributedServer.cs rename to Esiur/Protocol/EpServer.cs index 2b01aa9..2c54614 100644 --- a/Esiur/Net/IIP/DistributedServer.cs +++ b/Esiur/Protocol/EpServer.cs @@ -35,10 +35,12 @@ using System.Net; using Esiur.Resource; using Esiur.Security.Membership; using System.Threading.Tasks; -using Esiur.Data.Schema; +using Esiur.Data.Types; +using Esiur.Net; + +namespace Esiur.Protocol; -namespace Esiur.Net.IIP; -public class DistributedServer : NetworkServer, IResource +public class EpServer : NetworkServer, IResource { @@ -133,7 +135,7 @@ public class DistributedServer : NetworkServer, IResource - protected override void ClientConnected(DistributedConnection connection) + protected override void ClientConnected(EpConnection connection) { //Task.Delay(10000).ContinueWith((x) => //{ @@ -145,20 +147,20 @@ public class DistributedServer : NetworkServer, IResource } - public override void Add(DistributedConnection connection) + public override void Add(EpConnection connection) { connection.Server = this; connection.ExceptionLevel = ExceptionLevel; base.Add(connection); } - public override void Remove(DistributedConnection connection) + public override void Remove(EpConnection connection) { connection.Server = null; base.Remove(connection); } - protected override void ClientDisconnected(DistributedConnection connection) + protected override void ClientDisconnected(EpConnection connection) { //connection.OnReady -= ConnectionReadyEventReceiver; //Warehouse.Remove(connection); @@ -168,13 +170,13 @@ public class DistributedServer : NetworkServer, IResource public struct CallInfo { - public FunctionDefinition Template; + public FunctionDef Template; public Delegate Delegate; } - public DistributedServer MapCall(string call, Delegate handler) + public EpServer MapCall(string call, Delegate handler) { - var ft = FunctionDefinition.MakeFunctionDef(null, handler.Method, 0, call, null); + var ft = FunctionDef.MakeFunctionDef(null, handler.Method, 0, call, null); Calls.Add(call, new CallInfo() { Delegate = handler, Template = ft }); return this; } diff --git a/Esiur/Net/IIP/DistributedSession.cs b/Esiur/Protocol/EpSession.cs similarity index 93% rename from Esiur/Net/IIP/DistributedSession.cs rename to Esiur/Protocol/EpSession.cs index 360e9ed..d4b4303 100644 --- a/Esiur/Net/IIP/DistributedSession.cs +++ b/Esiur/Protocol/EpSession.cs @@ -25,11 +25,12 @@ SOFTWARE. using System; using System.Collections.Generic; using System.Text; +using Esiur.Net; using Esiur.Net.Sockets; using Esiur.Security.Authority; -namespace Esiur.Net.IIP; -public class DistributedSession : NetworkSession +namespace Esiur.Protocol; +public class EpSession : NetworkSession { public Source Source { get; set; } public Authentication Authentication { get; set; } diff --git a/Esiur/Protocol/PropertyContext.cs b/Esiur/Protocol/PropertyContext.cs new file mode 100644 index 0000000..004542c --- /dev/null +++ b/Esiur/Protocol/PropertyContext.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Esiur.Protocol; + +public interface IPropertyContext +{ + object GetValue(EpConnection connection); +} + +public class PropertyContext : IPropertyContext +{ + public T Value { get; private set; } + public EpConnection Connection { get; private set; } + public Func Method { get; private set; } + + public PropertyContext(EpConnection connection, T value) + { + this.Value = value; + this.Connection = connection; + } + + public PropertyContext(Func method) + { + this.Method = method; + } + + public static implicit operator PropertyContext(Func method) + => new PropertyContext(method); + + public object GetValue(EpConnection connection) + { + return Method.Invoke(connection); + } +} diff --git a/Esiur/Net/IIP/ResourcePropertyChangedEventArgs.cs b/Esiur/Protocol/ResourcePropertyChangedEventArgs.cs similarity index 95% rename from Esiur/Net/IIP/ResourcePropertyChangedEventArgs.cs rename to Esiur/Protocol/ResourcePropertyChangedEventArgs.cs index dc8a0e5..cfb5fe6 100644 --- a/Esiur/Net/IIP/ResourcePropertyChangedEventArgs.cs +++ b/Esiur/Protocol/ResourcePropertyChangedEventArgs.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Text; -namespace Esiur.Net.IIP +namespace Esiur.Protocol { public class ResourcePropertyChangedEventArgs : PropertyChangedEventArgs { diff --git a/Esiur/Proxy/ResourceGenerator.cs b/Esiur/Proxy/ResourceGenerator.cs index 837a73f..8750d0d 100644 --- a/Esiur/Proxy/ResourceGenerator.cs +++ b/Esiur/Proxy/ResourceGenerator.cs @@ -5,7 +5,7 @@ using Esiur.Core; using Esiur.Data; using Esiur.Data.Types; -using Esiur.Net.IIP; +using Esiur.Protocol; using Esiur.Resource; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; @@ -52,11 +52,11 @@ namespace Esiur.Proxy { try { - if (!TemplateGenerator.urlRegex.IsMatch(path)) + if (!TypeDefGenerator.urlRegex.IsMatch(path)) continue; - var parts = TemplateGenerator.urlRegex.Split(path); - var con = Warehouse.Default.Get($"{parts[1]}://{parts[2]}").Wait(20000); + var parts = TypeDefGenerator.urlRegex.Split(path); + var con = Warehouse.Default.Get($"{parts[1]}://{parts[2]}").Wait(20000); var templates = con.GetLinkDefinitions(parts[3]).Wait(60000); EmitTemplates(spc, templates); @@ -228,20 +228,20 @@ $@" public partial class {ci.Name} : IResource {{ { if (tmp.Kind == TypeDefKind.Resource) { - var source = TemplateGenerator.GenerateClass(tmp, templates, false); + var source = TypeDefGenerator.GenerateClass(tmp, templates, false); spc.AddSource(tmp.Name + ".g.cs", source); } else if (tmp.Kind == TypeDefKind.Record) { - var source = TemplateGenerator.GenerateRecord(tmp, templates); + var source = TypeDefGenerator.GenerateRecord(tmp, templates); spc.AddSource(tmp.Name + ".g.cs", source); } } var typesFile = "using System; \r\n namespace Esiur { public static class Generated { public static Type[] Resources {get;} = new Type[] { " + - string.Join(",", templates.Where(x => x.Kind == TypeDefKind.Resource).Select(x => $"typeof({x.ClassName})")) + string.Join(",", templates.Where(x => x.Kind == TypeDefKind.Resource).Select(x => $"typeof({x.Name})")) + " }; \r\n public static Type[] Records { get; } = new Type[] { " + - string.Join(",", templates.Where(x => x.Kind == TypeDefKind.Record).Select(x => $"typeof({x.ClassName})")) + string.Join(",", templates.Where(x => x.Kind == TypeDefKind.Record).Select(x => $"typeof({x.Name})")) + " }; " + "\r\n } \r\n}"; diff --git a/Esiur/Proxy/TemplateGenerator.cs b/Esiur/Proxy/TypeDefGenerator.cs similarity index 95% rename from Esiur/Proxy/TemplateGenerator.cs rename to Esiur/Proxy/TypeDefGenerator.cs index bf81aa0..94acc2e 100644 --- a/Esiur/Proxy/TemplateGenerator.cs +++ b/Esiur/Proxy/TypeDefGenerator.cs @@ -6,13 +6,13 @@ using System.Text; using System.Linq; using System.Text.RegularExpressions; using Esiur.Resource; -using Esiur.Net.IIP; using System.Diagnostics; using Esiur.Data.Types; +using Esiur.Protocol; namespace Esiur.Proxy; -public static class TemplateGenerator +public static class TypeDefGenerator { internal static Regex urlRegex = new Regex(@"^(?:([\S]*)://([^/]*)/?)"); @@ -71,7 +71,7 @@ public static class TemplateGenerator var rt = new StringBuilder(); - rt.AppendLine("using System;\r\nusing Esiur.Resource;\r\nusing Esiur.Core;\r\nusing Esiur.Data;\r\nusing Esiur.Net.IIP;"); + rt.AppendLine("using System;\r\nusing Esiur.Resource;\r\nusing Esiur.Core;\r\nusing Esiur.Data;\r\nusing Esiur.Protocol;"); rt.AppendLine($"namespace {nameSpace} {{"); if (typeDef.Annotations != null) @@ -118,7 +118,7 @@ public static class TemplateGenerator var rt = new StringBuilder(); - rt.AppendLine("using System;\r\nusing Esiur.Resource;\r\nusing Esiur.Core;\r\nusing Esiur.Data;\r\nusing Esiur.Net.IIP;"); + rt.AppendLine("using System;\r\nusing Esiur.Resource;\r\nusing Esiur.Core;\r\nusing Esiur.Data;\r\nusing Esiur.Protocol;"); rt.AppendLine($"namespace {nameSpace} {{"); if (template.Annotations != null) @@ -202,10 +202,10 @@ public static class TemplateGenerator { if (!urlRegex.IsMatch(url)) - throw new Exception("Invalid IIP URL"); + throw new Exception("Invalid EP URL"); var path = urlRegex.Split(url); - var con = Warehouse.Default.Get(path[1] + "://" + path[2], + var con = Warehouse.Default.Get(path[1] + "://" + path[2], !string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password) ? new { Username = username, Password = password } : null ).Wait(20000); @@ -288,7 +288,7 @@ public static class TemplateGenerator var rt = new StringBuilder(); - rt.AppendLine("using System;\r\nusing Esiur.Resource;\r\nusing Esiur.Core;\r\nusing Esiur.Data;\r\nusing Esiur.Net.IIP;"); + rt.AppendLine("using System;\r\nusing Esiur.Resource;\r\nusing Esiur.Core;\r\nusing Esiur.Data;\r\nusing Esiur.Protocol;"); rt.AppendLine("#nullable enable"); rt.AppendLine($"namespace {nameSpace} {{"); @@ -306,12 +306,12 @@ public static class TemplateGenerator // extends if (template.ParentId == null) - rt.AppendLine($"public class {className} : DistributedResource {{"); + rt.AppendLine($"public class {className} : EpResource {{"); else rt.AppendLine($"public class {className} : {templates.First(x => x.Id == template.ParentId && x.Kind == TypeDefKind.Resource).Name} {{"); - rt.AppendLine($"public {className}(DistributedConnection connection, uint instanceId, ulong age, string link) : base(connection, instanceId, age, link) {{}}"); + rt.AppendLine($"public {className}(EpConnection connection, uint instanceId, ulong age, string link) : base(connection, instanceId, age, link) {{}}"); rt.AppendLine($"public {className}() {{}}"); foreach (var f in template.Functions) @@ -335,7 +335,7 @@ public static class TemplateGenerator if (f.IsStatic) { - rt.Append($"[Export] public static AsyncReply<{rtTypeName}> {f.Name}(DistributedConnection connection"); + rt.Append($"[Export] public static AsyncReply<{rtTypeName}> {f.Name}(EpConnection connection"); if (positionalArgs.Length > 0) rt.Append(", " + diff --git a/Esiur/README.md b/Esiur/README.md index 7c4361a..b89cb30 100644 --- a/Esiur/README.md +++ b/Esiur/README.md @@ -83,7 +83,7 @@ Now we can add our resource to the memory store using ***Warehouse.Put*** await Warehouse.Put("sys/hello", new HelloResource()); ``` -To distribute our resource using Esiur IIP Protocol we need to add a DistributedServer +To distribute our resource using Esiur EP Protocol we need to add a DistributedServer ```C# @@ -111,7 +111,7 @@ To sum up To access our resource remotely, we need to use it's full path including the protocol, host and instance link. ```C# - dynamic res = await Warehouse.Get("iip://localhost/sys/hello"); + dynamic res = await Warehouse.Get("EP://localhost/sys/hello"); ``` Now we can invoke the exported functions and read/write properties; @@ -128,7 +128,7 @@ Summing up >```C# > using Esiur.Resource; > -> dynamic res = await Warehouse.Get("iip://localhost/sys/hello"); +> dynamic res = await Warehouse.Get("EP://localhost/sys/hello"); > > var reply = await res.SayHi("Hi, I'm calling you from dotnet"); > @@ -146,14 +146,14 @@ Esiur has a self describing feature which comes with every language it supports, After installing the Esiur nuget package a new command is added to Visual Studio Package Console Manager that is called ***Get-Template***, which generates client side classes for robust static typing. ```ps -Get-Template iip://localhost/sys/hello +Get-Template EP://localhost/sys/hello ``` This will generate and add wrappers for all types needed by our resource. Allowing us to use ```C# - var res = await Warehouse.Get("iip://localhost/sys/hello"); + var res = await Warehouse.Get("EP://localhost/sys/hello"); var reply = await res.SayHi("Static typing is better"); Console.WriteLine(reply); ``` diff --git a/Esiur/Resource/IStore.cs b/Esiur/Resource/IStore.cs index f149306..9e03c04 100644 --- a/Esiur/Resource/IStore.cs +++ b/Esiur/Resource/IStore.cs @@ -31,7 +31,7 @@ using System.Text; using System.Threading.Tasks; using Esiur.Security.Permissions; using Esiur.Security.Authority; -using Esiur.Data.Schema; +using Esiur.Data.Types; namespace Esiur.Resource; public interface IStore : IResource @@ -39,8 +39,8 @@ public interface IStore : IResource AsyncReply Get(string path); AsyncReply Put(IResource resource, string path); string Link(IResource resource); - bool Record(IResource resource, string propertyName, object value, ulong? age, DateTime? dateTime); - bool Modify(IResource resource, string propertyName, object value, ulong? age, DateTime? dateTime); + //bool Record(IResource resource, string propertyName, object value, ulong? age, DateTime? dateTime); + bool Modify(IResource resource, PropertyDef propertyDef, object value, ulong? age, DateTime? dateTime); AsyncReply Remove(IResource resource); AsyncReply Remove(string path); @@ -73,5 +73,5 @@ public interface IStore : IResource //AsyncReply> GetRecord(IResource resource, ulong fromAge, ulong toAge); // AsyncReply> GetRecordByDate(IResource resource, DateTime fromDate, DateTime toDate); - AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate); + //AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate); } diff --git a/Esiur/Resource/Instance.cs b/Esiur/Resource/Instance.cs index 2f41deb..e1b55a8 100644 --- a/Esiur/Resource/Instance.cs +++ b/Esiur/Resource/Instance.cs @@ -6,7 +6,6 @@ using System.Threading.Tasks; using Esiur.Data; using System.Runtime.CompilerServices; using System.Reflection; -using Esiur.Net.IIP; using Esiur.Misc; using Esiur.Security.Permissions; using Esiur.Security.Authority; @@ -16,67 +15,68 @@ using System.Text.Json; using System.ComponentModel.DataAnnotations.Schema; using System.Reflection.Emit; using Esiur.Data.Types; +using Esiur.Protocol; namespace Esiur.Resource; [NotMapped] public class Instance { - string name; + string name; - // public int IntVal { get; set; } + // public int IntVal { get; set; } - WeakReference resource; - IStore store; - TypeDef definition; - AutoList managers; + WeakReference resource; + IStore store; + TypeDef definition; + AutoList managers; - public event PropertyModifiedEvent PropertyModified; + public event PropertyModifiedEvent PropertyModified; - public event EventOccurredEvent EventOccurred; - public event CustomEventOccurredEvent CustomEventOccurred; - public event ResourceDestroyedEvent Destroyed; + public event EventOccurredEvent EventOccurred; + public event CustomEventOccurredEvent CustomEventOccurred; + public event ResourceDestroyedEvent Destroyed; - bool loading = false; + bool loading = false; - //KeyList attributes; + //KeyList attributes; - List ages = new(); - List modificationDates = new(); - private ulong instanceAge; - private byte hops; - private DateTime instanceModificationDate; + List ages = new(); + List modificationDates = new(); + private ulong instanceAge; + private byte hops; + private DateTime instanceModificationDate; - uint id; + uint id; - public KeyList Variables { get; } = new KeyList(); + public KeyList Variables { get; } = new KeyList(); - /// - /// Instance attributes are custom properties associated with the instance, a place to store information by IStore. - /// - //public KeyList Attributes - //{ - // get - // { - // return attributes; - // } - //} + /// + /// Instance attributes are custom properties associated with the instance, a place to store information by IStore. + /// + //public KeyList Attributes + //{ + // get + // { + // return attributes; + // } + //} - public override string ToString() - { - return name + " (" + Link + ")"; - } + public override string ToString() + { + return name + " (" + Link + ")"; + } - public bool RemoveAttributes(string[] attributes = null) - { + public bool RemoveAttributes(string[] attributes = null) + { - return false; + return false; - /* + /* IResource res; if (!resource.TryGetTarget(out res)) @@ -85,7 +85,7 @@ public class Instance return store.RemoveAttributes(res, attributes); */ - /* + /* if (attributes == null) this.attributes.Clear(); else @@ -96,51 +96,51 @@ public class Instance return true; */ - } + } - public Map GetAttributes(string[] attributes = null) - { - // @TODO - var rt = new Map(); + public Map GetAttributes(string[] attributes = null) + { + // @TODO + var rt = new Map(); - if (attributes != null) - { - for (var i = 0; i < attributes.Length; i++) - { - var at = definition.GetAttributeDef(attributes[i]); - if (at != null) - { + if (attributes != null) + { + for (var i = 0; i < attributes.Length; i++) + { + var at = definition.GetAttributeDef(attributes[i]); + if (at != null) + { - } - } - } + } + } + } - return rt; - } + return rt; + } - public bool SetAttributes(Map attributes, bool clearAttributes = false) - { + public bool SetAttributes(Map attributes, bool clearAttributes = false) + { - // @ TODO - IResource res; + // @ TODO + IResource res; - if (resource.TryGetTarget(out res)) - { - foreach (var kv in attributes) - { - var at = definition.GetAttributeDef(kv.Key); + if (resource.TryGetTarget(out res)) + { + foreach (var kv in attributes) + { + var at = definition.GetAttributeDef(kv.Key); - if (at != null) - if (at.PropertyInfo.CanWrite) - at.PropertyInfo.SetValue(res, RuntimeCaster.Cast(kv.Value, at.PropertyInfo.PropertyType)); + if (at != null) + if (at.PropertyInfo.CanWrite) + at.PropertyInfo.SetValue(res, RuntimeCaster.Cast(kv.Value, at.PropertyInfo.PropertyType)); - } - } + } + } - return true; + return true; - /* + /* try { @@ -189,9 +189,9 @@ public class Instance return true; */ - } + } - /* + /* public Structure GetAttributes() { var st = new Structure(); @@ -215,84 +215,84 @@ public class Instance return st; }*/ - /// - /// Get the age of a given property index. - /// - /// Zero-based property index. - /// Age. - public ulong? GetAge(byte index) - { - if (index < ages.Count) - return ages[index]; - else - return 0; - } + /// + /// Get the age of a given property index. + /// + /// Zero-based property index. + /// Age. + public ulong? GetAge(byte index) + { + if (index < ages.Count) + return ages[index]; + else + return 0; + } - /// - /// Set the age of a property. - /// - /// Zero-based property index. - /// Age. - public void SetAge(byte index, ulong? value) - { - if (index < ages.Count) - { - ages[index] = value; - if (value > instanceAge) - instanceAge = (ulong)value; - } - } + /// + /// Set the age of a property. + /// + /// Zero-based property index. + /// Age. + public void SetAge(byte index, ulong? value) + { + if (index < ages.Count) + { + ages[index] = value; + if (value > instanceAge) + instanceAge = (ulong)value; + } + } - /// - /// Set the modification date of a property. - /// - /// Zero-based property index. - /// Modification date. - public void SetModificationDate(byte index, DateTime? value) - { - if (index < modificationDates.Count) - { - modificationDates[index] = value; - if (value > instanceModificationDate) - instanceModificationDate = (DateTime)value; - } - } + /// + /// Set the modification date of a property. + /// + /// Zero-based property index. + /// Modification date. + public void SetModificationDate(byte index, DateTime? value) + { + if (index < modificationDates.Count) + { + modificationDates[index] = value; + if (value > instanceModificationDate) + instanceModificationDate = (DateTime)value; + } + } - /// - /// Get modification date of a specific property. - /// - /// Zero-based property index - /// Modification date. - public DateTime? GetModificationDate(byte index) - { - if (index < modificationDates.Count) - return modificationDates[index]; - else - return DateTime.MinValue; - } + /// + /// Get modification date of a specific property. + /// + /// Zero-based property index + /// Modification date. + public DateTime? GetModificationDate(byte index) + { + if (index < modificationDates.Count) + return modificationDates[index]; + else + return DateTime.MinValue; + } - /// - /// Load property value (used by stores) - /// - /// Property name - /// Property age - /// Property value - /// - public bool LoadProperty(string name, ulong? age, DateTime? modificationDate, object value) - { + /// + /// Load property value (used by stores) + /// + /// Property name + /// Property age + /// Property value + /// + public bool LoadProperty(string name, ulong? age, DateTime? modificationDate, object value) + { - IResource res; + IResource res; - if (!resource.TryGetTarget(out res)) - return false; + if (!resource.TryGetTarget(out res)) + return false; - var pt = definition.GetPropertyDefByName(name); + var pt = definition.GetPropertyDefByName(name); - if (pt == null) - return false; + if (pt == null) + return false; - /* + /* #if NETSTANDARD var pi = resource.GetType().GetTypeInfo().GetProperty(name, new[] { resource.GetType() }); #else @@ -300,560 +300,547 @@ public class Instance #endif */ - if (pt.PropertyInfo.PropertyType.IsGenericType - && pt.PropertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(PropertyContext<>)) - return false; + if (pt.PropertyInfo.PropertyType.IsGenericType + && pt.PropertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(PropertyContext<>)) + return false; - if (pt.PropertyInfo.CanWrite) - { - try - { - loading = true; + if (pt.PropertyInfo.CanWrite) + { + try + { + loading = true; - pt.PropertyInfo.SetValue(res, RuntimeCaster.Cast(value, pt.PropertyInfo.PropertyType)); - } - catch (Exception ex) - { - //Console.WriteLine(resource.ToString() + " " + name); - Global.Log(ex); - } + pt.PropertyInfo.SetValue(res, RuntimeCaster.Cast(value, pt.PropertyInfo.PropertyType)); + } + catch (Exception ex) + { + //Console.WriteLine(resource.ToString() + " " + name); + Global.Log(ex); + } - loading = false; - } + loading = false; + } - SetAge(pt.Index, age); - SetModificationDate(pt.Index, modificationDate); + SetAge(pt.Index, age); + SetModificationDate(pt.Index, modificationDate); - return true; - } + return true; + } - /// - /// Age of the instance, incremented by 1 in every modification. - /// - public ulong Age - { - get { return instanceAge; } - internal set { instanceAge = value; } - } + /// + /// Age of the instance, incremented by 1 in every modification. + /// + public ulong Age + { + get { return instanceAge; } + internal set { instanceAge = value; } + } - /// - /// Number of nodes to reach the original resource. - /// - public byte Hops - { - get { return hops; } - internal set { hops = value; } - } + /// + /// Number of nodes to reach the original resource. + /// + public byte Hops + { + get { return hops; } + internal set { hops = value; } + } - /// - /// Last modification date. - /// - public DateTime? ModificationDate - { - get - { - return instanceModificationDate; - } - } + /// + /// Last modification date. + /// + public DateTime? ModificationDate + { + get + { + return instanceModificationDate; + } + } - /// - /// Instance Id. - /// - public uint Id - { - get { return id; } - } + /// + /// Instance Id. + /// + public uint Id + { + get { return id; } + } - /// - /// Import properties from bytes array. - /// - /// - /// - public bool Deserialize(PropertyValue[] properties) - { - for (byte i = 0; i < properties.Length; i++) - { - var pt = this.definition.GetPropertyDefByIndex(i); - if (pt != null) - { - var pv = properties[i]; - LoadProperty(pt.Name, pv.Age, pv.Date, pv.Value); - } - } + /// + /// Import properties from bytes array. + /// + /// + /// + public bool Deserialize(PropertyValue[] properties) + { + for (byte i = 0; i < properties.Length; i++) + { + var pt = this.definition.GetPropertyDefByIndex(i); + if (pt != null) + { + var pv = properties[i]; + LoadProperty(pt.Name, pv.Age, pv.Date, pv.Value); + } + } - return true; - } + return true; + } - public string ToJson() - { - IResource res; - if (resource.TryGetTarget(out res)) - return JsonSerializer.Serialize(res, Global.SerializeOptions); - else - return null; - } + public string ToJson() + { + IResource res; + if (resource.TryGetTarget(out res)) + return JsonSerializer.Serialize(res, Global.SerializeOptions); + else + return null; + } - /// - /// Export all properties with ResourceProperty attributed as bytes array. - /// - /// - public PropertyValue[] Serialize() - { - IResource res; + /// + /// Export all properties with ResourceProperty attributed as bytes array. + /// + /// + public PropertyValue[] Serialize() + { + IResource res; - if (!resource.TryGetTarget(out res)) - throw new Exception("Resource no longer available."); + if (!resource.TryGetTarget(out res)) + throw new Exception("Resource no longer available."); - if (res is IDynamicResource dynamicResource) - return dynamicResource.SerializeResource(); + if (res is IDynamicResource dynamicResource) + return dynamicResource.SerializeResource(); - var props = new List(); + var props = new List(); - foreach (var pt in definition.Properties) - { - var rt = pt.PropertyInfo.GetValue(res, null); - props.Add(new PropertyValue(rt, ages[pt.Index], modificationDates[pt.Index])); - } + foreach (var pt in definition.Properties) + { + var rt = pt.PropertyInfo.GetValue(res, null); + props.Add(new PropertyValue(rt, ages[pt.Index], modificationDates[pt.Index])); + } - return props.ToArray(); - } + return props.ToArray(); + } - /// - /// Export all properties with ResourceProperty attributed as bytes array after a specific age. - /// - /// - public Map SerializeAfter(ulong age = 0) - { - IResource res; + /// + /// Export all properties with ResourceProperty attributed as bytes array after a specific age. + /// + /// + public Map SerializeAfter(ulong age = 0) + { + IResource res; - if (!resource.TryGetTarget(out res)) - throw new Exception("Resource no longer available."); + if (!resource.TryGetTarget(out res)) + throw new Exception("Resource no longer available."); - if (res is IDynamicResource dynamicResource) - return dynamicResource.SerializeResourceAfter(age); + if (res is IDynamicResource dynamicResource) + return dynamicResource.SerializeResourceAfter(age); - var props = new Map(); + var props = new Map(); - foreach (var pt in definition.Properties) - { - if (res.Instance.GetAge(pt.Index) > age) - { - var rt = pt.PropertyInfo.GetValue(res, null); - props.Add(pt.Index, - new PropertyValue(rt, - ages[pt.Index], - modificationDates[pt.Index])); - } - } + foreach (var pt in definition.Properties) + { + if (res.Instance.GetAge(pt.Index) > age) + { + var rt = pt.PropertyInfo.GetValue(res, null); + props.Add(pt.Index, + new PropertyValue(rt, + ages[pt.Index], + modificationDates[pt.Index])); + } + } - return props; - } + return props; + } - /// - /// If True, the instance can be stored to disk. - /// - /// - public bool IsStorable() - { + /// + /// If True, the instance can be stored to disk. + /// + /// + public bool IsStorable() + { #if NETSTANDARD - var attrs = resource.GetType().GetTypeInfo().GetCustomAttributes(typeof(Storable), true).ToArray(); + var attrs = resource.GetType().GetTypeInfo().GetCustomAttributes(typeof(Storable), true).ToArray(); #else var attrs = resource.GetType().GetCustomAttributes(typeof(Storable), true); #endif - return attrs.Length > 0; - - } - - - internal void EmitModification(PropertyDef pt, object value) - { - - IResource res; - if (this.resource.TryGetTarget(out res)) - { - instanceAge++; - var now = DateTime.UtcNow; - - ages[pt.Index] = instanceAge; - modificationDates[pt.Index] = now; - - if (pt.Recordable) - { - store.Record(res, pt.Name, value, ages[pt.Index], now); - } - else //if (pt.Storage == StorageMode.Recordable) - { - store.Modify(res, pt.Name, value, ages[pt.Index], now); - } - - //ResourceModified?.Invoke(res, pt.Name, value); - - PropertyModified?.Invoke(new PropertyModificationInfo(res, pt, value, instanceAge)); - } - } - - /// - /// Notify listeners that a property was modified. - /// - /// - /// - /// - public void Modified([CallerMemberName] string propertyName = "") - { - if (loading) - return; - - object value; - if (TryGetPropertyValue(propertyName, out value)) - { - var pt = definition.GetPropertyDefByName(propertyName); - EmitModification(pt, value); - } - } - - - - // internal void EmitResourceEvent(string name, string[] users, DistributedConnection[] connections, object[] args) - - internal void EmitCustomResourceEvent(object issuer, Func receivers, EventDef eventDef, object value) - { - IResource res; - if (this.resource.TryGetTarget(out res)) - { - CustomEventOccurred?.Invoke(new CustomEventOccurredInfo(res, eventDef, receivers, issuer, value)); - } - } - - internal void EmitResourceEvent(EventDef eventDef, object value) - { - IResource res; - if (this.resource.TryGetTarget(out res)) - { - EventOccurred?.Invoke(new EventOccurredInfo(res, eventDef, value)); - } - } - - internal void EmitResourceEventByIndex(byte eventIndex, object value) - { - IResource res; - if (this.resource.TryGetTarget(out res)) - { - var eventDef = definition.GetEventDefByIndex(eventIndex); - EventOccurred?.Invoke(new EventOccurredInfo(res, eventDef, value)); - } - } - - internal void EmitCustomResourceEventByIndex(object issuer, Func receivers, byte eventIndex, object value) - { - IResource res; - if (this.resource.TryGetTarget(out res)) - { - var eventDef = definition.GetEventDefByIndex(eventIndex); - CustomEventOccurred?.Invoke(new CustomEventOccurredInfo(res, eventDef, receivers, issuer, value)); - } - } - - - /// - /// Get the value of a given property by name. - /// - /// Property name - /// Output value - /// True, if the resource has the property. - public bool TryGetPropertyValue(string name, out object value) - { - var pt = definition.GetPropertyDefByName(name); - - IResource res; - if (resource.TryGetTarget(out res)) - { - if (res is IDynamicResource dynamicResource) - { - value = dynamicResource.GetResourceProperty(pt.Index); - return true; - } - else if (pt != null && pt.PropertyInfo != null) - { - value = pt.PropertyInfo.GetValue(res, null); - return true; - } - } - - value = null; - return false; - } - - public object GetPropertyValueOrDefault(string name, object defaultValue = null) - { - object value; - if (TryGetPropertyValue(name, out value)) - return value; - else - return defaultValue; - } - - /// - /// Store responsible for creating and keeping the resource. - /// - public IStore Store - { - get { return store; } - } - - public bool IsDestroyed { get; private set; } - - /// - /// The unique and permanent link to the resource. - /// - public string Link - { - get - { - IResource res; - if (this.resource.TryGetTarget(out res)) - { - if (res == res.Instance.store) - return name; // root store - else - return store.Instance.name + "/" + store.Link(res); - } - else - return null; - } - } - - public AsyncBag Children(string name = null) where T : IResource - { - IResource res; - if (this.resource.TryGetTarget(out res)) - { - return store.Children(res, name); - } - else - return new AsyncBag(null); - } - - public AsyncBag Parents(string name = null) where T : IResource - { - IResource res; - if (this.resource.TryGetTarget(out res)) - { - return store.Parents(res, name); - } - else - return new AsyncBag(default(T[])); - } - - - /// - /// Instance name. - /// - public string Name - { - get { return name; } - set { name = value; } - } - - - /// - /// Resource managed by this instance. - /// - public IResource Resource - { - get - { - IResource res; - if (this.resource.TryGetTarget(out res)) - { - return res; - } - else - return null; - } - } - - /// - /// Resource template describes the properties, functions and events of the resource. - /// - public TypeDef Definition - { - get { return definition; } - - /* - internal set - { - template = Warehouse.GetTemplate(resource.GetType()); - - // set ages - for (byte i = 0; i < template.Properties.Length; i++) - { - ages.Add(0); - modificationDates.Add(DateTime.MinValue); - } - } - */ - } - - /// - /// Check for permission. - /// - /// Caller sessions. - /// Action type - /// Function, property or event to check for permission. - /// Permission inquirer. - /// Ruling. - public Ruling Applicable(Session session, ActionType action, MemberDef member, object inquirer = null) - { - IResource res; - if (this.resource.TryGetTarget(out res)) - { - //return store.Applicable(res, session, action, member, inquirer); - - foreach (IPermissionsManager manager in managers) - { - var r = manager.Applicable(res, session, action, member, inquirer); - if (r != Ruling.DontCare) - return r; - } - - } - - return Ruling.DontCare; - - } - - /// - /// Execution managers. - /// - public AutoList Managers => managers; - - public readonly Warehouse Warehouse; - /// - /// Create new instance. - /// - /// Instance Id. - /// Name of the instance. - /// Resource to manage. - /// Store responsible for the resource. - public Instance(Warehouse warehouse, uint id, string name, IResource resource, IStore store, ulong age = 0) - { - this.Warehouse = warehouse; - this.store = store; - this.resource = new WeakReference(resource); - this.id = id; - this.name = name ?? ""; - this.instanceAge = age; - - //this.attributes = new KeyList(this); - //children = new AutoList(this); - //parents = new AutoList(this); - managers = new AutoList(this); - //children.OnAdd += Children_OnAdd; - //children.OnRemoved += Children_OnRemoved; - //parents.OnAdd += Parents_OnAdd; - //parents.OnRemoved += Parents_OnRemoved; - - resource.OnDestroy += Resource_OnDestroy; - - if (resource is IDynamicResource dynamicResource) - { - this.definition = dynamicResource.ResourceDefinition; - } - else - { - this.definition = Warehouse.GetTemplateByType(resource.GetType()); - } - - // set ages - for (byte i = 0; i < definition.Properties.Length; i++) - { - ages.Add(0); - modificationDates.Add(DateTime.MinValue); - } - - - // connect events - if (!(resource is DistributedResource)) - { - - Type t = ResourceProxy.GetBaseType(resource); - - var events = t.GetTypeInfo().GetEvents(BindingFlags.Public | BindingFlags.Instance); - - var emitEventByIndexMethod = GetType().GetMethod("EmitResourceEventByIndex", BindingFlags.Instance | BindingFlags.NonPublic); - var emitCustomEventByIndexMethod = GetType().GetMethod("EmitCustomResourceEventByIndex", BindingFlags.Instance | BindingFlags.NonPublic); - - foreach (var evt in definition.Events) - { - - if (evt.EventInfo == null) - continue; - - var eventGenericType = evt.EventInfo.EventHandlerType.GetGenericTypeDefinition(); - - if (eventGenericType == typeof(ResourceEventHandler<>)) - { - - var dm = new DynamicMethod("_", null, - new Type[] { typeof(Instance), evt.EventInfo.EventHandlerType.GenericTypeArguments[0] }, - typeof(Instance).Module, true); - - - var il = dm.GetILGenerator(); - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldc_I4, (int)evt.Index); - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Box, evt.EventInfo.EventHandlerType.GenericTypeArguments[0]); - il.Emit(OpCodes.Callvirt, emitEventByIndexMethod); - il.Emit(OpCodes.Nop); - il.Emit(OpCodes.Ret); - + return attrs.Length > 0; + + } + + + internal void EmitModification(PropertyDef pt, object value) + { + + IResource res; + if (this.resource.TryGetTarget(out res)) + { + instanceAge++; + var now = DateTime.UtcNow; + + ages[pt.Index] = instanceAge; + modificationDates[pt.Index] = now; + + //if (pt.HasHistory) + //{ + // store.Record(res, pt.Name, value, ages[pt.Index], now); + //} + //else //if (pt.Storage == StorageMode.Recordable) + //{ + store.Modify(res, pt, value, ages[pt.Index], now); + //} + + //ResourceModified?.Invoke(res, pt.Name, value); + + PropertyModified?.Invoke(new PropertyModificationInfo(res, pt, value, instanceAge)); + } + } + + /// + /// Notify listeners that a property was modified. + /// + /// + /// + /// + public void Modified([CallerMemberName] string propertyName = "") + { + if (loading) + return; + + object value; + if (TryGetPropertyValue(propertyName, out value)) + { + var pt = definition.GetPropertyDefByName(propertyName); + EmitModification(pt, value); + } + } + + + + // internal void EmitResourceEvent(string name, string[] users, EpConnection[] connections, object[] args) + + internal void EmitCustomResourceEvent(object issuer, Func receivers, EventDef eventDef, object value) + { + IResource res; + if (this.resource.TryGetTarget(out res)) + { + CustomEventOccurred?.Invoke(new CustomEventOccurredInfo(res, eventDef, receivers, issuer, value)); + } + } + + internal void EmitResourceEvent(EventDef eventDef, object value) + { + IResource res; + if (this.resource.TryGetTarget(out res)) + { + EventOccurred?.Invoke(new EventOccurredInfo(res, eventDef, value)); + } + } + + internal void EmitResourceEventByIndex(byte eventIndex, object value) + { + IResource res; + if (this.resource.TryGetTarget(out res)) + { + var eventDef = definition.GetEventDefByIndex(eventIndex); + EventOccurred?.Invoke(new EventOccurredInfo(res, eventDef, value)); + } + } + + internal void EmitCustomResourceEventByIndex(object issuer, Func receivers, byte eventIndex, object value) + { + IResource res; + if (this.resource.TryGetTarget(out res)) + { + var eventDef = definition.GetEventDefByIndex(eventIndex); + CustomEventOccurred?.Invoke(new CustomEventOccurredInfo(res, eventDef, receivers, issuer, value)); + } + } + + + /// + /// Get the value of a given property by name. + /// + /// Property name + /// Output value + /// True, if the resource has the property. + public bool TryGetPropertyValue(string name, out object value) + { + var pt = definition.GetPropertyDefByName(name); + + IResource res; + if (resource.TryGetTarget(out res)) + { + if (res is IDynamicResource dynamicResource) + { + value = dynamicResource.GetResourceProperty(pt.Index); + return true; + } + else if (pt != null && pt.PropertyInfo != null) + { + value = pt.PropertyInfo.GetValue(res, null); + return true; + } + } + + value = null; + return false; + } + + public object GetPropertyValueOrDefault(string name, object defaultValue = null) + { + object value; + if (TryGetPropertyValue(name, out value)) + return value; + else + return defaultValue; + } + + /// + /// Store responsible for creating and keeping the resource. + /// + public IStore Store + { + get { return store; } + } + + public bool IsDestroyed { get; private set; } + + /// + /// The unique and permanent link to the resource. + /// + public string Link + { + get + { + IResource res; + if (this.resource.TryGetTarget(out res)) + { + if (res == res.Instance.store) + return name; // root store + else + return store.Instance.name + "/" + store.Link(res); + } + else + return null; + } + } + + public AsyncBag Children(string name = null) where T : IResource + { + IResource res; + if (this.resource.TryGetTarget(out res)) + { + return store.Children(res, name); + } + else + return new AsyncBag(null); + } + + public AsyncBag Parents(string name = null) where T : IResource + { + IResource res; + if (this.resource.TryGetTarget(out res)) + { + return store.Parents(res, name); + } + else + return new AsyncBag(default(T[])); + } + + + /// + /// Instance name. + /// + public string Name + { + get { return name; } + set { name = value; } + } + + + /// + /// Resource managed by this instance. + /// + public IResource Resource + { + get + { + IResource res; + if (this.resource.TryGetTarget(out res)) + { + return res; + } + else + return null; + } + } + + /// + /// Resource TypeDef describes the properties, functions and events of the resource. + /// + public TypeDef Definition + { + get { return definition; } + + } + + /// + /// Check for permission. + /// + /// Caller sessions. + /// Action type + /// Function, property or event to check for permission. + /// Permission inquirer. + /// Ruling. + public Ruling Applicable(Session session, ActionType action, MemberDef member, object inquirer = null) + { + IResource res; + if (this.resource.TryGetTarget(out res)) + { + //return store.Applicable(res, session, action, member, inquirer); + + foreach (IPermissionsManager manager in managers) + { + var r = manager.Applicable(res, session, action, member, inquirer); + if (r != Ruling.DontCare) + return r; + } + + } + + return Ruling.DontCare; + + } + + /// + /// Execution managers. + /// + public AutoList Managers => managers; + + public readonly Warehouse Warehouse; + /// + /// Create new instance. + /// + /// Instance Id. + /// Name of the instance. + /// Resource to manage. + /// Store responsible for the resource. + public Instance(Warehouse warehouse, uint id, string name, IResource resource, IStore store, ulong age = 0) + { + this.Warehouse = warehouse; + this.store = store; + this.resource = new WeakReference(resource); + this.id = id; + this.name = name ?? ""; + this.instanceAge = age; + + //this.attributes = new KeyList(this); + //children = new AutoList(this); + //parents = new AutoList(this); + managers = new AutoList(this); + //children.OnAdd += Children_OnAdd; + //children.OnRemoved += Children_OnRemoved; + //parents.OnAdd += Parents_OnAdd; + //parents.OnRemoved += Parents_OnRemoved; + + resource.OnDestroy += Resource_OnDestroy; + + if (resource is IDynamicResource dynamicResource) + { + this.definition = dynamicResource.ResourceDefinition; + } + else + { + this.definition = Warehouse.GetTypeDefByType(resource.GetType()); + } + + // set ages + for (byte i = 0; i < definition.Properties.Length; i++) + { + ages.Add(0); + modificationDates.Add(DateTime.MinValue); + } + + + // connect events + if (!(resource is EpResource)) + { + + Type t = ResourceProxy.GetBaseType(resource); + + var events = t.GetTypeInfo().GetEvents(BindingFlags.Public | BindingFlags.Instance); + + var emitEventByIndexMethod = GetType().GetMethod("EmitResourceEventByIndex", BindingFlags.Instance | BindingFlags.NonPublic); + var emitCustomEventByIndexMethod = GetType().GetMethod("EmitCustomResourceEventByIndex", BindingFlags.Instance | BindingFlags.NonPublic); + + foreach (var evt in definition.Events) + { + + if (evt.EventInfo == null) + continue; + + var eventGenericType = evt.EventInfo.EventHandlerType.GetGenericTypeDefinition(); + + if (eventGenericType == typeof(ResourceEventHandler<>)) + { + + var dm = new DynamicMethod("_", null, + new Type[] { typeof(Instance), evt.EventInfo.EventHandlerType.GenericTypeArguments[0] }, + typeof(Instance).Module, true); + + + var il = dm.GetILGenerator(); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldc_I4, (int)evt.Index); + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Box, evt.EventInfo.EventHandlerType.GenericTypeArguments[0]); + il.Emit(OpCodes.Callvirt, emitEventByIndexMethod); + il.Emit(OpCodes.Nop); + il.Emit(OpCodes.Ret); + - var proxyDelegate = dm.CreateDelegate(evt.EventInfo.EventHandlerType, this); - - //ResourceEventHandler proxyDelegate = new ResourceEventHandler((args) => EmitResourceEvent(evt, args)); - evt.EventInfo.AddEventHandler(resource, proxyDelegate); + var proxyDelegate = dm.CreateDelegate(evt.EventInfo.EventHandlerType, this); + + //ResourceEventHandler proxyDelegate = new ResourceEventHandler((args) => EmitResourceEvent(evt, args)); + evt.EventInfo.AddEventHandler(resource, proxyDelegate); - } - else if (eventGenericType == typeof(CustomResourceEventHandler<>)) - { - var dm = new DynamicMethod("_", null, - new Type[] { typeof(Instance), typeof(object), typeof(Func), - evt.EventInfo.EventHandlerType.GenericTypeArguments[0] }, - typeof(Instance).Module, true); - - - var il = dm.GetILGenerator(); - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Ldarg_2); - il.Emit(OpCodes.Ldc_I4, (int)evt.Index); - il.Emit(OpCodes.Ldarg_3); - il.Emit(OpCodes.Box, evt.EventInfo.EventHandlerType.GenericTypeArguments[0]); - il.Emit(OpCodes.Callvirt, emitCustomEventByIndexMethod); - il.Emit(OpCodes.Nop); - il.Emit(OpCodes.Ret); + } + else if (eventGenericType == typeof(CustomResourceEventHandler<>)) + { + var dm = new DynamicMethod("_", null, + new Type[] { typeof(Instance), typeof(object), typeof(Func), + evt.EventInfo.EventHandlerType.GenericTypeArguments[0] }, + typeof(Instance).Module, true); + + + var il = dm.GetILGenerator(); + il.Emit(OpCodes.Ldarg_0); + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Ldarg_2); + il.Emit(OpCodes.Ldc_I4, (int)evt.Index); + il.Emit(OpCodes.Ldarg_3); + il.Emit(OpCodes.Box, evt.EventInfo.EventHandlerType.GenericTypeArguments[0]); + il.Emit(OpCodes.Callvirt, emitCustomEventByIndexMethod); + il.Emit(OpCodes.Nop); + il.Emit(OpCodes.Ret); - var proxyDelegate = dm.CreateDelegate(evt.EventInfo.EventHandlerType, this); + var proxyDelegate = dm.CreateDelegate(evt.EventInfo.EventHandlerType, this); - evt.EventInfo.AddEventHandler(resource, proxyDelegate); - } + evt.EventInfo.AddEventHandler(resource, proxyDelegate); + } - } + } - } - } + } + } - private void Resource_OnDestroy(object sender) - { - IsDestroyed = true; - Destroyed?.Invoke((IResource)sender); - } + private void Resource_OnDestroy(object sender) + { + IsDestroyed = true; + Destroyed?.Invoke((IResource)sender); + } } diff --git a/Esiur/Resource/ResourceEventHandler.cs b/Esiur/Resource/ResourceEventHandler.cs index c537f50..378ccf3 100644 --- a/Esiur/Resource/ResourceEventHandler.cs +++ b/Esiur/Resource/ResourceEventHandler.cs @@ -23,7 +23,6 @@ SOFTWARE. */ using Esiur.Data; using Esiur.Core; -using Esiur.Net.IIP; using Esiur.Security.Authority; using System; using System.Collections.Generic; @@ -37,10 +36,10 @@ namespace Esiur.Resource; public delegate void ResourceEventHandler(T argument);//where T : class; // public delegate void CustomUsersEventHanlder(string[] usernames, params object[] args); -//public delegate void CustomReceiversEventHanlder(DistributedConnection[] connections, params object[] args); +//public delegate void CustomReceiversEventHanlder(EpConnection[] connections, params object[] args); //public delegate void CustomInquirerEventHanlder(object inquirer, params object[] args); public delegate void CustomResourceEventHandler(object issuer, Func receivers, T argument);// object issuer, Session[] receivers, params object[] args); -// public delegate void CustomReceiversEventHanlder(string[] usernames, DistributedConnection[] connections, params object[] args); +// public delegate void CustomReceiversEventHanlder(string[] usernames, EpConnection[] connections, params object[] args); diff --git a/Esiur/Resource/StorageMode.cs b/Esiur/Resource/StorageMode.cs index ba8e5cb..347d273 100644 --- a/Esiur/Resource/StorageMode.cs +++ b/Esiur/Resource/StorageMode.cs @@ -7,5 +7,5 @@ public enum StorageMode : byte { NonVolatile, Volatile, - Recordable + History } diff --git a/Esiur/Resource/StoreGeneric.cs b/Esiur/Resource/StoreGeneric.cs index 0fcfb5a..e2cb13b 100644 --- a/Esiur/Resource/StoreGeneric.cs +++ b/Esiur/Resource/StoreGeneric.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Text; using Esiur.Core; using Esiur.Data; -using Esiur.Data.Schema; +using Esiur.Data.Types; namespace Esiur.Resource; public abstract class Store : IStore where T : IResource @@ -23,12 +23,12 @@ public abstract class Store : IStore where T : IResource public abstract AsyncReply Get(string path); - public abstract AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate); + public abstract AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate); public abstract string Link(IResource resource); - public abstract bool Modify(IResource resource, string propertyName, object value, ulong? age, DateTime? dateTime); + public abstract bool Modify(IResource resource, PropertyDef propertyDef, object value, ulong? age, DateTime? dateTime); public abstract AsyncReply Put(IResource resource, string path); diff --git a/Esiur/Resource/Warehouse.cs b/Esiur/Resource/Warehouse.cs index 233ec9d..ec7be16 100644 --- a/Esiur/Resource/Warehouse.cs +++ b/Esiur/Resource/Warehouse.cs @@ -26,8 +26,8 @@ using Esiur.Core; using Esiur.Data; using Esiur.Data.Types; using Esiur.Misc; -using Esiur.Net.IIP; using Esiur.Net.Packets; +using Esiur.Protocol; using Esiur.Proxy; using Esiur.Security.Permissions; using System; @@ -59,13 +59,11 @@ public class Warehouse uint resourceCounter = 0; - KeyList> schemas + KeyList> typeDefs = new KeyList>() { - //[TemplateType.Unspecified] = new KeyList(), [TypeDefKind.Resource] = new KeyList(), [TypeDefKind.Record] = new KeyList(), - //[TemplateType.Wrapper] = new KeyList(), [TypeDefKind.Enum] = new KeyList(), }; @@ -84,14 +82,14 @@ public class Warehouse public Warehouse() { - Protocols.Add("iip", + Protocols.Add("EP", async (name, attributes) - => await New(name, null, attributes)); + => await New(name, null, attributes)); - new TypeDef(typeof(IIPAuthPacketIAuthHeader), this); + new TypeDef(typeof(EpAuthPacketIAuthHeader), this); - new TypeDef(typeof(IIPAuthPacketIAuthDestination), this); - new TypeDef(typeof(IIPAuthPacketIAuthFormat), this); + new TypeDef(typeof(EpAuthPacketIAuthDestination), this); + new TypeDef(typeof(EpAuthPacketIAuthFormat), this); } @@ -139,19 +137,19 @@ public class Warehouse var resourceTypes = (Type[])generatedType.GetProperty("Resources").GetValue(null); foreach (var t in resourceTypes) { - RegisterSchema(new TypeDef(t)); + RegisterTypeDef(new TypeDef(t)); } var recordTypes = (Type[])generatedType.GetProperty("Records").GetValue(null); foreach (var t in recordTypes) { - RegisterSchema(new TypeDef(t)); + RegisterTypeDef(new TypeDef(t)); } var enumsTypes = (Type[])generatedType.GetProperty("Enums").GetValue(null); foreach (var t in enumsTypes) { - RegisterSchema(new TypeDef(t)); + RegisterTypeDef(new TypeDef(t)); } } } @@ -339,86 +337,6 @@ public class Warehouse } - /// - /// Put a resource in the warehouse. - /// - /// Resource name. - /// Resource instance. - /// IStore that manages the resource. Can be null if the resource is a store. - /// Parent resource. if not presented the store becomes the parent for the resource. - //public async AsyncReply Put(string instanceName, T resource, IStore store, TypeSchema customTemplate = null, ulong age = 0, IPermissionsManager manager = null, object attributes = null) where T : IResource - //{ - // if (resource.Instance != null) - // throw new Exception("Resource has a store."); - - - // var resourceReference = new WeakReference(resource); - - - // if (resource is IStore && store == null) - // store = (IStore)resource; - - // if (store == null) - // throw new Exception("Resource store is not set."); - - - // resource.Instance = new Instance(this, resourceCounter++, instanceName, resource, store, customTemplate, age); - - // if (attributes != null) - // if (attributes is Map attrs) - // resource.Instance.SetAttributes(attrs); - // else - // resource.Instance.SetAttributes(Map.FromObject(attributes)); - - // if (manager != null) - // resource.Instance.Managers.Add(manager); - - // //if (store == parent) - // // parent = null; - - - // try - // { - // if (resource is IStore) - // stores.TryAdd(resource as IStore, new List>()); - - - // if (!await store.Put(resource)) - // throw new Exception("Store failed to put the resource"); - // //return default(T); - - - // //if (parent != null) - // //{ - // // await parent.Instance.Store.AddChild(parent, resource); - // // await store.AddParent(resource, parent); - // //} - - // var t = resource.GetType(); - // Global.Counters["T-" + t.Namespace + "." + t.Name]++; - - // resources.TryAdd(resource.Instance.Id, resourceReference); - - // if (warehouseIsOpen) - // { - // await resource.Trigger(ResourceTrigger.Initialize); - // if (resource is IStore) - // await resource.Trigger(ResourceTrigger.Open); - // } - - // if (resource is IStore) - // StoreConnected?.Invoke(resource as IStore); - // } - // catch (Exception ex) - // { - // Remove(resource); - // throw ex; - // } - - // return resource; - - //} - /// /// Put a resource in the warehouse. /// @@ -525,9 +443,9 @@ public class Warehouse { if (properties is Map map) { - var template = GetTemplateByType(type); + var typeDef = GetTypeDefByType(type); foreach (var kvp in map) - template.GetPropertyDefByIndex(kvp.Key).PropertyInfo.SetValue(res, kvp.Value); + typeDef.GetPropertyDefByIndex(kvp.Key).PropertyInfo.SetValue(res, kvp.Value); } else { @@ -587,22 +505,22 @@ public class Warehouse /// /// Put a resource schema in the schemas warehouse. /// - /// Resource schema. - public void RegisterSchema(TypeDef typeDef) + /// Resource type definition. + public void RegisterTypeDef(TypeDef typeDef) { - if (schemas[typeDef.Kind].ContainsKey(typeDef.Id)) - throw new Exception($"Template with same class Id already exists. {schemas[typeDef.Kind][typeDef.Id].Name} -> {typeDef.Name}"); + if (typeDefs[typeDef.Kind].ContainsKey(typeDef.Id)) + throw new Exception($"TypeDef with same class Id already exists. {typeDefs[typeDef.Kind][typeDef.Id].Name} -> {typeDef.Name}"); - schemas[typeDef.Kind][typeDef.Id] = typeDef; + typeDefs[typeDef.Kind][typeDef.Id] = typeDef; } - /// - /// Get a template by type from the templates warehouse. If not in the warehouse, a new ResourceTemplate is created and added to the warehouse. - /// - /// .Net type. - /// Resource template. - public TypeDef GetTemplateByType(Type type) + /// + /// Get a TypeDef by type from the typeDefs warehouse. If not in the warehouse, a new ResourceTemplate is created and added to the warehouse. + /// + /// .Net type. + /// Resource template. + public TypeDef GetTypeDefByType(Type type) { if (!(type.IsClass || type.IsEnum)) return null; @@ -623,7 +541,7 @@ public class Warehouse else return null; - var schema = schemas[schemaKind].Values.FirstOrDefault(x => x.DefinedType == baseType); + var schema = typeDefs[schemaKind].Values.FirstOrDefault(x => x.DefinedType == baseType); if (schema != null) return schema; @@ -644,27 +562,22 @@ public class Warehouse if (templateType == null) { // look into resources - var template = schemas[TypeDefKind.Resource][typeId]; + var template = typeDefs[TypeDefKind.Resource][typeId]; if (template != null) return template; // look into records - template = schemas[TypeDefKind.Record][typeId]; + template = typeDefs[TypeDefKind.Record][typeId]; if (template != null) return template; // look into enums - template = schemas[TypeDefKind.Enum][typeId]; + template = typeDefs[TypeDefKind.Enum][typeId]; return template; - //if (template != null) - - - //// look in wrappers - //template = templates[TemplateType.Wrapper][classId]; - //return template; + } else - return schemas[templateType.Value][typeId]; + return typeDefs[templateType.Value][typeId]; } @@ -673,32 +586,28 @@ public class Warehouse /// /// Class name. /// Resource template. - public TypeDef GetTypeDfByName(string typeName, TypeDefKind? templateType = null) + public TypeDef GetTypeDefByName(string typeName, TypeDefKind? typeDefKind = null) { - if (templateType == null) + if (typeDefKind == null) { // look into resources - var template = schemas[TypeDefKind.Resource].Values.FirstOrDefault(x => x.Name == typeName); - if (template != null) - return template; + var typeDef = typeDefs[TypeDefKind.Resource].Values.FirstOrDefault(x => x.Name == typeName); + if (typeDef != null) + return typeDef; // look into records - template = schemas[TypeDefKind.Record].Values.FirstOrDefault(x => x.Name == typeName); - if (template != null) - return template; + typeDef = typeDefs[TypeDefKind.Record].Values.FirstOrDefault(x => x.Name == typeName); + if (typeDef != null) + return typeDef; // look into enums - template = schemas[TypeDefKind.Enum].Values.FirstOrDefault(x => x.Name == typeName); - //if (template != null) - return template; - - //// look in wrappers - //template = templates[TemplateType.Wrapper].Values.FirstOrDefault(x => x.ClassName == className); - //return template; + typeDef = typeDefs[TypeDefKind.Enum].Values.FirstOrDefault(x => x.Name == typeName); + return typeDef; + } else { - return schemas[templateType.Value].Values.FirstOrDefault(x => x.Name == typeName); + return typeDefs[typeDefKind.Value].Values.FirstOrDefault(x => x.Name == typeName); } } diff --git a/Esiur/Security/Authority/Authentication.cs b/Esiur/Security/Authority/Authentication.cs index cb1762c..ba31855 100644 --- a/Esiur/Security/Authority/Authentication.cs +++ b/Esiur/Security/Authority/Authentication.cs @@ -27,7 +27,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using static Esiur.Net.Packets.IIPAuthPacket; namespace Esiur.Security.Authority; diff --git a/Esiur/Security/Authority/Session.cs b/Esiur/Security/Authority/Session.cs index 92ea867..cc387af 100644 --- a/Esiur/Security/Authority/Session.cs +++ b/Esiur/Security/Authority/Session.cs @@ -48,8 +48,8 @@ public class Session public ISymetricCipher SymetricCipher { get; set; } = null; - public Map LocalHeaders { get; set; } = new Map(); - public Map RemoteHeaders { get; set; } = new Map(); + public Map LocalHeaders { get; set; } = new Map(); + public Map RemoteHeaders { get; set; } = new Map(); public AuthenticationMethod LocalMethod { get; set; } public AuthenticationMethod RemoteMethod { get; set; } diff --git a/Esiur/Security/Membership/AuthorizationRequest.cs b/Esiur/Security/Membership/AuthorizationRequest.cs index 1fe406b..3352af2 100644 --- a/Esiur/Security/Membership/AuthorizationRequest.cs +++ b/Esiur/Security/Membership/AuthorizationRequest.cs @@ -11,10 +11,10 @@ namespace Esiur.Security.Membership public class AuthorizationRequest { public uint Reference { get; set; } - public IIPAuthPacketIAuthDestination Destination { get; set; } + public EpAuthPacketIAuthDestination Destination { get; set; } public string Clue { get; set; } - public IIPAuthPacketIAuthFormat? RequiredFormat { get; set; } - public IIPAuthPacketIAuthFormat? ContentFormat { get; set; } + public EpAuthPacketIAuthFormat? RequiredFormat { get; set; } + public EpAuthPacketIAuthFormat? ContentFormat { get; set; } public object? Content { get; set; } public byte? Trials { get; set; } @@ -24,29 +24,29 @@ namespace Esiur.Security.Membership public int Timeout => Expire.HasValue && Issue.HasValue ? (int)(Expire.Value - Issue.Value).TotalSeconds : 0; - public AuthorizationRequest(Map headers) + public AuthorizationRequest(Map headers) { - Reference = (uint)headers[IIPAuthPacketIAuthHeader.Reference]; - Destination =(IIPAuthPacketIAuthDestination)headers[IIPAuthPacketIAuthHeader.Destination]; - Clue = (string)headers[IIPAuthPacketIAuthHeader.Clue]; + Reference = (uint)headers[EpAuthPacketIAuthHeader.Reference]; + Destination =(EpAuthPacketIAuthDestination)headers[EpAuthPacketIAuthHeader.Destination]; + Clue = (string)headers[EpAuthPacketIAuthHeader.Clue]; - if (headers.ContainsKey(IIPAuthPacketIAuthHeader.RequiredFormat)) - RequiredFormat = (IIPAuthPacketIAuthFormat)headers[IIPAuthPacketIAuthHeader.RequiredFormat]; + if (headers.ContainsKey(EpAuthPacketIAuthHeader.RequiredFormat)) + RequiredFormat = (EpAuthPacketIAuthFormat)headers[EpAuthPacketIAuthHeader.RequiredFormat]; - if (headers.ContainsKey(IIPAuthPacketIAuthHeader.ContentFormat)) - ContentFormat = (IIPAuthPacketIAuthFormat)headers[IIPAuthPacketIAuthHeader.ContentFormat]; + if (headers.ContainsKey(EpAuthPacketIAuthHeader.ContentFormat)) + ContentFormat = (EpAuthPacketIAuthFormat)headers[EpAuthPacketIAuthHeader.ContentFormat]; - if (headers.ContainsKey(IIPAuthPacketIAuthHeader.Content)) - Content = headers[IIPAuthPacketIAuthHeader.Content]; + if (headers.ContainsKey(EpAuthPacketIAuthHeader.Content)) + Content = headers[EpAuthPacketIAuthHeader.Content]; - if (headers.ContainsKey(IIPAuthPacketIAuthHeader.Trials)) - Trials = (byte)headers[IIPAuthPacketIAuthHeader.Trials]; + if (headers.ContainsKey(EpAuthPacketIAuthHeader.Trials)) + Trials = (byte)headers[EpAuthPacketIAuthHeader.Trials]; - if (headers.ContainsKey(IIPAuthPacketIAuthHeader.Issue)) - Issue = (DateTime)headers[IIPAuthPacketIAuthHeader.Issue]; + if (headers.ContainsKey(EpAuthPacketIAuthHeader.Issue)) + Issue = (DateTime)headers[EpAuthPacketIAuthHeader.Issue]; - if (headers.ContainsKey(IIPAuthPacketIAuthHeader.Expire)) - Expire = (DateTime)headers[IIPAuthPacketIAuthHeader.Expire]; + if (headers.ContainsKey(EpAuthPacketIAuthHeader.Expire)) + Expire = (DateTime)headers[EpAuthPacketIAuthHeader.Expire]; } } } diff --git a/Esiur/Security/Membership/AuthorizationResults.cs b/Esiur/Security/Membership/AuthorizationResults.cs index f205b47..6dc779a 100644 --- a/Esiur/Security/Membership/AuthorizationResults.cs +++ b/Esiur/Security/Membership/AuthorizationResults.cs @@ -13,10 +13,10 @@ namespace Esiur.Security.Membership public uint Reference { get; set; } - public IIPAuthPacketIAuthDestination Destination { get; set; } + public EpAuthPacketIAuthDestination Destination { get; set; } public string? Clue { get; set; } - public IIPAuthPacketIAuthFormat? RequiredFormat { get; set; } - public IIPAuthPacketIAuthFormat? ContentFormat { get; set; } + public EpAuthPacketIAuthFormat? RequiredFormat { get; set; } + public EpAuthPacketIAuthFormat? ContentFormat { get; set; } public object? Content { get; set; } public byte? Trials { get; set; } diff --git a/Esiur/Security/Membership/IMembership.cs b/Esiur/Security/Membership/IMembership.cs index 7bf2126..2ab51d6 100644 --- a/Esiur/Security/Membership/IMembership.cs +++ b/Esiur/Security/Membership/IMembership.cs @@ -28,7 +28,6 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Esiur.Data; -using Esiur.Net.IIP; using Esiur.Core; using Esiur.Security.Authority; using Esiur.Resource; @@ -47,8 +46,8 @@ public interface IMembership AsyncReply GetToken(ulong tokenIndex, string domain); AsyncReply Authorize(Session session); AsyncReply AuthorizePlain(Session session, uint reference, object value); - AsyncReply AuthorizeHashed(Session session, uint reference, IIPAuthPacketHashAlgorithm algorithm, byte[] value); - AsyncReply AuthorizeEncrypted(Session session, uint reference, IIPAuthPacketPublicKeyAlgorithm algorithm, byte[] value); + AsyncReply AuthorizeHashed(Session session, uint reference, EpAuthPacketHashAlgorithm algorithm, byte[] value); + AsyncReply AuthorizeEncrypted(Session session, uint reference, EpAuthPacketPublicKeyAlgorithm algorithm, byte[] value); AsyncReply Login(Session session); AsyncReply Logout(Session session); diff --git a/Esiur/Security/Membership/SimpleMembership.cs b/Esiur/Security/Membership/SimpleMembership.cs index b430782..04cfbcb 100644 --- a/Esiur/Security/Membership/SimpleMembership.cs +++ b/Esiur/Security/Membership/SimpleMembership.cs @@ -79,7 +79,7 @@ namespace Esiur.Security.Membership var ar = new AuthorizationResults() { Clue = q.Question, - Destination = IIPAuthPacketIAuthDestination.Self, + Destination = EpAuthPacketIAuthDestination.Self, Reference = (uint)r.Next(), RequiredFormat = format, Expire = DateTime.Now.AddSeconds(60), @@ -96,14 +96,14 @@ namespace Esiur.Security.Membership } } - public AsyncReply AuthorizeEncrypted(Session session, uint reference, IIPAuthPacketPublicKeyAlgorithm algorithm, byte[] value) + public AsyncReply AuthorizeEncrypted(Session session, uint reference, EpAuthPacketPublicKeyAlgorithm algorithm, byte[] value) { throw new NotImplementedException(); } - public AsyncReply AuthorizeHashed(Session session, uint reference, IIPAuthPacketHashAlgorithm algorithm, byte[] value) + public AsyncReply AuthorizeHashed(Session session, uint reference, EpAuthPacketHashAlgorithm algorithm, byte[] value) { - if (algorithm != IIPAuthPacketHashAlgorithm.SHA256) + if (algorithm != EpAuthPacketHashAlgorithm.SHA256) throw new NotImplementedException(); var ar = users[session.AuthorizedAccount].Results.First(x => x.Reference == reference); @@ -112,8 +112,8 @@ namespace Esiur.Security.Membership // compute hash - var remoteNonce = (byte[])session.RemoteHeaders[IIPAuthPacketHeader.Nonce]; - var localNonce = (byte[])session.LocalHeaders[IIPAuthPacketHeader.Nonce]; + var remoteNonce = (byte[])session.RemoteHeaders[EpAuthPacketHeader.Nonce]; + var localNonce = (byte[])session.LocalHeaders[EpAuthPacketHeader.Nonce]; var hashFunc = SHA256.Create(); // local nonce + password or token + remote nonce diff --git a/Esiur/Security/Permissions/StorePermissionsManager.cs b/Esiur/Security/Permissions/StorePermissionsManager.cs index 2de2350..8478680 100644 --- a/Esiur/Security/Permissions/StorePermissionsManager.cs +++ b/Esiur/Security/Permissions/StorePermissionsManager.cs @@ -29,7 +29,7 @@ using Esiur.Data; using Esiur.Core; using Esiur.Resource; using Esiur.Security.Authority; -using Esiur.Data.Schema; +using Esiur.Data.Types; namespace Esiur.Security.Permissions; @@ -39,7 +39,7 @@ public class StorePermissionsManager : IPermissionsManager public Map Settings => settings; - public Ruling Applicable(IResource resource, Session session, ActionType action, MemberDefinition member, object inquirer = null) + public Ruling Applicable(IResource resource, Session session, ActionType action, MemberDef member, object inquirer = null) { return resource.Instance.Store.Instance.Applicable(session, action, member, inquirer); } diff --git a/Esiur/Security/Permissions/UserPermissionsManager.cs b/Esiur/Security/Permissions/UserPermissionsManager.cs index fa8ed64..075da3e 100644 --- a/Esiur/Security/Permissions/UserPermissionsManager.cs +++ b/Esiur/Security/Permissions/UserPermissionsManager.cs @@ -29,7 +29,7 @@ using Esiur.Data; using Esiur.Core; using Esiur.Resource; using Esiur.Security.Authority; -using Esiur.Data.Schema; +using Esiur.Data.Types; namespace Esiur.Security.Permissions; @@ -40,7 +40,7 @@ public class UserPermissionsManager : IPermissionsManager public Map Settings => settings; - public Ruling Applicable(IResource resource, Session session, ActionType action, MemberDefinition member, object inquirer) + public Ruling Applicable(IResource resource, Session session, ActionType action, MemberDef member, object inquirer) { Map userPermissions = null; diff --git a/Esiur/Stores/MemoryStore.cs b/Esiur/Stores/MemoryStore.cs index d561620..609cda6 100644 --- a/Esiur/Stores/MemoryStore.cs +++ b/Esiur/Stores/MemoryStore.cs @@ -6,8 +6,8 @@ using System.Text; using System.Threading.Tasks; using Esiur.Core; using Esiur.Data; -using Esiur.Data.Schema; - +using Esiur.Data.Types; + namespace Esiur.Stores; public class MemoryStore : IStore @@ -78,13 +78,13 @@ public class MemoryStore : IStore throw new NotImplementedException(); } - public AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate) + public AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate) { throw new NotImplementedException(); } - public bool Modify(IResource resource, string propertyName, object value, ulong? age, DateTime? dateTime) + public bool Modify(IResource resource, PropertyDef propertyDef, object value, ulong? age, DateTime? dateTime) { return true; } diff --git a/Esiur/Stores/TemporaryStore.cs b/Esiur/Stores/TemporaryStore.cs index 495b62c..eab8b54 100644 --- a/Esiur/Stores/TemporaryStore.cs +++ b/Esiur/Stores/TemporaryStore.cs @@ -6,7 +6,7 @@ using System.Text; using System.Threading.Tasks; using Esiur.Core; using Esiur.Data; -using Esiur.Data.Schema; +using Esiur.Data.Types; namespace Esiur.Stores; public class TemporaryStore : IStore @@ -69,13 +69,13 @@ public class TemporaryStore : IStore throw new NotImplementedException(); } - public AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate) + public AsyncReply> GetRecord(IResource resource, DateTime fromDate, DateTime toDate) { throw new NotImplementedException(); } - public bool Modify(IResource resource, string propertyName, object value, ulong? age, DateTime? dateTime) + public bool Modify(IResource resource, PropertyDef propertyDef, object value, ulong? age, DateTime? dateTime) { return true; } diff --git a/Test/MyResource.cs b/Test/MyResource.cs index d05436d..35318b2 100644 --- a/Test/MyResource.cs +++ b/Test/MyResource.cs @@ -10,7 +10,7 @@ using static System.Runtime.InteropServices.JavaScript.JSType; namespace Test { [Resource] - [Annotation("A", "B", "C", "D")] + [Annotation("A", "B")] public partial class MyResource { [Export][Annotation("Comment")] string description; diff --git a/Test/MyService.cs b/Test/MyService.cs index 49fe3b9..be0468e 100644 --- a/Test/MyService.cs +++ b/Test/MyService.cs @@ -1,11 +1,11 @@ using Esiur.Data; using Esiur.Core; -using Esiur.Net.IIP; using Esiur.Resource; using System; using System.Collections.Generic; using System.Text; using System.Threading; +using Esiur.Protocol; #nullable enable @@ -183,12 +183,12 @@ public partial class MyService } [Export] - public void Connection(object a1, int a2, DistributedConnection a3) => + public void Connection(object a1, int a2, EpConnection a3) => Console.WriteLine($"VoidArgs {a1} {a2} {a3}"); [Export] - public void ConnectionOptional(object a1, int a2, string a3 = "sss", DistributedConnection? a4 = null) => + public void ConnectionOptional(object a1, int a2, string a3 = "sss", EpConnection? a4 = null) => Console.WriteLine($"VoidArgs {a1} {a2} {a3}"); [Export] diff --git a/Test/Program.cs b/Test/Program.cs index d0a28af..aef3759 100644 --- a/Test/Program.cs +++ b/Test/Program.cs @@ -25,7 +25,6 @@ SOFTWARE. using Esiur.Data; using Esiur.Core; using Esiur.Net.HTTP; -using Esiur.Net.IIP; using Esiur.Net.Sockets; using Esiur.Resource; using Esiur.Security.Permissions; @@ -49,6 +48,7 @@ using Esiur.Security.Cryptography; using Esiur.Security.Membership; using Esiur.Net.Packets; using System.Numerics; +using Esiur.Protocol; namespace Test { @@ -56,7 +56,7 @@ namespace Test class Program { - static void TestSerialization(object x, DistributedConnection connection = null) + static void TestSerialization(object x, EpConnection connection = null) { var d = Codec.Compose(x, Warehouse.Default, connection); @@ -145,7 +145,7 @@ namespace Test // Create stores to keep objects. var system = await wh.Put("sys", new MemoryStore()); - var server = await wh.Put("sys/server", new DistributedServer() { Membership = membership }); + var server = await wh.Put("sys/server", new EpServer() { Membership = membership }); var web = await wh.Put("sys/web", new HTTPServer() { Port = 8088 }); @@ -158,7 +158,7 @@ namespace Test //TestSerialization(res1); - server.MapCall("Hello", (string msg, DateTime time, DistributedConnection sender) => + server.MapCall("Hello", (string msg, DateTime time, EpConnection sender) => { Console.WriteLine(msg); return "Hi " + DateTime.UtcNow; @@ -200,9 +200,9 @@ namespace Test var format = x.RequiredFormat; - if (format == IIPAuthPacketIAuthFormat.Number) + if (format == EpAuthPacketIAuthFormat.Number) return new AsyncReply(Convert.ToInt32(10)); - else if (format == IIPAuthPacketIAuthFormat.Text) + else if (format == EpAuthPacketIAuthFormat.Text) return new AsyncReply(Console.ReadLine().Trim()); throw new NotImplementedException("Not supported format."); @@ -211,7 +211,7 @@ namespace Test private static async void TestClient(IResource local) { - var con = await new Warehouse().Get("iip://localhost", new DistributedConnectionConfig + var con = await new Warehouse().Get("EP://localhost", new EpConnectionConfig { AutoReconnect = true, Username = "admin", @@ -258,11 +258,11 @@ namespace Test var t4 = await remote.GetTuple4(1, "A", 1.3, true); Console.WriteLine(t4); - remote.StringEvent += new DistributedResourceEvent((sender, args) => + remote.StringEvent += new EpResourceEvent((sender, args) => Console.WriteLine($"StringEvent {args}") ); - remote.ArrayEvent += new DistributedResourceEvent((sender, args) => + remote.ArrayEvent += new EpResourceEvent((sender, args) => Console.WriteLine($"ArrayEvent {args}") ); @@ -270,7 +270,7 @@ namespace Test - //var path = TemplateGenerator.GetTemplate("iip://localhost/sys/service", "Generated"); + //var path = TemplateGenerator.GetTemplate("EP://localhost/sys/service", "Generated"); //Console.WriteLine(path); @@ -295,7 +295,7 @@ namespace Test static Timer perodicTimer; - static void TestObjectProps(IResource local, DistributedResource remote) + static void TestObjectProps(IResource local, EpResource remote) { foreach (var pt in local.Instance.Definition.Properties) @@ -333,6 +333,10 @@ namespace Test return rt; } + else if (value is Record) + { + return value.ToString(); + } else if (value is IRecord) { return "{" + String.Join(", ", t.GetProperties().Select(x => x.Name + ": " + x.GetValue(value))) + "}";