reflector.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. "use strict";
  2. // reflector.js
  3. //
  4. var parseurl = require( './parse-url' ),
  5. persistence = require( './persistence' ),
  6. helpers = require( './helpers' ),
  7. fs = require( 'fs' );
  8. function parseSocketUrl( socket ) {
  9. try
  10. {
  11. var query = require('url')
  12. .parse(socket.handshake.url)
  13. .query;
  14. var referer = require('querystring')
  15. .parse(query)
  16. .pathname;
  17. var resObj = require('querystring')
  18. .parse(query)
  19. .path;
  20. var namespace = referer;
  21. if(!namespace) return null;
  22. if (namespace[namespace.length - 1] != "/")
  23. namespace += "/";
  24. let parsedPath = JSON.parse(resObj);
  25. if (parsedPath) {
  26. return parsedPath
  27. }
  28. // else {
  29. // return parseurl.Process(namespace);
  30. // }
  31. }
  32. catch (e)
  33. {
  34. return null;
  35. }
  36. }
  37. function GetLoadForSocket( processedURL ) {
  38. if ( processedURL[ 'private_path' ] ) {
  39. return persistence.GetLoadInformation( processedURL );
  40. }
  41. return { 'save_name': undefined, 'save_revision': undefined, 'explicit_revision': undefined, 'application_path': undefined };
  42. }
  43. //Get the instance ID from the handshake headers for a socket
  44. function GetNamespace( processedURL ) {
  45. if ( ( processedURL[ 'instance' ] ) && ( processedURL[ 'public_path' ] ) ) {
  46. return helpers.JoinPath( processedURL[ 'public_path' ], processedURL[ 'application' ], processedURL[ 'instance' ] );
  47. }
  48. return undefined;
  49. }
  50. function GetNow( ) {
  51. return new Date( ).getTime( ) / 1000.0;
  52. }
  53. function OnConnection( socket ) {
  54. let resObj = parseSocketUrl( socket );
  55. if (resObj == null) {
  56. setInterval(function() {
  57. var address = socket.conn.request.headers.host;
  58. var obj = {};
  59. for (var prop in global.instances) {
  60. obj[prop] = {
  61. "instance":address + prop,
  62. "clients": Object.keys(global.instances[prop].clients).length
  63. };
  64. }
  65. var json = JSON.stringify(obj);
  66. socket.emit('getWebAppUpdate', json);
  67. }, 3000);
  68. // socket.on('getWebAppUpdate', function(msg){
  69. // });
  70. return
  71. }
  72. let processedURL = resObj.path;
  73. //get instance for new connection
  74. var namespace = GetNamespace( processedURL );
  75. if ( namespace == undefined ) {
  76. return;
  77. }
  78. //prepare for persistence request in case that's what this is
  79. var loadInfo = resObj.loadInfo //GetLoadForSocket( processedURL );
  80. var saveObject = resObj.saveObject //persistence.LoadSaveObject( loadInfo );
  81. //if it's a new instance, setup record
  82. if( !global.instances[ namespace ] ) {
  83. global.instances[ namespace ] = { };
  84. global.instances[ namespace ].clients = { };
  85. global.instances[ namespace ].pendingList = [ ];
  86. global.instances[ namespace ].start_time = undefined;
  87. global.instances[ namespace ].pause_time = undefined;
  88. global.instances[ namespace ].rate = 1.0;
  89. global.instances[ namespace ].setTime = function( time ) {
  90. this.start_time = GetNow( ) - time;
  91. this.pause_time = undefined;
  92. this.rate = 1.0;
  93. };
  94. global.instances[ namespace ].isPlaying = function( ) {
  95. if ( ( this.start_time != undefined ) && ( this.pause_time == undefined ) ) {
  96. return true;
  97. }
  98. return false
  99. };
  100. global.instances[ namespace ].isPaused = function( ) {
  101. if ( ( this.start_time != undefined ) && ( this.pause_time != undefined ) ) {
  102. return true;
  103. }
  104. return false
  105. };
  106. global.instances[ namespace ].isStopped = function( ) {
  107. if ( this.start_time == undefined ) {
  108. return true;
  109. }
  110. return false;
  111. };
  112. global.instances[ namespace ].getTime = function( ) {
  113. if ( this.isPlaying( ) ) {
  114. return ( GetNow( ) - this.start_time ) * this.rate;
  115. } else if ( this.isPaused( ) ) {
  116. return ( this.pause_time - this.start_time ) * this.rate;
  117. }
  118. else {
  119. return 0.0;
  120. }
  121. };
  122. global.instances[ namespace ].play = function( ) {
  123. if ( this.isStopped( ) ) {
  124. this.start_time = GetNow( );
  125. this.pause_time = undefined;
  126. } else if ( this.isPaused( ) ) {
  127. this.start_time = this.start_time + ( GetNow( ) - this.pause_time );
  128. this.pause_time = undefined;
  129. }
  130. };
  131. global.instances[ namespace ].pause = function( ) {
  132. if ( this.isPlaying( ) ) {
  133. this.pause_time = GetNow( );
  134. }
  135. };
  136. global.instances[ namespace ].stop = function( ) {
  137. if ( ( this.isPlaying( ) ) || ( this.isPaused( ) ) ) {
  138. this.start_time = undefined;
  139. this.pause_time = undefined;
  140. }
  141. };
  142. global.instances[ namespace ].setTime( 0.0 );
  143. if ( saveObject ) {
  144. if ( saveObject[ "queue" ] ) {
  145. if ( saveObject[ "queue" ][ "time" ] ) {
  146. global.instances[ namespace ].setTime( saveObject[ "queue" ][ "time" ] );
  147. }
  148. }
  149. }
  150. global.instances[ namespace ].state = { };
  151. var log;
  152. function generateLogFile() {
  153. try {
  154. if ( !fs.existsSync( './/log/' ) ) {
  155. fs.mkdir( './/log/', function ( err ) {
  156. if ( err ) {
  157. console.log ( err );
  158. }
  159. })
  160. }
  161. log = fs.createWriteStream( './/log/' + namespace.replace( /[\\\/]/g, '_' ), { 'flags': 'a' } );
  162. } catch( err ) {
  163. console.log( 'Error generating Node Server Log File\n');
  164. }
  165. }
  166. global.instances[ namespace ].Log = function ( message, level ) {
  167. if( global.logLevel >= level ) {
  168. if ( !log ) {
  169. generateLogFile();
  170. }
  171. log.write( message + '\n' );
  172. global.log( message + '\n' );
  173. }
  174. };
  175. global.instances[ namespace ].Error = function ( message, level ) {
  176. var red, brown, reset;
  177. red = '\u001b[31m';
  178. brown = '\u001b[33m';
  179. reset = '\u001b[0m';
  180. if ( global.logLevel >= level ) {
  181. if ( !log ) {
  182. generateLogFile();
  183. }
  184. log.write( message + '\n' );
  185. global.log( red + message + reset + '\n' );
  186. }
  187. };
  188. //keep track of the timer for this instance
  189. global.instances[ namespace ].timerID = setInterval( function ( ) {
  190. var message = { parameters: [ ], time: global.instances[ namespace ].getTime( ) };
  191. for ( var i in global.instances[ namespace ].clients ) {
  192. var client = global.instances[ namespace ].clients[ i ];
  193. if ( ! client.pending ) {
  194. client.emit( 'message', message );
  195. }
  196. }
  197. if(global.instances[ namespace ]){
  198. if ( global.instances[ namespace ].pendingList.pending ) {
  199. global.instances[ namespace ].pendingList.push( message );
  200. }
  201. }
  202. }, 50 );
  203. }
  204. //add the new client to the instance data
  205. global.instances[ namespace ].clients[ socket.id ] = socket;
  206. socket.pending = true;
  207. //Get the descriptor for the `clients.vwf` child.
  208. var clientDescriptor = GetClientDescriptor( socket );
  209. // The time for the setState message should be the time the new client joins, so save that time
  210. var setStateTime = global.instances[ namespace ].getTime( );
  211. // If this client is the first, it can just load the application, and mark it not pending
  212. if ( Object.keys( global.instances[ namespace ].clients ).length === 1 ) {
  213. if ( saveObject ) {
  214. socket.emit( 'message', {
  215. action: "setState",
  216. parameters: [ saveObject ],
  217. time: global.instances[ namespace ].getTime( )
  218. } );
  219. }
  220. else {
  221. var instance = namespace;
  222. //Get the state and load it.
  223. //Now the server has a rough idea of what the simulation is
  224. socket.emit( 'message', {
  225. action: "createNode",
  226. parameters: [ "http://vwf.example.com/clients.vwf" ],
  227. time: global.instances[ namespace ].getTime( )
  228. } );
  229. socket.emit( 'message', {
  230. action: "createNode",
  231. parameters: [
  232. ( processedURL.public_path === "/" ? "" : processedURL.public_path ) + "/" + processedURL.application,
  233. "application"
  234. ],
  235. time: global.instances[ namespace ].getTime( )
  236. } );
  237. }
  238. socket.pending = false;
  239. //xapi.logClient( saveObject, loadInfo[ 'application_path' ], loadInfo[ 'save_name' ], namespace, clientDescriptor.properties || {}, true, true );
  240. }
  241. else { //this client is not the first, we need to get the state and mark it pending
  242. if ( ! global.instances[ namespace ].pendingList.pending ) {
  243. var firstclient = Object.keys( global.instances[ namespace ].clients )[ 0 ];
  244. firstclient = global.instances[ namespace ].clients[ firstclient ];
  245. firstclient.emit( 'message', {
  246. action: "getState",
  247. respond: true,
  248. time: global.instances[ namespace ].getTime( )
  249. } );
  250. global.instances[ namespace ].Log( 'GetState from Client', 2 );
  251. global.instances[ namespace ].pendingList.pending = true;
  252. }
  253. socket.pending = true;
  254. }
  255. //Create a child in the application's 'clients.vwf' global to represent this client.
  256. var clientNodeMessage = {
  257. action: "createChild",
  258. parameters: [ "http://vwf.example.com/clients.vwf", socket.id, clientDescriptor ],
  259. time: global.instances[ namespace ].getTime( )
  260. };
  261. // Send messages to all the existing clients (that are not pending),
  262. // telling them to create a new node under the "clients" parent for the new client
  263. for ( var i in global.instances[ namespace ].clients ) {
  264. var client = global.instances[ namespace ].clients[ i ];
  265. if ( !client.pending ) {
  266. client.emit ( 'message', clientNodeMessage );
  267. }
  268. }
  269. if ( global.instances[ namespace ].pendingList.pending ) {
  270. global.instances[ namespace ].pendingList.push( clientNodeMessage );
  271. }
  272. socket.on( 'message', function ( msg ) {
  273. //need to add the client identifier to all outgoing messages
  274. try {
  275. var message = JSON.parse( msg );
  276. }
  277. catch ( e ) {
  278. console.error( "Error on socket message: ", e );
  279. return;
  280. }
  281. message.client = socket.id;
  282. message.time = global.instances[ namespace ].getTime( );
  283. if ( message.result === undefined ) {
  284. //distribute message to all clients on given instance
  285. for ( var i in global.instances[ namespace ].clients ) {
  286. var client = global.instances[ namespace ].clients[ i ];
  287. //just a regular message, so push if the client is pending a load, otherwise just send it.
  288. if ( ! client.pending ) {
  289. client.emit( 'message', message );
  290. }
  291. }
  292. if (global.instances[ namespace ]) {
  293. if ( global.instances[ namespace ].pendingList.pending ) {
  294. global.instances[ namespace ].pendingList.push( message );
  295. }
  296. }
  297. } else if ( message.action == "getState" ) {
  298. //distribute message to all clients on given instance
  299. for ( var i in global.instances[ namespace ].clients ) {
  300. var client = global.instances[ namespace ].clients[ i ];
  301. //if the message was get state, then fire all the pending messages after firing the setState
  302. if ( client.pending ) {
  303. global.instances[ namespace ].Log( 'Got State', 2 );
  304. var state = message.result;
  305. global.instances[ namespace ].Log( state, 2 );
  306. client.emit( 'message', { action: "setState", parameters: [ state ], time: setStateTime } );
  307. client.pending = false;
  308. for ( var j = 0; j < global.instances[ namespace ].pendingList.length; j++ ) {
  309. client.emit( 'message', global.instances[ namespace ].pendingList[ j ] );
  310. }
  311. //xapi.logClient( state, undefined, undefined, namespace, GetClientDescriptor( client ).properties || {}, true, false );
  312. }
  313. }
  314. global.instances[ namespace ].pendingList = [ ];
  315. } else if ( message.action === "execute" ) {
  316. var evaluation = socket.pendingEvaluations && socket.pendingEvaluations.shift();
  317. if ( evaluation ) {
  318. evaluation.resolve( message.result );
  319. clearTimeout( evaluation.timeout );
  320. }
  321. }
  322. } );
  323. // When a client disconnects, go ahead and remove the instance data
  324. socket.on( 'disconnect', function ( ) {
  325. // Remove the disconnecting client
  326. var leavingClient = global.instances[ namespace ].clients[ socket.id ];
  327. global.instances[ namespace ].clients[ socket.id ] = null;
  328. delete global.instances[ namespace ].clients[ socket.id ];
  329. if ( leavingClient.pendingEvaluations ) {
  330. leavingClient.pendingEvaluations.forEach( function( evaluation ) {
  331. evaluation.reject( new Error( "connection closed" ) );
  332. clearTimeout( evaluation.timeout );
  333. } );
  334. }
  335. // Notify others of the disconnecting client. Delete the child representing this client in the application's `clients.vwf` global.
  336. var clientMessage = { action: "deleteChild", parameters: [ "http://vwf.example.com/clients.vwf", socket.id ], time: global.instances[ namespace ].getTime( ) };
  337. for ( var i in global.instances[ namespace ].clients ) {
  338. var client = global.instances[ namespace ].clients[ i ];
  339. if ( ! client.pending ) {
  340. client.emit ( 'message', clientMessage );
  341. }
  342. }
  343. if ( global.instances[ namespace ].pendingList.pending ) {
  344. global.instances[ namespace ].pendingList.push( clientMessage );
  345. }
  346. // If it's the last client, delete the data and the timer
  347. if ( Object.keys( global.instances[ namespace ].clients ).length == 0 ) {
  348. clearInterval( global.instances[ namespace ].timerID );
  349. delete global.instances[ namespace ];
  350. // xapi.logClient( undefined, loadInfo[ 'application_path' ], loadInfo[ 'save_name' ], namespace, clientDescriptor.properties || {}, false, true );
  351. } else {
  352. // xapi.logClient( undefined, loadInfo[ 'application_path' ], loadInfo[ 'save_name' ], namespace, clientDescriptor.properties || {}, false, false );
  353. }
  354. } );
  355. }
  356. function Evaluate( namespace, node, expression ) {
  357. return new Promise( function( resolve, reject ) {
  358. var firstClientID = Object.keys( global.instances[ namespace ].clients )[ 0 ];
  359. var firstClient = global.instances[ namespace ].clients[ firstClientID ];
  360. if ( firstClient ) {
  361. firstClient.pendingEvaluations = firstClient.pendingEvaluations || [];
  362. firstClient.pendingEvaluations.push( {
  363. resolve: resolve,
  364. reject: reject,
  365. timeout: setTimeout( function() { reject( new Error( "timeout" ) ) }, 1000 ),
  366. } );
  367. firstClient.emit( "message", { node: node, action: "execute", parameters: [ expression ], respond: true, time: global.instances[ namespace ].getTime() } );
  368. } else {
  369. reject( new Error( "no clients are connected" ) );
  370. }
  371. } );
  372. }
  373. /// Get a descriptor for the `clients.vwf` child for a new client. An authenticator may set a
  374. /// descriptor in the session at `session.vwf.client`. If the authenticator doesn't provide a
  375. /// descriptor, use an empty node inheriting from `client.vwf`.
  376. function GetClientDescriptor( socket ) {
  377. // socket.io doesn't provide access to the request and the session, but we do have the cookies.
  378. // Create a mock request and run it through the session middleware to recreate the session. This
  379. // creates a session object at `mockRequest.session`.
  380. var mockRequest = {
  381. headers: { cookie: socket.handshake.headers.cookie },
  382. connection: {},
  383. session: {},
  384. };
  385. var mockResponse = {
  386. getHeader: function() {},
  387. setHeader: function() {},
  388. };
  389. sessionStack.forEach( function( middleware ) {
  390. middleware( mockRequest, mockResponse, function() {} );
  391. } );
  392. // Get the descriptor from `vwf.client` in the session.
  393. var descriptor = ( mockRequest.session.vwf || {} ).client || {};
  394. // Set the default prototype.
  395. if ( ! descriptor.extends ) {
  396. descriptor.extends = "http://vwf.example.com/client.vwf";
  397. }
  398. return descriptor;
  399. }
  400. /// Middleware stack to parse a cookie session from `req.headers.cookie` into `req.session`.
  401. var sessionStack = [
  402. //cookieParser(),
  403. //cookieSession( { secret: config.get( 'session.secret' ) } ),
  404. ];
  405. function GetInstances() {
  406. return global.instances;
  407. }
  408. exports.OnConnection = OnConnection;
  409. exports.Evaluate = Evaluate;
  410. exports.GetInstances = GetInstances;