asworker.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. /*******************************************************************************
  2. AToMPM - A Tool for Multi-Paradigm Modelling
  3. Copyright (c) 2011 Raphael Mannadiar (raphael.mannadiar@mail.mcgill.ca)
  4. This file is part of AToMPM.
  5. AToMPM is free software: you can redistribute it and/or modify it under the
  6. terms of the GNU Lesser General Public License as published by the Free Software
  7. Foundation, either version 3 of the License, or (at your option) any later
  8. version.
  9. AToMPM is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
  11. PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with AToMPM. If not, see <http://www.gnu.org/licenses/>.
  14. *******************************************************************************/
  15. {
  16. /************************** REST REQUEST HANDLING **************************/
  17. /* INTENT :
  18. ask our mtworker to do something (e.g., change transformation execution
  19. mode)
  20. IN PRACTICE:
  21. adjust uri and forward to mtworker
  22. 1. setup sync/async action chaining
  23. a) if this asworker doesn't already have an mtworker
  24. i. create mtworker
  25. ii. subscribe it to this asworker
  26. iii. send it this asworker's current model
  27. b) ask asworker to forward initial request to its mtworker
  28. 2. launch chain... return success code or error */
  29. '__mtwid':undefined,
  30. 'mtwRequest' :
  31. function(resp,method,uri,reqData)
  32. {
  33. var self = this,
  34. actions =
  35. [__successContinuable(),
  36. function()
  37. {
  38. uri = uri.substring('/__mt'.length);
  39. return __httpReq(
  40. method,
  41. uri+'?wid='+self.__mtwid,
  42. reqData,
  43. 8125);
  44. }];
  45. if( this.__mtwid == undefined )
  46. {
  47. if( reqData == undefined ||
  48. reqData['transfs'] == undefined ||
  49. reqData['transfs'].length == 0 )
  50. return __postInternalErrorMsg(resp,'missing transformations');
  51. else if( reqData == undefined ||
  52. reqData['username'] == undefined ||
  53. reqData['username'].length == 0 )
  54. return __postInternalErrorMsg(resp,'missing username');
  55. actions.splice(1,0,
  56. function()
  57. {
  58. return __httpReq(
  59. 'PUT',
  60. '/GET/console?wid='+__wid,
  61. {'text':'please wait while model transformation module'+
  62. ' initializes (this may take a few seconds)'});
  63. },
  64. function()
  65. {
  66. return __httpReq('POST','/mtworker',undefined,8125);
  67. },
  68. function(mtwid)
  69. {
  70. self.__mtwid = mtwid;
  71. return __httpReq(
  72. 'PUT',
  73. '/aswSubscription?wid='+self.__mtwid,
  74. {'aswid':__wid},
  75. 8125);
  76. },
  77. function()
  78. {
  79. return _fs.readFile('./users/'+reqData['username']+
  80. '/prefs','utf8');
  81. },
  82. function(prefs)
  83. {
  84. try {prefs = eval('('+prefs+')');}
  85. catch(err) {
  86. return __errorContinuable(
  87. 'an error occurred while reading your preferences '+
  88. '(you must restart your client before successful '+
  89. 'model transformation module initialization becomes'+
  90. ' possible :: '+err);}
  91. return __httpReq(
  92. 'PUT',
  93. '/envvars?wid='+self.__mtwid,
  94. {'username':reqData['username'],
  95. 'defaultDCL':prefs['default-mt-dcl']['value']},
  96. 8125);
  97. },
  98. function()
  99. {
  100. if( (mms = _mmmk.readMetamodels())['$err'] )
  101. return __errorContinuable(mms['$err']);
  102. else if( (m = _mmmk.read())['$err'] )
  103. return __errorContinuable(m['$err']);
  104. return __httpReq(
  105. 'PUT',
  106. '/current.model?wid='+self.__mtwid,
  107. {'mms':mms,
  108. 'm':m,
  109. 'sequence#':__sequenceNumber(0)},
  110. 8125);
  111. },
  112. function()
  113. {
  114. return __httpReq(
  115. 'PUT',
  116. '/current.transform?wid='+self.__mtwid,
  117. {'transfs':reqData['transfs']},
  118. 8125);
  119. },
  120. function()
  121. {
  122. return __httpReq(
  123. 'PUT',
  124. '/GET/console?wid='+__wid,
  125. {'text':'model tranformation module is ready to go!'});
  126. }
  127. );
  128. }
  129. _do.chain(actions)(
  130. function()
  131. {
  132. __postMessage({'statusCode':200, 'respIndex':resp});
  133. },
  134. function(err) {__postInternalErrorMsg(resp,err);}
  135. );
  136. },
  137. /* load a metamodel
  138. 1. setup sync/async action chaining
  139. a) if no hitchhiker containing CSMM information is provided, or if only
  140. a CSMM name is provided, setup hitchihiker construction/completion
  141. b) read specified mm from disk
  142. 2. launch chain... on success, load requested metamodel into _mmmk and
  143. return success code and 'hitchhiker' (see notes at top of csworker.js
  144. for more about 'hitchhikers')... on error, return error */
  145. 'PUT /current.metamodels' :
  146. function(resp,uri,reqData/*mm,hitchhiker*/)
  147. {
  148. var actions = [__successContinuable()];
  149. if( reqData['hitchhiker'] == undefined ||
  150. 'path' in reqData['hitchhiker'] )
  151. actions.push(
  152. function()
  153. {
  154. var ext = (reqData['mm'].match(/\.pattern\.metamodel$/) ?
  155. '.pattern.metamodel' :
  156. '.metamodel'),
  157. path =
  158. (reqData['hitchhiker'] && 'path' in reqData['hitchhiker'] ?
  159. reqData['hitchhiker']['path'] :
  160. reqData['mm'].match(/(.*)\.metamodel/)[1]+
  161. '.defaultIcons'+ext),
  162. name = path.match(/.+?(\/.*)\.metamodel/)[1];
  163. reqData['hitchhiker'] = {};
  164. reqData['hitchhiker']['name'] = name;
  165. return _fs.readFile('./users'+path,'utf8');
  166. },
  167. function(csmmData)
  168. {
  169. reqData['hitchhiker']['csmm'] = csmmData;
  170. return __successContinuable();
  171. });
  172. actions.push(
  173. function()
  174. {
  175. return _fs.readFile('./users'+reqData['mm'],'utf8');
  176. });
  177. _do.chain(actions)(
  178. function(asmmData)
  179. {
  180. var mm = reqData['mm'].match(/.+?(\/.*)\.metamodel/)[1],
  181. res = _mmmk.loadMetamodel(mm,asmmData);
  182. __postMessage(
  183. {'statusCode':200,
  184. 'changelog':res['changelog'],
  185. 'sequence#':__sequenceNumber(),
  186. 'hitchhiker':reqData['hitchhiker'],
  187. 'respIndex':resp});
  188. },
  189. function(err) {__postInternalErrorMsg(resp,err);}
  190. );
  191. },
  192. /* unload a metamodel (deletes all entities from that metamodel) */
  193. 'DELETE *.metamodel' :
  194. function(resp,uri)
  195. {
  196. var mm = uri.match(/(.*)\.metamodel/)[1],
  197. res = _mmmk.unloadMetamodel(mm);
  198. __postMessage(
  199. {'statusCode':200,
  200. 'changelog':res['changelog'],
  201. 'sequence#':__sequenceNumber(),
  202. 'respIndex':resp});
  203. },
  204. /* load a model */
  205. 'PUT /current.model' :
  206. function(resp,uri,reqData/*m,name,insert,hitchhiker*/)
  207. {
  208. if( (res = _mmmk.loadModel(
  209. reqData['name'],
  210. reqData['m'],
  211. reqData['insert']))['$err'] )
  212. __postInternalErrorMsg(resp,res['$err']);
  213. else
  214. __postMessage(
  215. {'statusCode':200,
  216. 'changelog':res['changelog'],
  217. 'sequence#':__sequenceNumber(),
  218. 'hitchhiker':reqData['hitchhiker'],
  219. 'respIndex':resp});
  220. },
  221. /* create a new instance of type... if reqData has 'src' and 'dest' fields,
  222. type is a connector
  223. 1. if *.type is a node, ask _mmmk to create it
  224. 1. if *.type is a connector, ask _mmmk to create it and connect
  225. its endpoints
  226. 2. return success or error code
  227. NOTE:: since create() is given 'attrs' (i.e., these aren't given to
  228. update() after creation), it is important that post-edit
  229. constraints also be made post-create constraints... otherwise, it
  230. would be possible to create nodes via copy-paste that would
  231. otherwise be blocked by post-edit constraints */
  232. 'POST *.type' :
  233. function(resp,uri,reqData/*[src,dest],hitchhiker,attrs*/)
  234. {
  235. var matches = uri.match(/(.*)\.type/),
  236. fulltype = matches[1],
  237. res = (reqData == undefined || reqData['src'] == undefined ?
  238. _mmmk.create(fulltype,reqData['attrs']) :
  239. _mmmk.connect(
  240. __uri_to_id(reqData['src']),
  241. __uri_to_id(reqData['dest']),
  242. fulltype,
  243. reqData['attrs']));
  244. if( '$err' in res )
  245. __postInternalErrorMsg(resp,res['$err']);
  246. else
  247. __postMessage(
  248. {'statusCode':200,
  249. 'changelog':res['changelog'],
  250. 'data':res['id'],
  251. 'sequence#':__sequenceNumber(),
  252. 'hitchhiker':reqData['hitchhiker'],
  253. 'respIndex':resp});
  254. },
  255. /* return an instance */
  256. 'GET *.instance' :
  257. function(resp,uri)
  258. {
  259. var id = __uri_to_id(uri);
  260. if( (res = _mmmk.read(id))['$err'] )
  261. __postInternalErrorMsg(resp,res['$err']);
  262. else
  263. __postMessage(
  264. {'statusCode':200,
  265. 'data':res,
  266. 'sequence#':__sequenceNumber(0),
  267. 'respIndex':resp});
  268. },
  269. /* updates an instance
  270. NOTE:: if this update produces no changelog *and* to-do-cschanges are
  271. bundled, we return a dummy changelog that ensures the said to-do-
  272. cschanges get handled by csworker.__applyASWChanges().CHATTR */
  273. 'PUT *.instance' :
  274. function(resp,uri,reqData/*changes[,hitchhiker]*/)
  275. {
  276. var id = __uri_to_id(uri);
  277. if( (res = _mmmk.update(id,reqData['changes']))['$err'] )
  278. __postInternalErrorMsg(resp,res['$err']);
  279. else
  280. {
  281. var changelog =
  282. (res['changelog'].length == 0 && reqData['hitchhiker'] ?
  283. [{'op':'CHATTR','id':id}] :
  284. res['changelog']);
  285. __postMessage(
  286. {'statusCode':200,
  287. 'changelog':changelog,
  288. 'sequence#':__sequenceNumber(),
  289. 'hitchhiker':reqData['hitchhiker'],
  290. 'respIndex':resp});
  291. }
  292. },
  293. 'POST *.instance.click' :
  294. function(id,vid)
  295. {
  296. //TODO
  297. },
  298. /* delete an instance
  299. NOTE:: this function does not return asworker errors to the client (see
  300. NOTE for csworker.DELETE *.instance with the difference that in
  301. this context, the client is the mtworker) */
  302. 'DELETE *.instance' :
  303. function(resp,uri)
  304. {
  305. var id = __uri_to_id(uri);
  306. if( (res = _mmmk.read(id))['$err'] )
  307. __postMessage({'statusCode':200, 'respIndex':resp});
  308. else if( (res = _mmmk['delete'](id))['$err'] )
  309. __postInternalErrorMsg(resp,res['$err']);
  310. else
  311. __postMessage(
  312. {'statusCode':200,
  313. 'changelog':res['changelog'],
  314. 'sequence#':__sequenceNumber(),
  315. 'respIndex':resp});
  316. },
  317. /* generate a metamodel from the current model and write it to disk
  318. 1. generate metamodel
  319. 1. setup sync/async action chaining
  320. a) write specified mm to disk
  321. 2. launch chain... return success or error code */
  322. 'PUT *.metamodel' :
  323. function(resp,uri,reqData/*[csm]*/)
  324. {
  325. if( uri.match(/(.*)\..*Icons\.metamodel/) &&
  326. (res = _mmmk.
  327. compileToIconDefinitionMetamodel(reqData['csm'], reqData['asmm']))['$err'] )
  328. __postInternalErrorMsg(resp,res['$err']);
  329. else if( ! uri.match(/(.*)\..*Icons\.metamodel/) &&
  330. (res = _mmmk.compileToMetamodel())['$err'] )
  331. __postInternalErrorMsg(resp,res['$err']);
  332. else
  333. {
  334. var uri = uri.substring('/GET'.length),
  335. actions = [_fs.writeFile('./users'+uri,res)];
  336. _do.chain(actions)(
  337. function()
  338. {
  339. __postMessage(
  340. {'statusCode':200,
  341. 'respIndex':resp});
  342. },
  343. function(err) {__postInternalErrorMsg(resp,err);}
  344. );
  345. }
  346. },
  347. /* validate a model */
  348. 'GET /validatem' :
  349. function(resp)
  350. {
  351. var err = _mmmk.validateModel();
  352. if( err )
  353. __postInternalErrorMsg(resp,err['$err']);
  354. else
  355. __postMessage(
  356. {'statusCode':200,
  357. 'respIndex':resp});
  358. },
  359. /* undo the effects of a csworker's last not yet undone action
  360. OR
  361. undo until the specified user-checkpoint */
  362. 'POST /undo' :
  363. function(resp,uri,reqData/*[undoUntil],hitchhiker*/)
  364. {
  365. __postMessage(
  366. {'statusCode':200,
  367. 'changelog':_mmmk.undo(reqData['undoUntil'])['changelog'],
  368. 'sequence#':__sequenceNumber(),
  369. 'hitchhiker':reqData['hitchhiker'],
  370. 'respIndex':resp});
  371. },
  372. /* redo the effects of a csworker's last undone action
  373. OR
  374. redo until the specified user-checkpoint */
  375. 'POST /redo' :
  376. function(resp,uri,reqData/*[redoUntil],hitchhiker*/)
  377. {
  378. __postMessage(
  379. {'statusCode':200,
  380. 'changelog':_mmmk.redo(reqData['redoUntil'])['changelog'],
  381. 'sequence#':__sequenceNumber(),
  382. 'hitchhiker':reqData['hitchhiker'],
  383. 'respIndex':resp});
  384. },
  385. /* evaluate a set of mapping functions (i.e., those functions that compute
  386. the values of coded VisualObject attributes based on the AS model)... of
  387. interest is that this function 'succeeds' even if one or more of the given
  388. mapping function produces an error: in such cases, the new value of the
  389. associated attribute will be the produced error
  390. NOTE:
  391. this request is actually a GET : it doesn't change anything anywhere...
  392. however, due to the possibly large amount of reqData it requires, we're
  393. forced to make it a POST */
  394. 'POST *.mappings' :
  395. function(resp,uri,reqData/*{...,fullvid:mapper,...}*/)
  396. {
  397. var id = __uri_to_id(uri),
  398. attrVals = {};
  399. for( var fullvid in reqData )
  400. {
  401. var res = _mmmk.runDesignerAccessorCode(
  402. reqData[fullvid],
  403. 'mapper evaluation ('+uri+')',
  404. id);
  405. if( res == undefined )
  406. continue;
  407. else if( !_utils.isObject(res) )
  408. {
  409. attrVals =
  410. {'$err':
  411. 'mapper returned non-dictionary type :: '+(typeof res)};
  412. break;
  413. }
  414. else if( '$err' in res )
  415. {
  416. attrVals = res;
  417. break;
  418. }
  419. else
  420. for( var attr in res )
  421. attrVals[fullvid+attr] = res[attr];
  422. }
  423. __postMessage(
  424. {'statusCode':200,
  425. 'data':attrVals,
  426. 'respIndex':resp});
  427. },
  428. /* little hack that allows pretty much anyone to send some text to the client
  429. for console output... this is currently used by mtworkers to post feedback
  430. about the state of a running transformation... eventually, it could also
  431. be used to implement inter-collaborator chatting */
  432. 'PUT /GET/console' :
  433. function(resp,uri,reqData/*text*/)
  434. {
  435. __postMessage(
  436. {'statusCode':200,
  437. 'changelog':[{'op':'SYSOUT','text':reqData['text']}],
  438. 'sequence#':__sequenceNumber(),
  439. 'respIndex':resp});
  440. },
  441. /* place an easily identifiable user-checkpoint in the journal */
  442. 'POST /batchCheckpoint' :
  443. function(resp,uri,reqData)
  444. {
  445. _mmmk.setUserCheckpoint(reqData['name']);
  446. __postMessage(
  447. {'statusCode':200,
  448. 'changelog':[{'op':'MKBTCCHKPT','name':reqData['name']}],
  449. 'sequence#':__sequenceNumber(),
  450. 'respIndex':resp});
  451. }
  452. }