Skip to content

Commit

Permalink
fix supranet.connected, global paths
Browse files Browse the repository at this point in the history
  • Loading branch information
benStre committed Jun 8, 2024
1 parent 4c957a9 commit 2bb03b6
Show file tree
Hide file tree
Showing 9 changed files with 88 additions and 47 deletions.
4 changes: 2 additions & 2 deletions init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Pointer } from "./runtime/pointers.ts";
import { LOCAL_ENDPOINT } from "./types/addressing.ts";
import { client_type } from "./utils/constants.ts";
import { Storage, registerStorageAsPointerSource } from "./storage/storage.ts";
import { cwdURL, logger } from "./utils/global_values.ts";
import { logger, projectRootURL } from "./utils/global_values.ts";
import { IndexedDBStorageLocation } from "./storage/storage-locations/indexed-db.ts";
import { LocalStorageLocation } from "./storage/storage-locations/local-storage.ts";
import { DenoKVStorageLocation } from "./storage/storage-locations/deno-kv.ts";
Expand Down Expand Up @@ -66,7 +66,7 @@ export async function init() {
}
else if (client_type == "deno") {
// TODO: dynamic storage.ts location - use uix path backend/storage.ts as workaround
storageInitModule = new Path('./backend/storage.ts', cwdURL)
storageInitModule = new Path('./backend/storage.ts', projectRootURL)
}

