reflector.js 18 KB

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