2
0
mirror of https://github.com/esiur/esiur-js.git synced 2025-06-27 07:13:12 +00:00
This commit is contained in:
2021-03-10 01:25:20 +03:00
parent ca2b89540a
commit a08519bde8
55 changed files with 4190 additions and 6679 deletions

View File

@ -28,11 +28,22 @@ import ExceptionCode from './ExceptionCode.js';
export default class AsyncException extends Error
{
constructor()
{
super();
this.raised = false;
}
constructor(type, code, message)
{
super();
if (type instanceof AsyncException) {
this.raise(type.type, type.code, type.message);
} else if (type instanceof Error) {
this.raise(1, 0, type.message);
} else if (type != undefined){
this.raise(type, code, message);
} else {
this.raised = false;
}
}
raise(type, code, message)
{

View File

@ -94,14 +94,16 @@ export default class AsyncReply extends Promise
this.ready = true;
for(var i = 0; i < this.callbacks.length; i++)
this.callbacks[i](result, this);
this.callbacks[i](result, this);
return this;
}
triggerError(type, code, message)
{
if (this.ready)
return;
return this;
if (type instanceof AsyncException)
this.exception.raise(type.type, type.code, type.message);
@ -113,18 +115,24 @@ export default class AsyncReply extends Promise
else
for(var i = 0; i < this.errorCallbacks.length; i++)
this.errorCallbacks[i](this.exception, this);
return this;
}
triggerProgress(type, value, max)
{
for(var i = 0; i < this.progressCallbacks.length; i++)
this.progressCallbacks[i](type, value, max, this);
return this;
}
triggerChunk(value)
{
for(var i = 0; i < this.chunkCallbacks.length; i++)
this.chunkCallbacks[i](value, this);
return this;
}
constructor(result)

View File

@ -30,5 +30,9 @@ export default //const ExceptionCode =
SetPropertyDenied: 27,
ReadOnlyProperty: 28,
GeneralFailure: 29,
AddToStoreFailed: 30
AddToStoreFailed: 30,
NotAttached: 31,
AlreadyListened: 32,
AlreadyUnlistened: 33,
NotListenable: 34
};

View File

@ -1,7 +1,7 @@
export default // const ResourceComparisonResult =
{
Null: 0,
Distributed: 1,
Local: 2,
Same: 3
};
{
Null: 0,
Distributed: 1,
Local: 2,
Same: 3
};

File diff suppressed because it is too large Load Diff

View File

