asworker.js 14 KB

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