reflector.js 19 KB

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