summaryrefslogtreecommitdiff
path: root/backend/instance/api-connection.ts
diff options
context:
space:
mode:
Diffstat (limited to 'backend/instance/api-connection.ts')
-rw-r--r--backend/instance/api-connection.ts70
1 files changed, 70 insertions, 0 deletions
diff --git a/backend/instance/api-connection.ts b/backend/instance/api-connection.ts
new file mode 100644
index 0000000..3f0a661
--- /dev/null
+++ b/backend/instance/api-connection.ts
@@ -0,0 +1,70 @@
+import { WebSocket as wsocket } from 'ws';
+import { ServerStatus as Status } from './api-defs.js';
+
+let SERVER_LOG = 1;
+let API_ADDRESS = 'http://localhost:4000';
+
+export var status: Status = { isBusy: false, lastUpdate: 0, loadedModel: '', domain: '' };
+export var ws: wsocket;
+
+let slog = ( msg: string ) => { if( SERVER_LOG ) console.log( '[server] ' + msg ); };
+
+export function setStatus( s: any ) {
+ const newstatus: Status = { ...status, ...s };
+ status = newstatus;
+ return status;
+}
+
+export function serverOpen( addr: string ) {
+ API_ADDRESS = addr;
+ ws = new wsocket( addr );
+
+ ws.on( 'open', () => {
+ slog( 'connection opened' );
+ let s = status;
+ s.lastUpdate = Date.now();
+ s.msg = 'welcome';
+ ws.send( JSON.stringify( s ) );
+ } );
+
+ ws.on( 'message', ( message: string ) => {
+ status.lastUpdate = Date.now();
+ try {
+ let json = JSON.parse( message );
+ if( json.msg == 'ping' ) {
+ let s = { ...status };
+ s.msg = 'pong';
+ setTimeout( () => ws.send( JSON.stringify( s ) ), 5000 );
+ }
+ else {
+ slog( `unhandled message: ${message}` );
+ }
+ } catch ( err ) {
+ slog( '[server] ' + err );
+ }
+ } );
+
+ ws.on( 'error' , ( err ) => {
+ slog( `WebSocket error: ${err}` );
+ ws.close();
+ } );
+
+ ws.on( 'close', ( code, reason ) => {
+ setTimeout( () => { ws = serverOpen( addr ) }, 5000 );
+ slog( `connection closed: ${code}, ${reason}` );
+ } );
+
+ return ws;
+};
+
+export function serverNotify( what: any ) {
+ const newstatus: Status = { ...status, ...what };
+ status = newstatus;
+ try {
+ ws.send( JSON.stringify( status ) );
+ }
+ catch ( err ) {
+ slog( '[server] ' + err );
+ ws = serverOpen( API_ADDRESS );
+ }
+};