reflector.js 19 KB

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