@ -31,6 +31,10 @@ import AsyncReply from '../../Core/AsyncReply.js';
import Codec from '../../Data/Codec.js';
import Structure from '../../Data/Structure.js';
import IIPPacketAction from '../Packets//IIPPacketAction.js';
import EventTemplate from '../../Resource/Template/EventTemplate.js';
import AsyncException from '../../Core/AsyncException.js';
import ExceptionCode from '../../Core//ExceptionCode.js';
import ErrorType from '../../Core/ErrorType.js';
export default class DistributedResource extends IResource
{
@ -166,6 +170,32 @@ export default class DistributedResource extends IResource
return true;
}
listen(event)
{
let et = event instanceof EventTemplate ? event : this.instance.template.getEventTemplateByName(event);
if (et == null)
return new AsyncReply().triggerError(new AsyncException(ErrorType.Management, ExceptionCode.MethodNotFound, ""));
if (!et.listenable)
return new AsyncReply().triggerError(new AsyncException(ErrorType.Management, ExceptionCode.NotListenable, ""));
return this._p.connection.sendListenRequest(this._p.instanceId, et.index);
}
unlisten(event)
{
let et = event instanceof EventTemplate ? event : this.instance.template.getEventTemplateByName(event);
if (et == null)
return new AsyncReply().triggerError(new AsyncException(ErrorType.Management, ExceptionCode.MethodNotFound, ""));
if (!et.listenable)
return new AsyncReply().triggerError(new AsyncException(ErrorType.Management, ExceptionCode.NotListenable, ""));
return this._p.connection.sendUnlistenRequest(this._p.instanceId, et.index);
}
_emitEventByIndex(index, args)
{
var et = this.instance.template.getEventTemplateByIndex(index);
@ -225,7 +255,7 @@ export default class DistributedResource extends IResource
{
if (!this._p.attached)
{
console.log("What ?");
console.log("Resource not attached.");
return;
}

View File

@ -0,0 +1,81 @@
/*
* Copyright (c) 2017-2021 Ahmed Kh. Zamil
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Created by Ahmed Zamil on 03/05/2021.
*/
"use strict";
import IResource from '../../Resource/IResource.js';
import AsyncReply from '../../Core/AsyncReply.js';
import Codec from '../../Data/Codec.js';
import Structure from '../../Data/Structure.js';
import IIPPacketAction from '../Packets//IIPPacketAction.js';
import EventTemplate from '../../Resource/Template/EventTemplate.js';
import AsyncException from '../../Core/AsyncException.js';
import ExceptionCode from '../../Core//ExceptionCode.js';
import ErrorType from '../../Core/ErrorType.js';
import DistributedConnection from './DistributedConnection.js';
export default class DistributedServer extends IResource
{
destroy()
{
this.connections = [];
this.destroyed = true;
this._emit("destroy", this);
}
trigger(type)
{
return new AsyncReply(true);
}
get membership() {
return this.instance.attributes.get("membership");
}
get entryPoint() {
return this.instance.attributes.get("entryPoint");
}
constructor()
{
super();
this.connections = [];
}
add() {
let self = this;
let con = new DistributedConnection(this);
con.on("close", () => self.remove(con));
this.connections.push(con);
return con;
}
remove(connection){
let i = this.connections.indexOf(connection);
if (i > -1)
this.connections.splice(i, 1);
}
}

View File

@ -0,0 +1,8 @@
import IResource from "../../Resource/IResource";
export default class EntryPoint extends IResource
{
query(path, sender) {}
create() {}
}

View File

@ -0,0 +1,7 @@
import IDestructible from "../Core/IDestructible";
export default class INetworkReceiver extends IDestructible {
networkClose(sender);
networkReceive(sender, buffer);
networkConnect(sender);
}

View File

@ -26,7 +26,7 @@
"use strict";
import DC from '../../Data/DataConverter.js';
import DC from '../Data/DataConverter.js';
export default class NetworkBuffer {
constructor() {

View File

@ -0,0 +1,5 @@
export default class NetowrkConnection extends INetworkReceiver
{
}

0
src/Net/NetworkServer.js Normal file
View File

View File

View File

@ -391,7 +391,9 @@ export default class IIPPacket
offset += cl;
}
else if (this.action == IIPPacketAction.GetProperty)
else if (this.action == IIPPacketAction.Listen
|| this.action == IIPPacketAction.Unlisten)
//this.action == IIPPacketAction.GetProperty)
{
if (this.notEnough(offset, ends, 5))
return -this.dataLengthNeeded;
@ -402,20 +404,20 @@ export default class IIPPacket
this.methodIndex = data.getUint8(offset++);
}
else if (this.action == IIPPacketAction.GetPropertyIfModified)
{
if (this.notEnough(offset, ends, 9))
return -this.dataLengthNeeded;
// else if (this.action == IIPPacketAction.GetPropertyIfModified)
// {
// if (this.notEnough(offset, ends, 9))
// return -this.dataLengthNeeded;
this.resourceId = data.getUint32(offset);
offset += 4;
// this.resourceId = data.getUint32(offset);
// offset += 4;
this.methodIndex = data[offset++];
// this.methodIndex = data[offset++];
this.resourceAge = data.getUint64(offset);
offset += 8;
// this.resourceAge = data.getUint64(offset);
// offset += 8;
}
// }
else if (this.action == IIPPacketAction.SetProperty)
{
if (this.notEnough(offset, ends, 6))
@ -552,9 +554,9 @@ export default class IIPPacket
offset += cl;
}
else if (this.action == IIPPacketAction.InvokeFunctionArrayArguments
|| this.action == IIPPacketAction.InvokeFunctionNamedArguments
|| this.action == IIPPacketAction.GetProperty
|| this.action == IIPPacketAction.GetPropertyIfModified)
|| this.action == IIPPacketAction.InvokeFunctionNamedArguments)
//|| this.action == IIPPacketAction.GetProperty
//|| this.action == IIPPacketAction.GetPropertyIfModified)
{
if (this.notEnough(offset, ends, 1))
@ -586,7 +588,9 @@ export default class IIPPacket
offset += size;
}
}
else if (this.action == IIPPacketAction.SetProperty)
else if (this.action == IIPPacketAction.SetProperty
|| this.action == IIPPacketAction.Listen
|| this.action == IIPPacketAction.Unlisten)
{
// nothing to do
}

View File

@ -21,10 +21,10 @@ export default // const IIPPacketAction =
// Request Invoke
InvokeFunctionArrayArguments: 16,
GetProperty: 17,
GetPropertyIfModified: 18,
SetProperty: 19,
InvokeFunctionNamedArguments: 20,
InvokeFunctionNamedArguments: 17,
Listen: 18,
Unlisten: 19,
SetProperty: 20,
// Request Attribute
GetAllAttributes: 24,

View File

@ -39,7 +39,7 @@ export default class SendList extends BinaryList
done()
{
this.connection.send(this.toArray());
this.connection.sendAll(this.toArray());
return this.reply;
}
}