if (await storageInitModule?.fsExists()) {
Expand Down
12 changes: 12 additions & 0 deletions network/communication-hub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { IOHandler } from "../runtime/io_handler.ts";
import { DATEX_ERROR } from "../types/error_codes.ts";
import { LocalLoopbackInterfaceSocket } from "./communication-interfaces/local-loopback-interface.ts";
import { Datex } from "../mod.ts";
import { Supranet } from "./supranet.ts";

export type DatexInData = {
dxb: ArrayBuffer|ReadableStreamDefaultReader<Uint8Array>,
Expand Down Expand Up @@ -115,9 +116,20 @@ export class CommunicationHubHandler {
const isConnected = this.isConnected();
if (isConnected !== this.connected) {
this.#connected = isConnected;
Supranet._setConnected(this.#connected);
this.#logger.debug(`Connection status was changed. This endpoint (${Datex.Runtime.endpoint}) is ${isConnected ? "online" : "offline"}!`);
if (this.#connected)
this.onlineEvents.forEach(e => e());
}
}

private onlineEvents = new Set<() => unknown>();
public addOnlineHandler(method: () => unknown) {
this.onlineEvents.add(method);
}
public removeOnlineHandler(method: () => unknown) {
this.onlineEvents.delete(method);
}

private isConnected() {
if (this.#defaultInterface?.getSockets().size) {
Expand Down
7 changes: 3 additions & 4 deletions network/communication-interfaces/websocket-interface.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CommunicationInterface, CommunicationInterfaceSocket } from "../communication-interface.ts";
import { onlineStatus } from "../online-status.ts";
import { getOnlineState, onlineStatus } from "../online-state.ts";

/**
* WebSocket interface socket, used by WebSocket client and server interfaces
Expand Down Expand Up @@ -51,7 +51,6 @@ export abstract class WebSocketInterface extends CommunicationInterface<WebSocke

let connectionOpen = false;
const errorHandler = () => {
console.warn("error handler", connectionOpen)
// don't trigger any further errorHandlers
webSocket.removeEventListener('close', errorHandler);
webSocket.removeEventListener('error', errorHandler);
Expand All @@ -64,7 +63,6 @@ export abstract class WebSocketInterface extends CommunicationInterface<WebSocke

if (!connectionOpen) resolve(false);
else {
console.warn("Remove socket");
this.removeSocket(socket);
this.onWebSocketClosed(socket)
}
Expand All @@ -86,8 +84,9 @@ export abstract class WebSocketInterface extends CommunicationInterface<WebSocke
webSocket.addEventListener('error', errorHandler);
webSocket.addEventListener('close', errorHandler);

const onlineState = getOnlineState();
effect(()=>{
if (!onlineStatus.val)
if (!onlineState.val)
errorHandler();
});

Expand Down
16 changes: 16 additions & 0 deletions network/online-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Pointer } from "../runtime/pointers.ts";
import { client_type } from "../utils/constants.ts";
let onlineStatus: Pointer<boolean> | undefined = undefined;

export function getOnlineState() {
if (!onlineStatus)
onlineStatus = Pointer.createOrGet<boolean>(navigator?.onLine ?? true);
if (client_type === "deno") {
// TODO
}
else {
globalThis.addEventListener("online", () => onlineStatus!.val = true);
globalThis.addEventListener("offline", () => onlineStatus!.val = false);
}
return onlineStatus;
}
10 changes: 0 additions & 10 deletions network/online-status.ts

This file was deleted.

5 changes: 5 additions & 0 deletions network/supranet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,11 @@ export class Supranet {
return connected;
}

// update Supranet.connected state
static _setConnected(connected:boolean) {
this.#connected = connected;
}


static getNode(use_node?:Endpoint) {
// channel types?
Expand Down
62 changes: 34 additions & 28 deletions runtime/cache_path.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,47 @@
import { client_type } from "../utils/constants.ts";
import { cwdURL } from "../utils/global_values.ts";
import { projectRootURL } from "../utils/global_values.ts";
import { normalizePath } from "../utils/normalize-path.ts";
import { commandLineOptions } from "../utils/args.ts";

let custom_cache_path = commandLineOptions.option("cache-path", {aliases: ["c"], type: "string", description: "Overrides the default path for datex cache files (.datex-cache)"})

let _cache_path:string|URL = new URL('./.datex-cache/', cwdURL);
let _ptr_cache_path:string|URL = new URL('./pointers/', _cache_path);
export async function _updateCachePaths() {

// command line args (--watch-backend)
if (client_type == "deno") {
let _cache_path:string|URL = new URL('./.datex-cache/', projectRootURL);
let _ptr_cache_path:string|URL = new URL('./pointers/', _cache_path);

const commandLineOptions = (await import("../utils/args.ts" /*lazy*/)).commandLineOptions

let custom_cache_path = commandLineOptions.option("cache-path", {aliases: ["c"], type: "string", description: "Overrides the default path for datex cache files (.datex-cache)"})

if (custom_cache_path) {
if (custom_cache_path?.startsWith("/")) custom_cache_path = `file://${custom_cache_path}`;
if (!custom_cache_path?.endsWith("/")) custom_cache_path += '/';
// command line args (--watch-backend)
if (client_type == "deno") {

if (custom_cache_path) {
_cache_path = new URL(custom_cache_path, cwdURL);
if (custom_cache_path?.startsWith("/")) custom_cache_path = `file://${custom_cache_path}`;
if (!custom_cache_path?.endsWith("/")) custom_cache_path += '/';
if (custom_cache_path) {
_cache_path = new URL(custom_cache_path, projectRootURL);
_ptr_cache_path = new URL('./pointers/', _cache_path);
}
}

// check if write permission for configured datex cache dir

try {
const testUrl = new URL("write_test", _cache_path.toString());
Deno.mkdirSync(normalizePath(testUrl), {recursive: true})
Deno.removeSync(testUrl);
}
catch {
const prev = _cache_path;
_cache_path = new URL(normalizePath(await Deno.makeTempDir()+"/"), "file:///");
_ptr_cache_path = new URL('./pointers/', _cache_path);
console.log("(!) cache directory "+prev+" is readonly, using temporary directory " + _cache_path);
}
}

// check if write permission for configured datex cache dir

try {
const testUrl = new URL("write_test", _cache_path.toString());
Deno.mkdirSync(normalizePath(testUrl), {recursive: true})
Deno.removeSync(testUrl);
}
catch (e) {
const prev = _cache_path;
_cache_path = new URL(normalizePath(await Deno.makeTempDir()+"/"), "file:///");
_ptr_cache_path = new URL('./pointers/', _cache_path);
console.log("(!) cache directory "+prev+" is readonly, using temporary directory " + _cache_path);
}
cache_path = _cache_path;
ptr_cache_path = _ptr_cache_path;
}

export const cache_path = _cache_path;
export const ptr_cache_path = _ptr_cache_path;
export let cache_path: URL;
export let ptr_cache_path: URL;

await _updateCachePaths();
4 changes: 2 additions & 2 deletions runtime/endpoint_config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// store and read endpoint config (name, keys, ...)

import { cwdURL, Deno, logger } from "../utils/global_values.ts";
import { Deno, logger, projectRootURL } from "../utils/global_values.ts";
import { client_type } from "../utils/constants.ts";
import { Endpoint } from "../types/addressing.ts";
import { Crypto } from "./crypto.ts";
Expand Down Expand Up @@ -77,7 +77,7 @@ class EndpointConfig implements EndpointConfigData {
}
// use normal dx file
catch {
if (!path) path = new URL('./'+this.DX_FILE_NAME, cwdURL)
if (!path) path = new URL('./'+this.DX_FILE_NAME, projectRootURL)
config_file = path;
}
try {
Expand Down
15 changes: 14 additions & 1 deletion utils/global_values.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,17 @@ export const baseURL = new URL('../../', import.meta.url);
export const libURL = new URL('../', import.meta.url);

// path from which the script was executed (same aas baseURL in browsers)
export const cwdURL = client_type == "deno" ? new URL('file://'+Deno.cwd()+"/") : baseURL;
export const cwdURL = client_type == "deno" ? new URL('file://'+Deno.cwd()+"/") : baseURL;

export let projectRootURL = cwdURL;

/**
* Modify the project root URL (default is the current working directory)
* @param url
*/
export async function _updateProjectRootURL(url:URL) {
const { _updateCachePaths } = await import("../runtime/cache_path.ts");

projectRootURL = url;
await _updateCachePaths();
}

0 comments on commit 2bb03b6

Please sign in to comment.