asworker.js 14 KB

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