View File

@ -0,0 +1,34 @@
"use strict";
import IDestructible from "../../Core/IDestructible.js";
import SocketState from "./SocketState.js";
export default class ISocket extends IDestructible
{
//SocketState State { get; }
//INetworkReceiver<ISocket> Receiver { get; set; }
constructor(){
super();
this.state = SocketState.Initial;
}
// get state() {}
sendAsync(message, offset, length) { }
send(message, offset, length) {}
close() {}
connect(hostname, port) {}
begin() {}
beginAsync() {}
acceptAsync() {}
accept() {}
get remoteEndPoint(){}
get localEndPoint() {}
hold() {}
unhold() {}
}

View File

@ -0,0 +1,7 @@
export default {
Initial : 0,
Listening : 1,
Connecting : 2,
Established : 3,
Closed: 4,
}

165
src/Net/Sockets/WSSocket.js Normal file
View File

@ -0,0 +1,165 @@
import AsyncReply from "../../Core/AsyncReply.js";
import ErrorType from "../../Core/ErrorType.js";
import ExceptionCode from "../../Core/ExceptionCode.js";
import ISocket from "./ISocket.js";
import SocketState from "./SocketState.js";
import NetworkBuffer from "../NetworkBuffer.js";
export default class WSSocket extends ISocket
{
//SocketState State { get; }
//INetworkReceiver<ISocket> Receiver { get; set; }
constructor(websocket){
super();
this.receiveNetworkBuffer = new NetworkBuffer();
this.sendNetworkBuffer = new NetworkBuffer();
this.held = false;
if (websocket != null)// instanceof WebSocket)
{
//websocket.onerror = () => {
// self.state = SocketState.Closed;
//};
websocket.onopen = () => {
self.state = SocketState.Established;
};
websocket.onerror = () => {
self.state = SocketState.Closed;
};
this._assign(websocket);
}
}
destroy(){
this.close();
this.receiveNetworkBuffer = null;
this.receiver = null;
thsi.ws = null;
this._emit("destroy");
}
sendAsync(message, offset, length) {
}
sendAll(message)
{
if (this.held)
this.sendNetworkBuffer.writeAll(message);
else
{
try
{
this.ws.send(message);
} catch {
this.state = SocketState.Closed;
}
}
}
send(message, offset, length) {
this.sendAll(message.clip(offset, length));
}
close() {
this.ws.close();
}
connect(hostname, port, secure = false) {
let self = this;
var rt = new AsyncReply();
this.state = SocketState.Connecting;
this.url = `ws${secure ? 's' : ''}://${hostname}:${port}`;
let ws = new WebSocket(this.url, "iip");
ws.binaryType = "arraybuffer";
ws.onopen = () => {
self.state = SocketState.Established;
rt.trigger(true);
};
ws.onerror = () => {
self.state = SocketState.Closed;
rt.triggerError(ErrorType.Management, ExceptionCode.HostNotReachable);
};
this._assign(ws);
return rt;// new AsyncReply(true);
}
_assign(ws)
{
let self = this;
ws.onclose = () => {
self.state = SocketState.Closed;
self.receiver?.networkClose(self);
};
ws.onmessage = function(msg) {
self.receiveNetworkBuffer.writeAll(msg.data);
self.receiver.networkReceive(this, self.receiveNetworkBuffer);
//self.lastAction = new Date();
};
this.ws = ws;
}
begin() {
}
beginAsync() {
}
acceptAsync() {
}
accept() {
}
get remoteEndPoint(){}
get localEndPoint() {}
hold()
{
this.held = true;
}
unhold()
{
this.held = false;
var message = this.sendNetworkBuffer.read();
if (message == null)
return;
// totalSent += message.Length;
try {
this.ws.send(message);
} catch {
this.state = SocketState.Closed;
}
}
}
// if (this.holdSending) {
// //console.log("hold ", data.length);
// this.sendBuffer.writeAll(data);
// }
// else
// //console.log("Send", data.length);

