asworker.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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) {
  190. if (err['code'].includes("ENOENT")) {
  191. err = "Error! File not found: " + err['path'];
  192. }
  193. __postInternalErrorMsg(resp, err);
  194. }
  195. );
  196. },
  197. /* unload a metamodel (deletes all entities from that metamodel) */
  198. 'DELETE *.metamodel' :
  199. function(resp,uri)
  200. {
  201. var mm = uri.match(/(.*)\.metamodel/)[1],
  202. res = _mmmk.unloadMetamodel(mm);
  203. __postMessage(
  204. {'statusCode':200,
  205. 'changelog':res['changelog'],
  206. 'sequence#':__sequenceNumber(),
  207. 'respIndex':resp});
  208. },
  209. /* load a model */
  210. 'PUT /current.model' :
  211. function(resp,uri,reqData/*m,name,insert,hitchhiker*/)
  212. {
  213. if( (res = _mmmk.loadModel(
  214. reqData['name'],
  215. reqData['m'],
  216. reqData['insert']))['$err'] )
  217. __postInternalErrorMsg(resp,res['$err']);
  218. else
  219. __postMessage(
  220. {'statusCode':200,
  221. 'changelog':res['changelog'],
  222. 'sequence#':__sequenceNumber(),
  223. 'hitchhiker':reqData['hitchhiker'],
  224. 'respIndex':resp});
  225. },
  226. /* create a new instance of type... if reqData has 'src' and 'dest' fields,
  227. type is a connector
  228. 1. if *.type is a node, ask _mmmk to create it
  229. 1. if *.type is a connector, ask _mmmk to create it and connect
  230. its endpoints
  231. 2. return success or error code
  232. NOTE:: since create() is given 'attrs' (i.e., these aren't given to
  233. update() after creation), it is important that post-edit
  234. constraints also be made post-create constraints... otherwise, it
  235. would be possible to create nodes via copy-paste that would
  236. otherwise be blocked by post-edit constraints */
  237. 'POST *.type' :
  238. function(resp,uri,reqData/*[src,dest],hitchhiker,attrs*/)
  239. {
  240. var matches = uri.match(/(.*)\.type/),
  241. fulltype = matches[1],
  242. res = (reqData == undefined || reqData['src'] == undefined ?
  243. _mmmk.create(fulltype,reqData['attrs']) :
  244. _mmmk.connect(
  245. __uri_to_id(reqData['src']),
  246. __uri_to_id(reqData['dest']),
  247. fulltype,
  248. reqData['attrs']));
  249. if( '$err' in res )
  250. __postInternalErrorMsg(resp,res['$err']);
  251. else
  252. __postMessage(
  253. {'statusCode':200,
  254. 'changelog':res['changelog'],
  255. 'data':res['id'],
  256. 'sequence#':__sequenceNumber(),
  257. 'hitchhiker':reqData['hitchhiker'],
  258. 'respIndex':resp});
  259. },
  260. /* return an instance */
  261. 'GET *.instance' :
  262. function(resp,uri)
  263. {
  264. var id = __uri_to_id(uri);
  265. if( (res = _mmmk.read(id))['$err'] )
  266. __postInternalErrorMsg(resp,res['$err']);
  267. else
  268. __postMessage(
  269. {'statusCode':200,
  270. 'data':res,
  271. 'sequence#':__sequenceNumber(0),
  272. 'respIndex':resp});
  273. },
  274. /* updates an instance
  275. NOTE:: if this update produces no changelog *and* to-do-cschanges are
  276. bundled, we return a dummy changelog that ensures the said to-do-
  277. cschanges get handled by csworker.__applyASWChanges().CHATTR */
  278. 'PUT *.instance' :
  279. function(resp,uri,reqData/*changes[,hitchhiker]*/)
  280. {
  281. var id = __uri_to_id(uri);
  282. if( (res = _mmmk.update(id,reqData['changes']))['$err'] )
  283. __postInternalErrorMsg(resp,res['$err']);
  284. else
  285. {
  286. var changelog =
  287. (res['changelog'].length == 0 && reqData['hitchhiker'] ?
  288. [{'op':'CHATTR','id':id}] :
  289. res['changelog']);
  290. __postMessage(
  291. {'statusCode':200,
  292. 'changelog':changelog,
  293. 'sequence#':__sequenceNumber(),
  294. 'hitchhiker':reqData['hitchhiker'],
  295. 'respIndex':resp});
  296. }
  297. },
  298. 'POST *.instance.click' :
  299. function(id,vid)
  300. {
  301. //TODO
  302. },
  303. /* delete an instance
  304. NOTE:: this function does not return asworker errors to the client (see
  305. NOTE for csworker.DELETE *.instance with the difference that in
  306. this context, the client is the mtworker) */
  307. 'DELETE *.instance' :
  308. function(resp,uri)
  309. {
  310. var id = __uri_to_id(uri);
  311. if( (res = _mmmk.read(id))['$err'] )
  312. __postMessage({'statusCode':200, 'respIndex':resp});
  313. else if( (res = _mmmk['delete'](id))['$err'] )
  314. __postInternalErrorMsg(resp,res['$err']);
  315. else
  316. __postMessage(
  317. {'statusCode':200,
  318. 'changelog':res['changelog'],
  319. 'sequence#':__sequenceNumber(),
  320. 'respIndex':resp});
  321. },
  322. /* generate a metamodel from the current model and write it to disk
  323. 1. generate metamodel
  324. 1. setup sync/async action chaining
  325. a) write specified mm to disk
  326. 2. launch chain... return success or error code */
  327. 'PUT *.metamodel' :
  328. function(resp,uri,reqData/*[csm]*/)
  329. {
  330. if( uri.match(/(.*)\..*Icons\.metamodel/) &&
  331. (res = _mmmk.
  332. compileToIconDefinitionMetamodel(reqData['csm'], reqData['asmm']))['$err'] )
  333. __postInternalErrorMsg(resp,res['$err']);
  334. else if( ! uri.match(/(.*)\..*Icons\.metamodel/) &&
  335. (res = _mmmk.compileToMetamodel())['$err'] )
  336. __postInternalErrorMsg(resp,res['$err']);
  337. else
  338. {
  339. var uri = uri.substring('/GET'.length),
  340. actions = [_fs.writeFile('./users'+uri,res)];
  341. _do.chain(actions)(
  342. function()
  343. {
  344. __postMessage(
  345. {'statusCode':200,
  346. 'respIndex':resp});
  347. },
  348. function(err) {__postInternalErrorMsg(resp,err);}
  349. );
  350. }
  351. },
  352. /* validate a model */
  353. 'GET /validatem' :
  354. function(resp)
  355. {
  356. var err = _mmmk.validateModel();
  357. if( err )
  358. __postInternalErrorMsg(resp,err['$err']);
  359. else
  360. __postMessage(
  361. {'statusCode':200,
  362. 'respIndex':resp});
  363. },
  364. /* undo the effects of a csworker's last not yet undone action
  365. OR
  366. undo until the specified user-checkpoint */
  367. 'POST /undo' :
  368. function(resp,uri,reqData/*[undoUntil],hitchhiker*/)
  369. {
  370. __postMessage(
  371. {'statusCode':200,
  372. 'changelog':_mmmk.undo(reqData['undoUntil'])['changelog'],
  373. 'sequence#':__sequenceNumber(),
  374. 'hitchhiker':reqData['hitchhiker'],
  375. 'respIndex':resp});
  376. },
  377. /* redo the effects of a csworker's last undone action
  378. OR
  379. redo until the specified user-checkpoint */
  380. 'POST /redo' :
  381. function(resp,uri,reqData/*[redoUntil],hitchhiker*/)
  382. {
  383. __postMessage(
  384. {'statusCode':200,
  385. 'changelog':_mmmk.redo(reqData['redoUntil'])['changelog'],
  386. 'sequence#':__sequenceNumber(),
  387. 'hitchhiker':reqData['hitchhiker'],
  388. 'respIndex':resp});
  389. },
  390. /* evaluate a set of mapping functions (i.e., those functions that compute
  391. the values of coded VisualObject attributes based on the AS model)... of
  392. interest is that this function 'succeeds' even if one or more of the given
  393. mapping function produces an error: in such cases, the new value of the
  394. associated attribute will be the produced error
  395. NOTE:
  396. this request is actually a GET : it doesn't change anything anywhere...
  397. however, due to the possibly large amount of reqData it requires, we're
  398. forced to make it a POST */
  399. 'POST *.mappings' :
  400. function(resp,uri,reqData/*{...,fullvid:mapper,...}*/)
  401. {
  402. var id = __uri_to_id(uri),
  403. attrVals = {};
  404. for( var fullvid in reqData )
  405. {
  406. var res = _mmmk.runDesignerAccessorCode(
  407. reqData[fullvid],
  408. 'mapper evaluation ('+uri+')',
  409. id);
  410. if( res == undefined )
  411. continue;
  412. else if( !_utils.isObject(res) )
  413. {
  414. attrVals =
  415. {'$err':
  416. 'mapper returned non-dictionary type :: '+(typeof res)};
  417. break;
  418. }
  419. else if( '$err' in res )
  420. {
  421. attrVals = res;
  422. break;
  423. }
  424. else
  425. for( var attr in res )
  426. attrVals[fullvid+attr] = res[attr];
  427. }
  428. __postMessage(
  429. {'statusCode':200,
  430. 'data':attrVals,
  431. 'respIndex':resp});
  432. },
  433. /* little hack that allows pretty much anyone to send some text to the client
  434. for console output... this is currently used by mtworkers to post feedback
  435. about the state of a running transformation... eventually, it could also
  436. be used to implement inter-collaborator chatting */
  437. 'PUT /GET/console' :
  438. function(resp,uri,reqData/*text*/)
  439. {
  440. __postMessage(
  441. {'statusCode':200,
  442. 'changelog':[{'op':'SYSOUT','text':reqData['text']}],
  443. 'sequence#':__sequenceNumber(),
  444. 'respIndex':resp});
  445. },
  446. /* place an easily identifiable user-checkpoint in the journal */
  447. 'POST /batchCheckpoint' :
  448. function(resp,uri,reqData)
  449. {
  450. _mmmk.setUserCheckpoint(reqData['name']);
  451. __postMessage(
  452. {'statusCode':200,
  453. 'changelog':[{'op':'MKBTCCHKPT','name':reqData['name']}],
  454. 'sequence#':__sequenceNumber(),
  455. 'respIndex':resp});
  456. }
  457. }