Skip to content

Commit

Permalink
improve routing
Browse files Browse the repository at this point in the history
  • Loading branch information
benStre committed Nov 18, 2023
1 parent bc503af commit 20d5ffb
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 16 deletions.
5 changes: 3 additions & 2 deletions iframes/iframe-com-interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,13 @@ export class IFrameCommunicationInterface extends CommonInterface<[HTMLIFrameEle
}

onReceive = (event: MessageEvent) => {
if (event.origin == this.otherOrigin) {

if (event.source === this.other) {
const data = event.data;
if (data instanceof ArrayBuffer) {
InterfaceManager.handleReceiveBlock(data, this.endpoint, this);
}
else if (data?.type == "INIT") {
else if (data?.type == "INIT" && !this.endpoint) {
this.endpoint = Target.get(data.endpoint) as Datex.Endpoint;

// if in parent: send INIT to iframe after initialized
Expand Down
2 changes: 1 addition & 1 deletion network/blockchain_adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export type BCData<T extends BCEntryType> =

public async sign(){
const data_dx = Datex.Compiler.encodeValue(this.data);
this.creator = Datex.Runtime.endpoint;
this.creator = Datex.Runtime.endpoint.main;
this.signature = await Datex.Crypto.sign(data_dx);
return this;
}
Expand Down
12 changes: 11 additions & 1 deletion network/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ export abstract class CommonInterface<Args extends unknown[] = []> implements Co

// use this per default for all outgoing datex requests
public static default_interface:ComInterface;
public static proxy_interface?:ComInterface;

public type = "local"
public persistent = false; // interface can be disconnected (per default)
Expand All @@ -167,9 +168,11 @@ export abstract class CommonInterface<Args extends unknown[] = []> implements Co
}

public set endpoint(endpoint: Endpoint|undefined) {
if (endpoint === this._endpoint) return;
this.logger.debug("updated endpoint to " + endpoint);
this._endpoint = endpoint;
this.updateEndpoint();
this.onEndpointSet?.(endpoint);
}

private updateEndpoint() {
Expand All @@ -179,6 +182,8 @@ export abstract class CommonInterface<Args extends unknown[] = []> implements Co
}
}

private onEndpointSet?: Function


protected declare initial_arguments:Args

Expand Down Expand Up @@ -806,10 +811,15 @@ export class InterfaceManager {
return InterfaceManager.handleNoRedirectFound(to);
}

// prefere proxy_interface
if (CommonInterface.proxy_interface) comInterface = CommonInterface.proxy_interface;

// error: loopback
if (source && !source?.is_bidirectional_hub && (source == comInterface || comInterface.isEqualSource?.(source, to))) {
// fallback to default interface
if (CommonInterface.default_interface && comInterface !== CommonInterface.default_interface) comInterface = CommonInterface.default_interface;
// fallback to proxy interface
if (CommonInterface.proxy_interface && comInterface !== CommonInterface.proxy_interface) comInterface = CommonInterface.proxy_interface;
else return InterfaceManager.handleNoRedirectFound(to);
}

Expand All @@ -823,7 +833,7 @@ export class InterfaceManager {
const exclude_endpoints = new Set([exclude]);

// iterate over all active endpoints
for (const interf of this.active_interfaces) {
for (const interf of CommonInterface.proxy_interface ? [CommonInterface.proxy_interface]: this.active_interfaces) {
if (interf.endpoint && !exclude_endpoints.has(interf.endpoint) && !interf.endpoint.equals(Runtime.endpoint)) {
exclude_endpoints.add(interf.endpoint);
//console.log("FLOOD > " + interf.endpoint)
Expand Down
12 changes: 9 additions & 3 deletions network/supranet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,20 @@ export class Supranet {
else {
// existing locally available endpoint instances -> hashes
const hashes = await Storage.loadOrCreate("Datex.Supranet.ENDPOINT_INSTANCE_HASHES", () => new Map<Endpoint, string>())

logger.debug("available cached instances: " + [...hashes.keys()].map(e=>e.toString()).join(", "))

try {
logger.debug("available cached instances: " + [...hashes.keys()].map(e=>e.toString()).join(", "))
}
catch (e) {
console.error("invalid hashes", hashes)
throw e;
}

const activeEndpoints = Runtime.getActiveLocalStorageEndpoints();
let hash: string|undefined = undefined;
let endpoint = Runtime.endpoint;
for (const [storedEndpoint, storedHash] of hashes) {
if (!activeEndpoints.includes(storedEndpoint)) {
if (Runtime.endpoint.main == storedEndpoint.main && !activeEndpoints.includes(storedEndpoint)) {
hash = storedHash;
endpoint = storedEndpoint;
break;
Expand Down
27 changes: 21 additions & 6 deletions types/function-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,19 @@ export async function getDeclaredExternalVariablesAsync(fn: (...args:unknown[])=
}

export function getSourceWithoutUsingDeclaration(fn: (...args:unknown[])=>unknown) {
return fn
.toString()
let fnSource = fn.toString();
// object methods check if 'this' context is component context;
if (isObjectMethod(fnSource)) {
if (fnSource.startsWith("async")) fnSource = fnSource.replace("async", "async function")
else fnSource = "function " + fnSource
}
return fnSource
.replace(/(?<=(?:(?:[\w\s*])+\(.*\)\s*{|\(.*\)\s*=>\s*{?|.*\s*=>\s*{?)\s*)(use\s*\((?:[\s\S]*?)\))/, 'true /*$1*/')
}


function isObjectMethod(fnSrc:string) {
return !!fnSrc.match(/^(async\s+)?[^\s(]+ *(\(|\*)/)
}

/**
* Create a new function from JS source code with injected dependency variables
Expand All @@ -139,9 +147,16 @@ export function createFunctionWithDependencyInjections(source: string, dependenc
return val;
};`

let creatorFn = new Function(...renamedVars, `"use strict";${varMapping?createStaticFn:''}${varMapping}; return (${source})`)
if (hasThis) creatorFn = creatorFn.bind(dependencies['this'])
return creatorFn(...Object.values(dependencies));
try {
let creatorFn = new Function(...renamedVars, `"use strict";${varMapping?createStaticFn:''}${varMapping}; return (${source})`)
if (hasThis) creatorFn = creatorFn.bind(dependencies['this'])
return creatorFn(...Object.values(dependencies));
}
catch (e) {
console.error(source)
throw e;
}

}

export class ExtensibleFunction {
Expand Down
9 changes: 6 additions & 3 deletions windows/window-com-interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ export class WindowCommunicationInterface extends CommonInterface<[Window, strin

protected async connect() {
// is the parent document
if (!this.initial_arguments[0]?.opener ||
(this.initial_arguments[0].opener === self.window)) {
console.log("iinit", this.initial_arguments)
if (this.initial_arguments[0] !== self.window.opener) {
this.window = this.initial_arguments[0];
this.otherOrigin = this.initial_arguments[1];
this.logger.info("initializing as parent window, window origin: " + this.otherOrigin)
Expand All @@ -40,6 +40,7 @@ export class WindowCommunicationInterface extends CommonInterface<[Window, strin
}
globalThis.addEventListener("message", this.onReceive);
// if in sub window: send INIT to parent immediately
console.log("SEND sendInit", this.parentDocument)
if (this.parentDocument)
this.sendInit();

Expand All @@ -55,6 +56,7 @@ export class WindowCommunicationInterface extends CommonInterface<[Window, strin
}

else if (data?.type == "INIT") {
console.warn(" && !this.endpoint", !this.endpoint)
this.endpoint = Target.get(data.endpoint) as Datex.Endpoint;

// if in parent: send INIT to window after initialized
Expand All @@ -64,6 +66,7 @@ export class WindowCommunicationInterface extends CommonInterface<[Window, strin
}

private sendInit() {
console.log("SEND sendInit...")
this.other.postMessage({
type:"INIT",
endpoint:Datex.Runtime.endpoint.toString()
Expand All @@ -78,7 +81,7 @@ export class WindowCommunicationInterface extends CommonInterface<[Window, strin
get other() {
return this.window ?
this.window :
this.parentDocument?.opener
this.parentDocument
}

protected sendBlock(datex: ArrayBuffer) {
Expand Down

0 comments on commit 20d5ffb

Please sign in to comment.