asworker.js 15 KB

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