View File

@ -18,14 +18,14 @@ export default class ResourceProxy
for(var i = 0; i < template.properties.length; i++)
{
let pt = template.properties[i];
let desc = Object.getOwnPropertyDescriptor(Payment.prototype, pt.name);
let desc = Object.getOwnPropertyDescriptor(type.prototype, pt.name);
if (desc)
{
code += `\r\n set ${pt.name}(v) { \r\n if (this.instance) this.instance.emitModification(this.instance.template.properties[${i}], v); \r\n super.${pt.name} = v; } \r\n get ${pt.name}() { \r\n return super.${pt.name};}`;
}
else
{
code += `\r\n set ${pt.name}(v) { \r\n if (this.instance) this.instance.emitModification(this.instance.template.properties[${i}], v); \r\n super._${pt.name} = v; } \r\n get ${pt.name}() { \r\n return super._${pt.name};}`;
code += `\r\n set ${pt.name}(v) { \r\n if (this.instance) this.instance.emitModification(this.instance.template.properties[${i}], v); \r\n this._${pt.name} = v; } \r\n get ${pt.name}() { \r\n return this._${pt.name};}`;
}
}

View File

@ -28,10 +28,10 @@
export default class CustomResourceEvent
{
constructor(issuer, receivers, params)
constructor(issuer, receivers, args)
{
this.issuer = issuer;
this.receivers = receivers;
this.params = params;
this.args = args;
}
}

View File

@ -234,7 +234,7 @@ export default class Instance extends IEventHandler
return function(args)
{
if (args instanceof CustomResourceEvent)
self._emitResourceEvent(args.issuer, args.receivers, name, args.params);
self._emitResourceEvent(args.issuer, args.receivers, name, args.args);
else
self._emitResourceEvent(null, null, name, args);
};

View File

@ -46,7 +46,7 @@ export default class EventTemplate extends MemberTemplate
var name = super.compose();
if (this.expansion != null) {
var exp = DC.stringToBytes(this.expansion);
return rt.addUint8(0x50)
return rt.addUint8(this.listenable ? 0x58 : 0x50)
.addUint8(name.length)
.addUint8Array(name)
.addUint32(exp.length)
@ -54,7 +54,7 @@ export default class EventTemplate extends MemberTemplate
.toArray();
}
else
return rt.addUint8(0x40)
return rt.addUint8(this.listenable ? 0x48 : 0x40)
.addUint8(name.length)
.addUint8Array(name)
.toArray();

View File

