asworker.js 15 KB

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