@ -123,6 +123,7 @@ export default class ResourceTemplate {
et.name = template.events[i].name;
et.index = i;
et.expansion = template.events[i].help;
et.listenable = template.events[i].listenable;
this.events.push(et);
}
@ -266,9 +267,11 @@ export default class ResourceTemplate {
{
var et = new EventTemplate();
et.index = eventIndex++;
var expansion = ((data.getUint8(offset++) & 0x10) == 0x10);
var expansion = ((data.getUint8(offset) & 0x10) == 0x10);
et.listenable = ((data.getUint8(offset++) & 0x8) == 0x8);
var len = data.getUint8(offset++);
et.name = data.getString(offset, len);
offset += len;
if (expansion) // expansion ?

View File

@ -58,22 +58,38 @@ export class WH extends IEventHandler
this._urlRegex = /^(?:([^\s|:]*):\/\/([^\/]*)\/?)/;
}
newInstance(type, properties)
{
var proxyType = ResourceProxy.getProxy(type);
var res = new proxyType();
if (properties != null)
Object.assign(res, properties);
return type;
}
new(type, name, store = null, parent = null, manager = null, attributes = null, properties = null)
{
var proxyType = ResourceProxy.getProxy(type);
var rt = new AsyncReply();
var res = new proxyType();
if (properties != null)
Object.assign(res, properties);
this.put(res, name, store, parent, null, 0, manager, attributes)
.then((ok)=>rt.trigger(res))
.error((ex)=>rt.triggerError(ex));
if (store != null || parent != null || res instanceof IStore)
{
var rt = new AsyncReply();
return rt;
this.put(res, name, store, parent, null, 0, manager, attributes)
.then((ok)=>rt.trigger(res))
.error((ex)=>rt.triggerError(ex));
return rt;
}
else
{
return new AsyncReply(res);
}
}
getById(id)
@ -103,7 +119,6 @@ export class WH extends IEventHandler
else
rt.triggerError(store);
}).error(ex=>{
Warehouse.remove(resource);
rt.triggerError(ex);
});
}
@ -176,7 +191,7 @@ export class WH extends IEventHandler
}
put(resource, name, store, parent, customTemplate = null, age = 0, manager = null, attributes = null){
var rt = new AsyncReply();
resource.instance = new Instance(this.resourceCounter++, name, resource, store, customTemplate, age);
@ -202,6 +217,7 @@ export class WH extends IEventHandler
let self = this;
const initResource = ()=>{
self.resources.add(resource.instance.id, resource);
if (self.warehouseIsOpen)
@ -210,16 +226,22 @@ export class WH extends IEventHandler
if (resource instanceof IStore)
resource.trigger(ResourceTrigger.Open).then(y=>{ rt.trigger(true);
self._emit("connected", resource)
}).error(ex => rt.triggerError(ex));
}).error(ex => {
Warehouse.remove(resource);
rt.triggerError(ex)
});
else
rt.trigger(true);
}).error(ex=>rt.triggerError(ex));
}).error(ex => {
Warehouse.remove(resource);
rt.triggerError(ex)
});
}
else
{
if (resource instanceof IStore)
self._emit("connected", resource);
if (resource instanceof IStore)
self._emit("connected", resource);
rt.trigger(true);
}
}
@ -232,7 +254,11 @@ export class WH extends IEventHandler
else
store.put(resource).then(ok=>{
initResource();
}).error(ex=>rt.triggerError(ex));
}).error(ex=> {
// failed to put
Warehouse.remove(resource);
rt.triggerError(ex);
});
return rt;
}
@ -268,8 +294,7 @@ export class WH extends IEventHandler
getTemplateByType(type)
{
//debugger;
let className = type.prototype.constructor.name;
if (className.startsWith("E_"))

View File

@ -0,0 +1,10 @@
import Authentication from "./Authentication.js";
import AuthenticationType from "./AuthenticationType.js";
export default class ClientAuthentication extends Authentication
{
constructor()
{
super(AuthenticationType.Client);
}
}

View File

@ -0,0 +1,10 @@
import Authentication from "./Authentication.js";
import AuthenticationType from "./AuthenticationType.js";
export default class HostAuthentication extends Authentication
{
constructor()
{
super(AuthenticationType.Host);
}
}

View File

@ -0,0 +1,33 @@
import AsyncReply from "../../Core/AsyncReply.js";
import IResource from "../../Resource/IResource.js";
export default class IMembership extends IResource
{
userExists(username, domain){
return new AsyncReply(false);
}
getPassword(username, domain)
{
return new AsyncReply(null);
}
getToken(tokenIndex, domain)
{
return new AsyncReply(null);
}
login(session)
{
}
logout(session)
{
}
tokenExists(tokenIndex, domain)
{
}
}

View File

@ -34,12 +34,13 @@ export default class MemoryStore extends IStore
constructor()
{
super();
this.resources = [];
this.resources = new Map();
}
put(resource)
{
this.resources[resource.instance.id] = resource;
this.resources.set(resource.instance.id, resource);
return new AsyncReply(true);
}
retrive(id)

View File

@ -6,8 +6,10 @@ import MemoryStore from './Stores/MemoryStore.js';
import IndexedDBStore from './Stores/IndexedDBStore.js';
import IResource from './Resource/IResource.js';
import ResourceProxy from './Proxy/ResourceProxy.js';
import DistributedConnection from './Net/IIP/DistributedConnection.js';
if (window) {
if (typeof window !== 'undefined')
{
window.wh = wh;
window.Structure = Structure;
window.DistributedResource = DistributedResource;
@ -15,8 +17,9 @@ if (window) {
window.IndexedDBStore = IndexedDBStore;
window.IResource = IResource;
window.ResourceProxy = ResourceProxy;
window.DistributedConnection = DistributedConnection;
}
else if (global)
else if (typeof global !== 'undefined')
{
global.wh = wh;
global.Structure = Structure;
@ -24,6 +27,7 @@ else if (global)
global.MemoryStore = MemoryStore;
global.IndexedDBStore = IndexedDBStore;
global.IResource = IResource;
global.DistributedConnection = DistributedConnection;
}
export default wh;