csworker.js 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268
  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. /* NOTES:
  6. it is assumed that csworker _mmmk cud operations NEVER FAIL...
  7. 1. IMPLICATIONS
  8. a) we don't check for failure
  9. b) if failure were to occur, we wouldn't rollback the associated
  10. asworker perations
  11. c) *Icons.metamodels should NOT support actions, constraints or
  12. multiplicities to ensure neither of these block cud operations...
  13. they do however support parsing functions (designer code that
  14. translates CS updates into AS operations) which are somewhat akin to
  15. pre-edit actions: if the parsing function or the AS operations fail,
  16. the CS update fails
  17. 2. REASONING
  18. a) if we allowed csworker to rollback asworker operations, it would be
  19. a natural extension for csworkers to be allowed to fail and "respond
  20. negatively" to pushed changelogs and request asworker rollbacks...
  21. this might cause severe user experience problems in collaboration
  22. scenarios (e.g., A's changes could be repeatedly undone by failures
  23. produced by B's csworker)
  24. b) it doesn't make sense for logic that could overturn AS cud
  25. operations to live anywhere else than in the AS spec
  26. csworker cud operations are CHANGELOG-DRIVEN... in other words, when a client
  27. makes PUT/POST/DELETE requests to a csworker, these are translated into
  28. appropriate requests for an asworker...
  29. 1. on success, the asworker
  30. a) returns a 20x status code to the csworker who made the request, in
  31. turn, it forwards it to the client who made the request
  32. b) returns a changelog that describes the AS impacts of the request...
  33. this changelog is pushed to all of its csworker subscribers
  34. (including the one who made the request) and which point their
  35. internal CS models are adjusted to reflect AS changes... finally,
  36. the result of these CS model modifications are themselves bundled
  37. into changelogs that are forwarded to all subscribed clients
  38. (subscription managment is performed in httpwsd.js)
  39. 2. on failure, the asworker
  40. a) returns a 40x|50x status code to the csworker...
  41. so basically, when a client asks a csworker to change something, all that
  42. csworker does is forward the request to its asworker... if and when the
  43. csworker does comply, it will be in response to an asworker changelog
  44. received sometime after it has responded a 20x status code to the client
  45. 'HITCHHIKERS' allow subscriber information exchange... for instance, if A
  46. loads SC.purpleIcons.metamodel, we'd like for all csworkers subscribed to A's
  47. associated asworker to be told (1) that their asworker has loaded
  48. SC.metamodel *and* (2) that they should load SC.purpleIcons.metamodel... with
  49. hitchhikers, 'subscriber-relevant' but 'worker-irrelevant' data is sent to
  50. workers so that they may push it back to all of their subscribers upon
  51. returning
  52. technically, asworkers and csworkers could be run on DISTINCT MACHINES...
  53. however, for the moment, this is neither supported nor recommended:
  54. 1. csworkers as they are now are not robust to asworker failures caused by
  55. timeouts and/or other network problems
  56. 2. requests to asworkers would need to be prepended with the actual url of
  57. wherever the asworker is being served from
  58. there are at least 3 alternatives for EVALUATING A MAPPING FUNCTION
  59. 1. retrieve the full AS model and run the mapping function within this
  60. csworker within some scope where the said model is accessible via the
  61. designer API (ala. _mmmk.__runDesignerCode())
  62. + RESTful requests to asworker
  63. - possibly very inefficient to transmit AS model
  64. 2. run the mapping function within this csworker within some scope where
  65. calls to getAttr() are translated to REST that retrieve desired
  66. information from the asworker
  67. + RESTful requests to asworker
  68. - possibly numerous queries
  69. 3. send mapping function to asworker and run it there
  70. - non-RESTful request
  71. + most efficient in terms of data traffic
  72. we chose the 3rd approach for its efficiency... furthermore, when
  73. regenerating icons (who may contain numerous VisualObjects with numerous
  74. coded attributes), to avoid having to send many queries to the asworker
  75. (i.e., one for each mappingf), we bundle together all of the icon's mappingfs
  76. and send them to the asworker for evaluation in a single query
  77. CREATING AN ICON AT A SPECIFIC POSITION brings up a few issues in the context
  78. where icon position plays a role in AS attribute values... consider this
  79. scenario:
  80. 1. user creates a BuildingIcon at (500,600)
  81. 2. request is received by csworker and forwarded to asworker
  82. 3. asworker creates a Building and sets abstract attribute 'address' to
  83. metamodel-specified default (0,0)
  84. 4. later, __applyASWChanges() receives MKNODE
  85. a) it creates a BuildingIcon
  86. b) sets its 'position' to (500,600)
  87. c) calls __regenIcon() who determines that 'position' should be (0,0)
  88. after mapping AS attribute 'address'
  89. d) emits changelog instructing client to create a BuildingIcon at (0,0)
  90. the core issue here is that step 4b) is a hack... instead of 'position' being
  91. set via 'PUT *.cs' which would have parsed 'position', appropriately updated
  92. 'address', and only later -- via AS changelog -- mapped 'address' and updated
  93. 'position', step 4b) bypasses this whole pipeline... this causes CS and AS to
  94. be out-of-sync, which in turn causes the behaviour described for step 4c)...
  95. to address this issue, during step 2 we perform a task similar to that of
  96. 'PUT *.cs'... step 2 from the above scenario thus becomes:
  97. 0. request is received by csworker
  98. A. retrieve the BuildingIcon's parser
  99. B. create a dummy context where a *Icon's parser can be run... within this
  100. context, 'orientation' and 'scale' are set to their defaults, but
  101. 'position' is set to (500,600)
  102. C. run the BuildingIcon's parser within this dummy context, this could
  103. yield {'address':(5,6)}
  104. D. forwarded creation request to asworker *and* bundle the result from
  105. step C.
  106. step 3 is also slightly changed: the asworker creates a new Building *and*
  107. updates any specified attributes, in our example, 'address' would be set to
  108. (5,6)... step 4 is left unchanged but step 4c) no longer causes any problems
  109. because __regenIcon's mapping of 'address' will return (500,600)
  110. supporting undo/redo requires REMEMBERING HITCHHIKERS... __applyASWChanges()
  111. sometimes expects asworker changelogs to be bundled with hitchhikers... this
  112. is the case when changelogs are the result of 'normal' requests getting
  113. forwarded to the asworker by the csworker... however, for undos/redos, no
  114. hitchhikers are bundled and as such, when __applyASWChanges() is called as a
  115. result of undos and redos on the asworker, required information that would
  116. normally be in hitchhikers is missing... to address this, we 'remember'
  117. hitchhikers as we encounter them like so:
  118. 1. MKNODE hitchhikers are remembered by asid
  119. 2. LOADMM hitchhikers are remembered by asmm
  120. 3. RESETM hitchhikers are remembered by name *
  121. * for this case, we also create and remember a hitchhiker to enable
  122. undoing loading a model over an unsaved non-empty model
  123. long story short, when handling asworker changelogs, missing hitchhikers, if
  124. any, are retrieved from the __hitchhikerJournal
  125. supporting FULL UNDO/REDO in our distributed environment presents a few
  126. challenges
  127. 1. operations with no AS implications should be undone/redone by csworkers
  128. 2. operations with AS implications should be undone/redone by asworkers
  129. *but* resulting changelogs should be handled specially to ensure that
  130. csworkers undo/redo in response to asworer undo/redos
  131. challenge 1 requires means to determine what kind of operation the client
  132. wishes to undo/redo... we addressed this by logging handled sequence#s (via
  133. __checkpointUserOperation()... when an undo/redo request is received, the
  134. current sequence# to undo/redo dictates whether we're in case 1 or 2.
  135. challenge 2 requires means to determine whether or not an asworker changelog
  136. pertains to an undo/redo operation *and*, which csworker operations to undo/
  137. redo in response to an asworker undo/redo... we addressed this in 3 parts
  138. 1. when DOing something in response to asworker changelogs, the csworker
  139. sets a user-checkpoint (named after the asworker sequence#) in its
  140. journal
  141. 2. when forwarding undo/redo requests to asworkers, the asworker sequence#
  142. to undo/redo is bundled in a hitchhiker
  143. 3. when an asworker changelog has a bundled undo/redo hitchhiker, the
  144. csworker handles it by undoing/redoing all of the changes the bundled
  145. asworker sequence# had originally induced
  146. step 3 is paramount... if the csworker responded to undo/redos like it would
  147. any other request (e.g., respond to RMNODE by RMNODE), it would become out of
  148. sync with the asworker... see example below:
  149. 1. client creates A/0, AIcon/0
  150. 2. client moves AIcon/0
  151. 3. client undoes move (csworker only, OK)
  152. 4. client undoes create (would trigger RMNODE A/0, AIcon/0)
  153. 5. client redoes create (would trigger MKNODE A/0, AIcon/1)
  154. 6. client redoes move (will fail because AIcon/0 doesn't exist)
  155. in short, proper undo/redo requires that operations resultings from undo/redo
  156. be distinguishable from normal ones
  157. TBI:: undoing/redoing SYSOUT-only changelogs has no perceptible effect from
  158. client... one inconvenient side-effect of this is that rules require 2
  159. undos/redos to undo/redo: 1 to undo/redo the rule, 1 to undo/redo the
  160. SYSOUT message announcing the launching of the rule... a sensible and
  161. nice solution would be not to remember such changelogs in
  162. __handledSeqNums */
  163. const {
  164. __errorContinuable,
  165. __httpReq,
  166. __wHttpReq,
  167. __postInternalErrorMsg, __postMessage,
  168. __sequenceNumber,
  169. __successContinuable,
  170. __uri_to_id
  171. } = require("./__worker");
  172. const _do = require("./___do");
  173. const _utils = require('./utils');
  174. const _mmmk = require("./mmmk");
  175. const _fs = _do.convert(require('fs'), ['readFile', 'writeFile', 'readdir']);
  176. const _siocl = require('socket.io-client');
  177. module.exports = {
  178. '__REGEN_ICON_RETRY_DELAY_MS':200,
  179. '__asmm2csmm':{},
  180. '__asid2csid':{},
  181. '__aswid':undefined,
  182. '__handledSeqNums':{'i':undefined,'#s':[]},
  183. /*************************** ASWORKER INTERACTION **************************/
  184. /* apply asworker changes
  185. 0. check the changelog's sequence number to know if we should handle it
  186. now or later
  187. 1. iterate through the AS changelog setting up sync/async actions that
  188. appropriately modify the CS while accumulating CS changelogs (for
  189. pushing to subscribed clients)
  190. 2. launch sync/async action chain... on error, post error... on success,
  191. a) flatten the CS changelogs into a single changelog
  192. b) post message to server with flattened CS changelog, the server will
  193. then push it to subscribed clients
  194. c) apply next pending asworker changelog, if any and if applicable
  195. __nextASWSequenceNumber
  196. used to determine if a changelog is received out of order, and if a
  197. pending changelog is now ready to be handled
  198. __pendingChangelogs
  199. stores out or order changelogs until we're ready to handle them
  200. __hitchhikerJournal
  201. stores encountered hithchikers for future use (see NOTES above) */
  202. '__nextASWSequenceNumber':'/asworker#1',
  203. '__pendingChangelogs':[],
  204. '__hitchhikerJournal':{},
  205. '__applyASWChanges' :
  206. function(changelog,aswSequenceNumber,hitchhiker)
  207. {
  208. //console.error('w#'+__wid+' ++ ('+aswSequenceNumber+') '+
  209. // _utils.jsons(changelog));
  210. if( _utils.sn2int(aswSequenceNumber) >
  211. _utils.sn2int(this.__nextASWSequenceNumber) )
  212. {
  213. this.__pendingChangelogs.push(
  214. {'changelog':changelog,
  215. 'sequence#':aswSequenceNumber,
  216. 'hitchhiker':hitchhiker});
  217. var self = this;
  218. this.__pendingChangelogs.sort(
  219. function(a,b)
  220. {
  221. return self.__sn2int(a['sequence#']) -
  222. self.__sn2int(b['sequence#']);
  223. });
  224. return;
  225. }
  226. else if( _utils.sn2int(aswSequenceNumber) <
  227. _utils.sn2int(this.__nextASWSequenceNumber) )
  228. throw 'invalid changelog sequence#';
  229. var cschangelogs = [],
  230. cshitchhiker,
  231. actions = [__successContinuable()],
  232. self = this;
  233. /* special handling of undo/redo changelogs (see NOTES above) */
  234. if( hitchhiker && 'undo' in hitchhiker )
  235. cschangelogs.push(_mmmk.undo(hitchhiker['undo'])['changelog']);
  236. else if( hitchhiker && 'redo' in hitchhiker )
  237. cschangelogs.push(_mmmk.redo(hitchhiker['redo'])['changelog']);
  238. /* special handling of batchCheckpoint changelogs (see NOTES above) */
  239. else if( changelog.length == 1 && changelog[0]['op'] == 'MKBTCCHKPT' )
  240. this.__checkpointUserOperation(changelog[0]['name']);
  241. /* handle any other changelog */
  242. else
  243. {
  244. var manageHitchhiker =
  245. function(hhid,hh)
  246. {
  247. /* remember/restore a hitchhiker given specified id */
  248. if( hh )
  249. self.__hitchhikerJournal[hhid] = hh;
  250. else if( hitchhiker )
  251. self.__hitchhikerJournal[hhid] = hitchhiker;
  252. else
  253. hitchhiker = self.__hitchhikerJournal[hhid];
  254. };
  255. this.__checkpointUserOperation(aswSequenceNumber);
  256. changelog.forEach(
  257. function(step)
  258. {
  259. /* no legal connections exist between *Icon types, so we
  260. simply simulate the CS change such a [dis]connection would
  261. incur */
  262. if( step['op'] == 'MKEDGE' || step['op'] == 'RMEDGE' )
  263. actions.push(
  264. function()
  265. {
  266. var asid1 = step['id1'],
  267. asid2 = step['id2'],
  268. csid1 = self.__asid_to_csid(asid1),
  269. csid2 = self.__asid_to_csid(asid2);
  270. cschangelogs.push(
  271. [{'op':step['op'],'id1':csid1,'id2':csid2}]);
  272. return __successContinuable();
  273. });
  274. /* create appropriate CS instance and associate it with new AS
  275. instance (remember the association in __asid2csid to
  276. optimize future operations) */
  277. else if( step['op'] == 'MKNODE' )
  278. actions.push(
  279. function()
  280. {
  281. manageHitchhiker(step['id']);
  282. var asid = step['id'],
  283. node = _utils.jsonp(step['node']),
  284. isLink = ('segments' in hitchhiker),
  285. fullastype = node['$type'],
  286. fullcstype = self.__astype_to_cstype(
  287. fullastype,
  288. isLink),
  289. asuri = fullastype+'/'+asid+'.instance';
  290. attrs = {'$asuri':asuri};
  291. if( 'pos' in hitchhiker )
  292. attrs['position'] = hitchhiker['pos'];
  293. else if( 'neighborhood' in hitchhiker )
  294. {
  295. var nc = self.__nodesCenter(
  296. hitchhiker['neighborhood']);
  297. attrs['position'] =
  298. [(nc[0] || 200), (nc[1] || 200)];
  299. }
  300. else if( 'clone' in hitchhiker )
  301. attrs = _utils.mergeDicts(
  302. [attrs,hitchhiker['clone']]);
  303. else
  304. attrs['position'] = [200,200];
  305. var res = _mmmk.create(fullcstype,attrs),
  306. csid = res['id'];
  307. self.__asid2csid[asid] = csid;
  308. cschangelogs.push(res['changelog']);
  309. if( isLink )
  310. {
  311. var s = {},
  312. src =
  313. hitchhiker['src'] ||
  314. self.__asuri_to_csuri(hitchhiker['asSrc']),
  315. dest =
  316. hitchhiker['dest'] ||
  317. self.__asuri_to_csuri(hitchhiker['asDest']),
  318. segments =
  319. hitchhiker['segments'] ||
  320. self.__defaultSegments(src,dest);
  321. s[ src+'--'+__id_to_uri(csid) ] = segments[0];
  322. s[ __id_to_uri(csid)+'--'+dest ] = segments[1];
  323. cschangelogs.push(
  324. _mmmk.update(
  325. csid,
  326. {'$segments':s})['changelog'],
  327. self.__positionLinkDecorators(csid));
  328. }
  329. return self.__regenIcon(csid);
  330. },
  331. function(riChangelog)
  332. {
  333. cschangelogs.push(riChangelog);
  334. return __successContinuable();
  335. });
  336. /* remove appropriate CS instance... update __asid2csid for it
  337. to remain consistent */
  338. else if( step['op'] == 'RMNODE' )
  339. actions.push(
  340. function()
  341. {
  342. var asid = step['id'],
  343. csid = self.__asid_to_csid(asid);
  344. cschangelogs.push(_mmmk['delete'](csid)['changelog']);
  345. delete self.__asid2csid[asid];
  346. return __successContinuable();
  347. });
  348. /* regenerate the icon to re-evaluate any coded attributes
  349. NOTE:: CS changes may be bundled (i.e., if an AS update was
  350. simulated by a CS update)... if so, perform them
  351. before regenerating the icon */
  352. else if( step['op'] == 'CHATTR' )
  353. actions.push(
  354. function()
  355. {
  356. var asid = step['id'],
  357. csid = self.__asid_to_csid(asid);
  358. if( hitchhiker && 'cschanges' in hitchhiker )
  359. {
  360. var cschanges = hitchhiker['cschanges'];
  361. cschangelogs.push(
  362. _mmmk.update(csid,cschanges)['changelog'],
  363. ('$segments' in cschanges ?
  364. self.__positionLinkDecorators(csid) :
  365. []));
  366. }
  367. return self.__regenIcon(csid);
  368. },
  369. function(riChangelog)
  370. {
  371. cschangelogs.push(riChangelog);
  372. return __successContinuable();
  373. });
  374. /* load appropriate CS metamodel (stored in hitchhiker)...
  375. remember AS-to-CS metamodel mapping in __asmm2csmm to
  376. optimize future operations */
  377. else if( step['op'] == 'LOADMM' )
  378. actions.push(
  379. function()
  380. {
  381. manageHitchhiker(step['name']);
  382. var asmm = step['name'],
  383. csmm = hitchhiker['name'],
  384. data = hitchhiker['csmm'];
  385. cschangelogs.push(
  386. _mmmk.loadMetamodel(csmm,data)['changelog'],
  387. {'op':'LOADASMM',
  388. 'name':asmm,
  389. 'mm':step['mm']});
  390. self.__asmm2csmm[asmm] = csmm;
  391. return __successContinuable();
  392. });
  393. /* unload appropriate CS metamodel... update __asmm2csmm for
  394. it to remain consistent */
  395. else if( step['op'] == 'DUMPMM' )
  396. actions.push(
  397. function()
  398. {
  399. var asmm = step['name'],
  400. csmm = self.__asmm2csmm[asmm];
  401. cschangelogs.push(_mmmk.unloadMetamodel(csmm)['changelog']);
  402. delete self.__asmm2csmm[asmm];
  403. return __successContinuable();
  404. });
  405. /* load appropriate CS model (stored in hitchhiker) and
  406. overwrite past hitchhiker associated to initial load of
  407. current model, if any... when step['insert'] is specified,
  408. adjust $asuris to compensate for offsetting of inserted asm
  409. and $segments to compensate for upcoming offsetting of to-
  410. be-inserted csm */
  411. else if (step['op'] == 'RESETM')
  412. actions.push(
  413. function () {
  414. manageHitchhiker(
  415. step['old_name'],
  416. {'csm': _mmmk.read()});
  417. manageHitchhiker(step['new_name']);
  418. var csm = hitchhiker['csm'];
  419. var _csm = eval('(' + csm + ')');
  420. if (step['insert']) {
  421. var asoffset = parseInt(step['insert']),
  422. csoffset = _mmmk.next_id,
  423. incUri =
  424. function (oldUri, offset) {
  425. var matches = oldUri.match(/(.+\/)(.+)(\.instance)/);
  426. return matches[1] +
  427. (parseInt(matches[2]) + offset) +
  428. matches[3];
  429. };
  430. for (var id in _csm.nodes) {
  431. _csm.nodes[id]['$asuri']['value'] =
  432. incUri(_csm.nodes[id]['$asuri']['value'],
  433. asoffset);
  434. if (!('$segments' in _csm.nodes[id]))
  435. continue;
  436. var segments =
  437. _csm.nodes[id]['$segments']['value'],
  438. _segments = {};
  439. for (var edgeId in segments) {
  440. var uris = edgeId.match(
  441. /^(.*\.instance)--(.*\.instance)$/);
  442. _segments[incUri(uris[1], csoffset) + '--' +
  443. incUri(uris[2], csoffset)] =
  444. segments[edgeId];
  445. }
  446. _csm.nodes[id]['$segments']['value'] = _segments;
  447. }
  448. csm = _utils.jsons(_csm, null, '\t');
  449. }
  450. //see if any cs metamodels are missing
  451. //this fixes issue #28
  452. //this loading should be done elsewhere in the model loading chain
  453. for (var i in _csm.metamodels) {
  454. var mm = _csm.metamodels[i];
  455. if (!(_mmmk.model.metamodels.includes(mm))) {
  456. console.error("Last-minute loading for CS metamodel: " + mm);
  457. var csmm = _fs.readFile('./users/' + mm, 'utf8');
  458. _mmmk.loadMetamodel(mm, csmm);
  459. }
  460. }
  461. var res = _mmmk.loadModel(
  462. step['new_name'],
  463. csm,
  464. step['insert']);
  465. if (res["$err"] == undefined) {
  466. cschangelogs.push(res['changelog']);
  467. return __successContinuable();
  468. } else {
  469. return __errorContinuable();
  470. }
  471. });
  472. /* forward this SYSOUT command */
  473. else if( step['op'] == 'SYSOUT' )
  474. actions.push(
  475. function()
  476. {
  477. cschangelogs.push([step]);
  478. return __successContinuable();
  479. });
  480. });
  481. actions.push(
  482. function()
  483. {
  484. cschangelogs.push( self.__solveLayoutContraints(changelog) );
  485. return __successContinuable();
  486. });
  487. }
  488. _do.chain(actions)(
  489. function()
  490. {
  491. var cschangelog = _utils.flatten(cschangelogs);
  492. //console.error('w#'+__wid+' -- ('+aswSequenceNumber+') '+
  493. // _utils.jsons(cschangelog));
  494. __postMessage(
  495. {'statusCode':200,
  496. 'changelog':cschangelog,
  497. 'sequence#':aswSequenceNumber,
  498. 'hitchhiker':cshitchhiker});
  499. self.__nextASWSequenceNumber =
  500. _utils.incrementSequenceNumber(self.__nextASWSequenceNumber);
  501. self.__applyPendingASWChanges();
  502. },
  503. function(err)
  504. {
  505. throw 'unexpected error while applying changelogs :: '+err;
  506. }
  507. );
  508. },
  509. /* apply pending asworker changelogs, if any and if applicable */
  510. '__applyPendingASWChanges' :
  511. function()
  512. {
  513. if( this.__pendingChangelogs.length > 0 &&
  514. this.__nextASWSequenceNumber ==
  515. this.__pendingChangelogs[0]['sequence#'] )
  516. {
  517. var pc = this.__pendingChangelogs.shift();
  518. this.__applyASWChanges(
  519. pc['changelog'],
  520. pc['sequence#'],
  521. pc['hitchhiker']);
  522. }
  523. },
  524. /* initialize a socket that will listen for and handle changelogs returned by
  525. this csworker's associated asworker
  526. 1. onconnect() is triggered when 2 way communication is established, at
  527. which point we attempt to subscribe for specified asworker
  528. 2. onmessage() is triggered once in response to our subscription attempt:
  529. a) we set this.__aswid to specified aswid
  530. b) if a cswid was provided (i.e., a shared model session is being
  531. set up)
  532. i. retrieve the specified csworker's internal state
  533. ii. setup this csworker's state and _mmmk based on the
  534. results from step ii.
  535. iii. return the new state to the client (via callback())
  536. iv. remove any obsolete changelogs received since step i.
  537. and set __nextASWSequenceNumber to the same value as
  538. that of the csworker whose state we're cloning
  539. v. apply pending changelogs, if any
  540. all future triggers of onmessage() are due to the asworker pushing
  541. changelogs, these are handled by __applyASWChanges
  542. NOTE : actually, there is a 3rd case where onmessage() is triggered...
  543. between the moment where the socket is created and the moment
  544. where we receive the response to our subscription attempt, we
  545. will receive *all* messages broadcasted by the websocket server
  546. in httpwsd.js... these are detected and discarded */
  547. '__aswSubscribe' :
  548. function(aswid,cswid)
  549. {
  550. var self = this;
  551. return function(callback,errback)
  552. {
  553. var socket = _siocl.connect('127.0.0.1',{port:8124});
  554. socket.on('connect',
  555. function()
  556. {
  557. socket.emit('message',
  558. {'method':'POST','url':'/changeListener?wid='+aswid});
  559. });
  560. socket.on('disconnect',
  561. function() {self.__aswid = undefined;});
  562. socket.on('message',
  563. function(msg)
  564. {
  565. /* on POST /changeListener response */
  566. if( msg.statusCode != undefined )
  567. {
  568. if( ! _utils.isHttpSuccessCode(msg.statusCode) )
  569. return errback(msg.statusCode+':'+msg.reason);
  570. self.__aswid = aswid;
  571. if( cswid != undefined )
  572. {
  573. var actions =
  574. [__wHttpReq('GET','/internal.state?wid='+cswid)];
  575. _do.chain(actions)(
  576. function(respData)
  577. {
  578. var state = respData['data'];
  579. _mmmk.clone(state['_mmmk']);
  580. self.__clone(state['_wlib']);
  581. __ids2uris = state['__ids2uris'];
  582. __nextSequenceNumber =
  583. state['__nextSequenceNumber'];
  584. self.__pendingChangelogs =
  585. self.__pendingChangelogs.filter(
  586. function(pc)
  587. {
  588. return self.__sn2int(pc['sequence#']) >
  589. self.__sn2int(
  590. self.__nextASWSequenceNumber);
  591. });
  592. callback();
  593. self.__applyPendingASWChanges();
  594. },
  595. function(err) {errback(err);}
  596. );
  597. }
  598. else
  599. callback();
  600. }
  601. /* on changelog reception (ignore changelogs while not
  602. subscribed to an asworker... see NOTE) */
  603. else if( self.__aswid != undefined )
  604. self.__applyASWChanges(
  605. msg.data.changelog,
  606. msg.data['sequence#'],
  607. msg.data.hitchhiker);
  608. });
  609. };
  610. },
  611. /***************************** ICON GENERATION *****************************/
  612. /* determine the correct positions and orientations of the given link's
  613. decorators, adjust them and return changelogs
  614. 0. concatenate segments into a single path
  615. 1. for each link decorator (i.e., Link $contents)
  616. *. do nothing if link decoration information is missing... this ensures
  617. backward compatibility with pre-link decorator models
  618. a. extract link decoration information, i.e., xratio and yoffset
  619. b. determine point on path at xratio and its orientation
  620. c. adjust yoffset given orientation (yoffset was specified for 0deg)
  621. d. adjust endAt given orientation (endAt is specified for 0deg)... note
  622. that endAt is only relevant for arrowtails
  623. e. relativize point from step b. w.r.t. to Link center and adjust
  624. position by adjusted yoffset
  625. f. set new position and orientation in mmmk and remember changelogs
  626. 2. return flattened changelogs
  627. NOTE:: the initial values of vobject geometric attribute values must
  628. always be remembered... they are needed on the client to properly
  629. support the drawing and transformation of vobjects... this is
  630. captured by buildVobjGeomAttrVal(), which we use in step 1f */
  631. '__positionLinkDecorators' :
  632. function(id)
  633. {
  634. var link = _utils.jsonp(_mmmk.read(id)),
  635. vobjs = link['$contents']['value'].nodes,
  636. segments = _utils.values(link['$segments']['value']),
  637. path = segments[0]+
  638. segments[1].substring(segments[1].indexOf('L')),
  639. changelogs = [];
  640. for( var vid in vobjs )
  641. {
  642. if( !('$linkDecoratorInfo' in vobjs[vid]) )
  643. continue;
  644. var ldi = vobjs[vid]['$linkDecoratorInfo']['value'],
  645. pp = _svg.fns.getPointOnPathAtRatio(path,ldi.xratio);
  646. if (pp == undefined)
  647. continue;
  648. var yoffset = new _svg.types.Point(0,ldi.yoffset).rotate(pp.O),
  649. endAt = (ldi.xratio >= 1 ?
  650. new _svg.types.Point(100,0).rotate(pp.O) :
  651. new _svg.types.Point(0,0)),
  652. changes = {};
  653. pp.x += yoffset.x - link['position']['value'][0];
  654. pp.y += yoffset.y - link['position']['value'][1];
  655. changes['$contents/value/nodes/'+vid+'/position'] =
  656. [_utils.buildVobjGeomAttrVal(
  657. vobjs[vid]['position']['value'][0], pp.x+','+endAt.x+'%'),
  658. _utils.buildVobjGeomAttrVal(
  659. vobjs[vid]['position']['value'][1], pp.y+','+endAt.y+'%')];
  660. changes['$contents/value/nodes/'+vid+'/orientation'] =
  661. _utils.buildVobjGeomAttrVal(
  662. vobjs[vid]['orientation']['value'], pp.O);
  663. changelogs.push( _mmmk.update(id,changes)['changelog'] );
  664. }
  665. return _utils.flatten(changelogs);
  666. },
  667. /* regenerate specified icon... if newCsmm is specified, the regeneration
  668. process essentially transforms the icon for it to conform to whatever is
  669. specified by newCsmm... otherwise, it merely involves re-evaluating
  670. VisualObject mappers
  671. 1. if newCSmm is defined
  672. a) create a new instance I of node 'id''s icontype given newCsmm
  673. b) copy node 'id''s '$asuri', 'position', etc. attributes to I
  674. c) delete node 'id'
  675. d) update__asid2csid and 'id' variable to be I's id
  676. e) save the changelogs of steps a-c)
  677. 2. in either case, [re-]eval VisualObject mappers
  678. a) retrieve Icon and VisualObject mappers...
  679. i. fetch specified node from mmmk
  680. ii. retrieve its '$contents' attribute
  681. iii. retrieve the 'mapper' attribute for the node itself
  682. iii. retrieve the 'mapper' attribute of VisualObjects within
  683. '$contents'
  684. b) return empty changelog if all mappers are empty
  685. c) setup sync/async action chaining
  686. i. ask asworker to evaluate a bunch of mappers
  687. ii. save results for later access
  688. d) launch chain...
  689. on success, populate attributes with results from step 2ci and
  690. 'return' changelog OR 'return' SYSOUT error if evaluating mappers
  691. raised exceptions
  692. on failure (this only occurs if we were unable to obtain an
  693. asworker read-lock), relaunch chain after short delay
  694. TBI: step 2d) could potentially lead to an infinite loop if failure is due
  695. to unforeseen error or to very long delays if lock holder takes a
  696. long time to finish... we could address this by *not* relaunching the
  697. chain if some number of tries have failed, and instead setting coded
  698. attribute values to '<out-of-date>' */
  699. '__regenIcon' :
  700. function(id,newCsmm)
  701. {
  702. var changelogs = [],
  703. self = this;
  704. return function(callback,errback)
  705. {
  706. if( newCsmm != undefined )
  707. {
  708. var node = _utils.jsonp(_mmmk.read(id)),
  709. asuri = _mmmk.read(id,'$asuri'),
  710. asid = __uri_to_id(asuri),
  711. attrs = _utils.mergeDicts([
  712. {'$asuri':asuri,
  713. 'position':node['position']['value'],
  714. 'orientation':node['orientation']['value'],
  715. 'scale':node['scale']['value']},
  716. ((s=_mmmk.read(id,'$segments'))['$err'] ?
  717. {} : {'$segments':s}) ]),
  718. cres = _mmmk.create(
  719. newCsmm+'/'+node['$type'].match(/.*\/(.*)/)[1],
  720. attrs),
  721. csid = cres['id'],
  722. dres = _mmmk['delete'](id);
  723. self.__asid2csid[asid] = id = csid;
  724. changelogs.push(
  725. cres['changelog'],
  726. dres['changelog']);
  727. }
  728. var csuri = __id_to_uri(id),
  729. asuri = self.__csuri_to_asuri(csuri),
  730. icon = _utils.jsonp(_mmmk.read(id)),
  731. vobjects = icon['$contents']['value'],
  732. mappers = {};
  733. if( icon['mapper']['value'] != '' )
  734. mappers[''] = icon['mapper']['value'];
  735. for( var vid in vobjects['nodes'] )
  736. if( 'mapper' in vobjects['nodes'][vid] &&
  737. vobjects['nodes'][vid]['mapper']['value'] != '' )
  738. mappers['$contents/value/nodes/'+vid+'/'] =
  739. vobjects['nodes'][vid]['mapper']['value'];
  740. if( _utils.keys(mappers).length > 0 )
  741. {
  742. var actions =
  743. [__wHttpReq(
  744. 'POST',
  745. '/GET/'+asuri+'.mappings?wid='+self.__aswid,
  746. mappers)],
  747. successf =
  748. function(attrVals)
  749. {
  750. if( '$err' in attrVals )
  751. callback(
  752. [{'op':'SYSOUT',
  753. 'text':'ERROR :: '+attrVals['$err']}]);
  754. else
  755. {
  756. var changes = {};
  757. for( var fullattr in attrVals )
  758. changes[fullattr] = attrVals[fullattr];
  759. var result = _mmmk.update(id,changes);
  760. if ( '$err' in result )
  761. callback(
  762. [{'op':'SYSOUT',
  763. 'text':'ERROR :: '+result['$err']}]);
  764. else {
  765. changelogs.push(
  766. result['changelog'] );
  767. callback( _utils.flatten(changelogs) );
  768. }
  769. }
  770. },
  771. failuref =
  772. function(err)
  773. {
  774. console.error('"POST *.mappings" failed on :: '+err+
  775. '\n(will try again soon)');
  776. setTimeout(
  777. _do.chain(actions),
  778. self.__REGEN_ICON_RETRY_DELAY_MS,
  779. successf,
  780. failuref);
  781. };
  782. _do.chain(actions)(successf,failuref);
  783. }
  784. else
  785. callback( _utils.flatten(changelogs) );
  786. };
  787. },
  788. '__solveLayoutContraints':
  789. function(changelog)
  790. {
  791. // TBC actually implement this function
  792. // use ids in changelog to determine what changed
  793. // add 2 lines below to mmmk.__create() if necessary
  794. // if( type in this.metamodels[metamodel]['connectorTypes'] )
  795. // new_node['$linktype'] = this.metamodels[metamodel]['connectorTypes'][type];
  796. return [];
  797. // return [{'op':'SYSOUT',
  798. // 'text':'WARNING :: '+
  799. // 'a proper layout constraint solver has yet to be '+
  800. // 'implemented... inter-VisualObject relationships are '+
  801. // 'ignored and containers do not resize to fit their '+
  802. // 'contents'}];
  803. },
  804. /* transform all icons from tgtCsmm into appropriate icons of newCsmm
  805. 1. read model and newCsmm from _mmmk
  806. 2. for each icon of tgtCsmm, if newCsmm defines a replacement icon, save
  807. the icon's id in 'tgtIds'... otherwise, return error
  808. 3. init sync/async action chaining...
  809. a) for each id in 'tgtIds', add 2 entries to chain
  810. i. call __regenIcon on specified icon
  811. ii. save resulting changelog and continue
  812. 4. launch chain...
  813. on success,
  814. a) adjust $segments attributes from all Links to account for edge
  815. end change of id (and uri)
  816. b) 'return' flattened changelogs
  817. on failure, 'return' error */
  818. '__transformIcons' :
  819. function(tgtCsmm,newCsmm)
  820. {
  821. var self = this;
  822. return function(callback,errback)
  823. {
  824. var m = _utils.jsonp(_mmmk.read()),
  825. newCsmmData = _utils.jsonp(_mmmk.readMetamodels(newCsmm)),
  826. tgtIds = [],
  827. newIds = {},
  828. changelogs = [],
  829. actions = [__successContinuable()];
  830. for( var id in m.nodes )
  831. if( (matches = m.nodes[id]['$type'].match('^'+tgtCsmm+'/(.*)')) )
  832. {
  833. var type = matches[1];
  834. if( newCsmmData.types[type] == undefined )
  835. {
  836. errback('Icons mm should define type :: '+type);
  837. return;
  838. }
  839. tgtIds.push(id);
  840. }
  841. tgtIds.forEach(
  842. function(id)
  843. {
  844. actions.push(
  845. function() {return self.__regenIcon(id,newCsmm);},
  846. function(changelog)
  847. {
  848. var newId = changelog[0]['id'];
  849. newIds[id] = newId;
  850. changelogs.push(
  851. changelog.concat(
  852. '$err' in _mmmk.read(newId,'$segments') ?
  853. [] : self.__positionLinkDecorators(newId)) );
  854. return __successContinuable();
  855. });
  856. });
  857. _do.chain(actions)(
  858. function()
  859. {
  860. var m = _utils.jsonp(_mmmk.read());
  861. for( var id in m.nodes )
  862. if( (matches = m.nodes[id]['$type'].match(/Link$/)) )
  863. {
  864. var s = _mmmk.read(id,'$segments'),
  865. changed = false;
  866. for( var edgeId in s )
  867. {
  868. var ends =
  869. edgeId.match(/(.*\.instance)--(.*\.instance)/),
  870. id1 = __uri_to_id(ends[1]),
  871. id2 = __uri_to_id(ends[2]);
  872. if( id1 in newIds )
  873. {
  874. ends[1] = __id_to_uri( newIds[id1] );
  875. changed = true;
  876. }
  877. if( id2 in newIds )
  878. {
  879. ends[2] = __id_to_uri( newIds[id2] );
  880. changed = true;
  881. }
  882. if( changed )
  883. {
  884. s[ends[1]+'--'+ends[2]] = s[edgeId];
  885. delete s[edgeId];
  886. }
  887. }
  888. if( changed )
  889. changelogs.push(
  890. _mmmk.update(id,{'$segments':s})['changelog'] );
  891. }
  892. callback(_utils.flatten(changelogs));
  893. },
  894. function(err)
  895. {
  896. errback('__transformIcons() should never fail... '+
  897. 'failed on :: '+err);
  898. }
  899. );
  900. };
  901. },
  902. /************************** REST REQUEST HANDLING **************************/
  903. /* INTENT :
  904. ask our asworker's mtworker to do something (e.g., change
  905. transformation execution mode)
  906. IN PRACTICE:
  907. adjust uri and forward to asworker
  908. 1. setup sync/async action chaining
  909. a) ask asworker to forward request to its mtworker
  910. 2. launch chain... return success code or error */
  911. 'mtwRequest' :
  912. function(resp,method,uri,reqData)
  913. {
  914. var actions = [__wHttpReq(
  915. method,
  916. uri+'?wid='+this.__aswid,
  917. reqData)];
  918. _do.chain(actions)(
  919. function()
  920. {
  921. __postMessage({'statusCode':200, 'respIndex':resp});
  922. },
  923. function(err) {__postInternalErrorMsg(resp,err);}
  924. );
  925. },
  926. /* return sufficient information to clone the current csworker to the tinyest
  927. detail... this is a pimped out version of GET current.state for internal
  928. use only
  929. 1. bundle info about _mmmk and _wlib
  930. 2. return to querier */
  931. 'GET /internal.state' :
  932. function(resp)
  933. {
  934. __postMessage(
  935. {'statusCode':200,
  936. 'data':{'_mmmk':_mmmk.clone(),
  937. '_wlib':this.__clone(),
  938. '__ids2uris':_utils.clone(__ids2uris),
  939. '__nextSequenceNumber':__nextSequenceNumber},
  940. 'sequence#':__sequenceNumber(0),
  941. 'respIndex':resp});
  942. },
  943. /* subscribe to an existing or to-be-created asworker
  944. 1. validate parameters
  945. 2. if 'aswid' and 'cswid' are given,
  946. a) setup sync/async action chaining
  947. i) attempt to subsribe to specified asworker using specified
  948. csworker's current model as this csworker's initial model
  949. b) launch chain... on success, 'return' current state (via
  950. GET__current_state())... on error, return error
  951. 2. otherwise,
  952. a) setup sync/async action chaining
  953. i) spawn new asworker
  954. ii) subscribe to it
  955. b) launch chain... return success code or error */
  956. 'PUT /aswSubscription' :
  957. function(resp,uri,reqData/*wid*/)
  958. {
  959. if( this.__aswid > -1 )
  960. return __postForbiddenErrorMsg(
  961. resp,
  962. 'already subscribed to an asworker');
  963. if( reqData != undefined )
  964. {
  965. if( reqData['aswid'] == undefined ||
  966. reqData['cswid'] == undefined )
  967. return __postInternalErrorMsg(resp, 'missing AS and/or CS wid');
  968. var self = this,
  969. actions =
  970. [this.__aswSubscribe(reqData['aswid'],reqData['cswid'])];
  971. _do.chain(actions)(
  972. function()
  973. {
  974. GET__current_state(resp);
  975. },
  976. function(err) {__postInternalErrorMsg(resp,err);}
  977. );
  978. }
  979. else
  980. {
  981. var self = this,
  982. actions =
  983. [__httpReq('POST','/asworker'),
  984. function(aswid) {return self.__aswSubscribe(aswid);}];
  985. _do.chain(actions)(
  986. function()
  987. {
  988. __postMessage(
  989. {'statusCode':200,
  990. 'data':self.__aswid,
  991. 'respIndex':resp});
  992. },
  993. function(err) {__postInternalErrorMsg(resp,err);}
  994. );
  995. }
  996. },
  997. /* INTENT :
  998. load a CS and an AS metamodel from disk
  999. *OR*
  1000. switch between different CS metamodels
  1001. IN PRACTICE:
  1002. adjust uri and reqData and forward to asworker
  1003. *OR*
  1004. fulfill intent
  1005. 1. parse + validate parameters
  1006. 2. if no asmm is specified (CS switch),
  1007. a) setup sync/async action chaining
  1008. i. read specified csmm from disk
  1009. ii. load read data into _mmmk
  1010. iii. try to regen all icons from overwritten csmm
  1011. b) launch chain...
  1012. i. on failure, undo step 2.a)ii. if it ran, and return error
  1013. ii. on success,
  1014. j. return success code
  1015. jj. unload previous csmm
  1016. jjj. post bundled and flattened changelogs
  1017. 2. if an asmm is specified (MM load)
  1018. a) setup sync/async action chaining
  1019. i. read specified csmm from disk
  1020. ii. ask asworker to load AS metamodel + pass CS metamodel name and
  1021. data as 'hitchhiker'
  1022. b) launch chain... return success code or error */
  1023. 'PUT /current.metamodels' :
  1024. function(resp,uri,reqData/*[asmm,]csmm*/)
  1025. {
  1026. if( reqData == undefined )
  1027. return __postBadReqErrorMsg(resp, 'missing request data');
  1028. else if( reqData['csmm'] == undefined )
  1029. return __postBadReqErrorMsg(resp, 'missing CS mm');
  1030. else if( ! (matches = reqData['csmm'].
  1031. match(/.+?((\/.*)\..*Icons(\.pattern){0,1})\.metamodel/)) )
  1032. return __postBadReqErrorMsg(
  1033. resp,
  1034. 'bad uri for Icons mm :: '+reqData['csmm']);
  1035. var asmm = matches[2]+(matches[3] || ''),
  1036. csmm = matches[1];
  1037. if( reqData['asmm'] == undefined )
  1038. {
  1039. if( this.__asmm2csmm[asmm] == undefined )
  1040. return __postBadReqErrorMsg(resp, 'missing AS mm');
  1041. var lres = undefined,
  1042. sn = undefined,
  1043. self = this,
  1044. actions =
  1045. [_fs.readFile('./users'+reqData['csmm'],'utf8'),
  1046. function(csmmData)
  1047. {
  1048. sn = __sequenceNumber();
  1049. self.__checkpointUserOperation(sn);
  1050. lres = _mmmk.loadMetamodel(csmm,csmmData);
  1051. return __successContinuable();
  1052. },
  1053. function()
  1054. {
  1055. return self.__transformIcons(
  1056. self.__asmm2csmm[asmm],
  1057. csmm);
  1058. }];
  1059. _do.chain(actions)(
  1060. function(changelog)
  1061. {
  1062. __postMessage({'statusCode':202, 'respIndex':resp});
  1063. var ures = _mmmk.unloadMetamodel(self.__asmm2csmm[asmm]),
  1064. changelogs =
  1065. [lres['changelog'],changelog,ures['changelog']];
  1066. self.__asmm2csmm[asmm] = csmm;
  1067. __postMessage(
  1068. {'statusCode':200,
  1069. 'changelog':_utils.flatten(changelogs),
  1070. 'sequence#':sn});
  1071. },
  1072. function(err)
  1073. {
  1074. if( sn != undefined )
  1075. __postInternalErrorMsg(resp,
  1076. 'CS switch should never fail for non-I/O reason'+
  1077. '... backend may now be in unstable state... '+
  1078. 'failed on :: '+err);
  1079. else
  1080. __postInternalErrorMsg(resp,err);
  1081. }
  1082. );
  1083. }
  1084. else
  1085. {
  1086. var self = this,
  1087. actions =
  1088. [_fs.readFile('./users'+reqData['csmm'],'utf8'),
  1089. function(csmmData)
  1090. {
  1091. return __wHttpReq(
  1092. 'PUT',
  1093. uri+'?wid='+self.__aswid,
  1094. {'mm':reqData['asmm'],
  1095. 'hitchhiker':{'csmm':csmmData,'name':csmm}});
  1096. }];
  1097. _do.chain(actions)(
  1098. function()
  1099. {
  1100. __postMessage({'statusCode':202, 'respIndex':resp});
  1101. },
  1102. function(err) {__postInternalErrorMsg(resp,err);}
  1103. );
  1104. }
  1105. },
  1106. /* INTENT :
  1107. unload a metamodel (deletes all entities from that metamodel)
  1108. IN PRACTICE:
  1109. adjust uri and forward to asworker
  1110. 1. parse + validate parameters
  1111. 2. setup sync/async action chaining
  1112. a) ask asworker to unload corresponding AS mm
  1113. 3. launch chain... on success, unload specified metamodel */
  1114. 'DELETE *.metamodel' :
  1115. function(resp,uri)
  1116. {
  1117. var matches = uri.match(/(.*)\..*Icons(\.pattern){0,1}\.metamodel/);
  1118. if( ! matches )
  1119. return __postBadReqErrorMsg(resp,'bad uri for Icons mm :: '+uri);
  1120. var asuri = matches[1]+(matches[2] || '')+'.metamodel',
  1121. actions =
  1122. [__wHttpReq('DELETE',asuri+'?wid='+this.__aswid)];
  1123. _do.chain(actions)(
  1124. function()
  1125. {
  1126. __postMessage({'statusCode':202, 'respIndex':resp});
  1127. },
  1128. function(err) {__postInternalErrorMsg(resp,err);}
  1129. );
  1130. },
  1131. /* INTENT :
  1132. load a model from disk
  1133. OR
  1134. clear current model (and metamodels)
  1135. IN PRACTICE:
  1136. adjust reqData and forward to asworker
  1137. 1. parse + validate parameters
  1138. 2. read specified model from disk
  1139. OR
  1140. fabricate empty model
  1141. 3. setup sync/async action chaining
  1142. a) ask asworker to load associated AS model + pass CS model as
  1143. 'hitchhiker'
  1144. 4. launch chain... return success code or error */
  1145. 'PUT /current.model' :
  1146. function(resp,uri,reqData/*m[,insert]*/)
  1147. {
  1148. if( reqData == undefined )
  1149. return __postBadReqErrorMsg(resp, 'missing model');
  1150. var self = this,
  1151. mData = undefined,
  1152. actions = [];
  1153. if( reqData['m'] == undefined )
  1154. actions =
  1155. [__successContinuable(),
  1156. function()
  1157. {
  1158. mData = {"csm": {"nodes": {},
  1159. "edges": [],
  1160. "metamodels": []},
  1161. "asm": {"nodes": {},
  1162. "edges": [],
  1163. "metamodels": []}};
  1164. reqData['m'] = 'new';
  1165. return __successContinuable(mData);
  1166. }];
  1167. else {
  1168. try {
  1169. _fs.accessSync('./users/'+reqData['m']);
  1170. } catch (e) {
  1171. return __postBadReqErrorMsg(resp, 'cannot read ' + reqData['m']);
  1172. }
  1173. actions = [ _fs.readFile('./users/'+reqData['m'],'utf8'),
  1174. function(_mData)
  1175. {
  1176. mData = eval('('+_mData+')');
  1177. return __successContinuable(mData);
  1178. }];
  1179. actions.push(
  1180. function(m)
  1181. {
  1182. var asmData = _utils.jsons(m['asm']),
  1183. csmData = _utils.jsons(m['csm']);
  1184. return __wHttpReq(
  1185. 'PUT',
  1186. uri+'?wid='+self.__aswid,
  1187. {'m':asmData,
  1188. 'name':reqData['m']+(new Date().getTime()),
  1189. 'insert':reqData['insert'],
  1190. 'hitchhiker':{'csm':csmData}});
  1191. });
  1192. _do.chain(actions)(
  1193. function()
  1194. {
  1195. __postMessage({'statusCode':202,'respIndex':resp});
  1196. },
  1197. function(err)
  1198. {
  1199. var MISSING_MM_ERROR = 'metamodel not loaded :: ';
  1200. if( (matches = err.match('^500:'+MISSING_MM_ERROR+
  1201. '(.*?)(\\.pattern){0,1}$')) )
  1202. {
  1203. var asmm = matches[1],
  1204. pmm = (matches[2] != undefined),
  1205. csmm;
  1206. mData['csm'].metamodels.some(
  1207. function(mm)
  1208. {
  1209. if( (pmm && mm.match(
  1210. '^'+asmm+'\\.[a-zA-Z0-9]*Icons\\.pattern$')) ||
  1211. (!pmm && mm.match(
  1212. '^'+asmm+'\\.[a-zA-Z0-9]*Icons$')) )
  1213. csmm = mm;
  1214. return csmm;
  1215. });
  1216. __postInternalErrorMsg(resp,MISSING_MM_ERROR+csmm);
  1217. }
  1218. else
  1219. __postInternalErrorMsg(resp,err);
  1220. }
  1221. );
  1222. }
  1223. },
  1224. /* INTENT :
  1225. create a new instance of specified type (if reqData has 'segments',
  1226. 'src' and 'dest' fields, type is a connector)
  1227. IN PRACTICE:
  1228. adjust uri (and reqData) and forward to asworker
  1229. 1. parse + validate parameters
  1230. 2. setup sync/async action chaining
  1231. a) construct reqData for asworker.POST *.type
  1232. i. handle connector ends if applicable
  1233. ii. handle 'pos'... pass as hitchhiker and evaluate the to-be
  1234. *Icon's parser within a dummy context where 'position' is set
  1235. to 'pos'... see NOTES above for more details on this
  1236. b) ask asworker to create an instance of appropriate AS type
  1237. 3. launch chain... return success code or error */
  1238. 'POST *.type' :
  1239. function(resp,uri,reqData/*pos|clone,[segments,src,dest]*/)
  1240. {
  1241. var matches =
  1242. uri.match(/((.*)\..*Icons)(\.pattern){0,1}\/((.*)Icon)\.type/) ||
  1243. uri.match(/((.*)\..*Icons)(\.pattern){0,1}\/((.*)Link)\.type/);
  1244. if( ! matches )
  1245. return __postBadReqErrorMsg(
  1246. resp,
  1247. 'bad uri for Icon/Link type :: '+uri);
  1248. var asuri = matches[2]+(matches[3] || '')+'/'+matches[5]+'.type',
  1249. csmm = matches[1]+(matches[3] || ''),
  1250. cstype = matches[4],
  1251. types = _utils.jsonp(_mmmk.readMetamodels(csmm))['types'];
  1252. if (cstype in types) {
  1253. var parser =
  1254. types[cstype].
  1255. filter(
  1256. function(attr)
  1257. {
  1258. return attr['name']=='parser';
  1259. })[0]['default'],
  1260. self = this,
  1261. actions =
  1262. [__successContinuable(),
  1263. function()
  1264. {
  1265. if( reqData == undefined ||
  1266. (pos = reqData['pos']) == undefined )
  1267. return __errorContinuable('missing creation parameters');
  1268. var hitchhiker = {},
  1269. reqParams = {};
  1270. if( (segments = reqData['segments']) != undefined &&
  1271. (src = reqData['src']) != undefined &&
  1272. (dest = reqData['dest']) != undefined )
  1273. {
  1274. if( (src_asuri = self.__csuri_to_asuri(src))['$err'] )
  1275. return __errorContinuable(src_asuri['$err']);
  1276. if( (dest_asuri = self.__csuri_to_asuri(dest))['$err'] )
  1277. return __errorContinuable(dest_asuri['$err']);
  1278. hitchhiker = {'segments':segments,
  1279. 'src':src,
  1280. 'dest':dest};
  1281. reqParams = {'src':src_asuri,
  1282. 'dest':dest_asuri};
  1283. }
  1284. hitchhiker['pos'] = pos;
  1285. reqParams['attrs'] =
  1286. self.__runParser(
  1287. parser,
  1288. {'position':pos,
  1289. 'orientation':0,
  1290. 'scale':[1,1]},
  1291. {});
  1292. return __successContinuable(
  1293. _utils.mergeDicts(
  1294. [{'hitchhiker':hitchhiker}, reqParams]) );
  1295. },
  1296. function(asreqData)
  1297. {
  1298. return __wHttpReq(
  1299. 'POST',
  1300. asuri+'?wid='+self.__aswid,
  1301. asreqData);
  1302. }];
  1303. _do.chain(actions)(
  1304. function(res)
  1305. {
  1306. __postMessage({'statusCode':202, 'respIndex':resp});
  1307. },
  1308. function(err) {__postInternalErrorMsg(resp,err);}
  1309. );
  1310. } else {
  1311. return __postBadReqErrorMsg(
  1312. resp,
  1313. 'no concrete syntax definition found for '+cstype);
  1314. }
  1315. },
  1316. /* return an AS instance, and optionally also the associated CS instance
  1317. 1. setup sync/async action chaining
  1318. a) get AS instance uri for specified CS instance
  1319. b) ask asworker for AS instance
  1320. 2. launch chain
  1321. ... on success, 'return' instance possibly bundling CS instance
  1322. ... on error, 'return' error */
  1323. 'GET *.instance' :
  1324. function(resp,uri,reqData/*[full]*/)
  1325. {
  1326. var self = this,
  1327. actions =
  1328. [__successContinuable(),
  1329. function()
  1330. {
  1331. if( (asuri = self.__csuri_to_asuri(uri))['$err'] )
  1332. return __errorContinuable(asuri['$err']);
  1333. return __successContinuable(asuri);
  1334. },
  1335. function(asuri)
  1336. {
  1337. return __wHttpReq('GET',asuri+'?wid='+self.__aswid);
  1338. }];
  1339. _do.chain(actions)(
  1340. function(respData)
  1341. {
  1342. if( reqData && 'full' in reqData )
  1343. var data = {'cs':_mmmk.read(__uri_to_id(uri)),
  1344. 'as':respData['data']};
  1345. else
  1346. var data = respData['data'];
  1347. __postMessage(
  1348. {'statusCode':200,
  1349. 'data':data,
  1350. 'sequence#':respData['sequence#'],
  1351. 'respIndex':resp});
  1352. },
  1353. function(err) {__postInternalErrorMsg(resp,err);}
  1354. );
  1355. },
  1356. /* INTENT :
  1357. update an AS instance's attributes
  1358. IN PRACTICE:
  1359. adjust uri and forward to asworker
  1360. 1. setup sync/async action chaining
  1361. a) determine associated AS instance uri
  1362. b) ask asworker to update it
  1363. 2. launch chain... return success code or error */
  1364. 'PUT *.instance' :
  1365. function(resp,uri,reqData)
  1366. {
  1367. var self = this,
  1368. actions =
  1369. [__successContinuable(),
  1370. function()
  1371. {
  1372. if( (asuri = self.__csuri_to_asuri(uri))['$err'] )
  1373. return __errorContinuable(asuri['$err']);
  1374. return __successContinuable(asuri);
  1375. },
  1376. function(asuri)
  1377. {
  1378. return __wHttpReq(
  1379. 'PUT',
  1380. asuri+'?wid='+self.__aswid,
  1381. reqData);
  1382. }];
  1383. _do.chain(actions)(
  1384. function(asnode)
  1385. {
  1386. __postMessage(
  1387. {'statusCode':202,
  1388. 'respIndex':resp});
  1389. },
  1390. function(err) {__postInternalErrorMsg(resp,err);}
  1391. );
  1392. },
  1393. 'POST *.instance.click' :
  1394. function(resp,uri,reqData)
  1395. {
  1396. /* TBA
  1397. REST requests vs. code run on ASw
  1398. + checkout bak/ for _mmmk.handleVisualObjectClick */
  1399. },
  1400. /* INTENT :
  1401. delete an instance
  1402. IN PRACTICE:
  1403. adjust uri and forward to asworker
  1404. 1. setup sync/async action chaining
  1405. a) determine associated AS instance uri
  1406. b) ask asworker to delete it
  1407. 2. launch chain... return success code
  1408. NOTE:: this function does not return csworker errors to the client (i.e.,
  1409. errors triggered by __csuri_to_asuri() failures)... the reason for
  1410. this is that mmmk sometimes cascades deletes (e.g., deleting a
  1411. node alsos deletes any connected links) which often causes errors
  1412. during 'mass' deletions, e.g.,
  1413. a) client requests
  1414. delete A
  1415. delete A->B
  1416. delete B
  1417. b) csworker handles delete A (deletes A and A->B)
  1418. c) csworker handles delete A->B (error, A->B already deleted)
  1419. ... */
  1420. 'DELETE *.instance' :
  1421. function(resp,uri)
  1422. {
  1423. var self = this,
  1424. asuri = this.__csuri_to_asuri(uri),
  1425. actions =
  1426. [__wHttpReq('DELETE',asuri+'?wid='+self.__aswid)];
  1427. if( asuri['$err'] )
  1428. __postMessage({'statusCode':200, 'respIndex':resp});
  1429. else
  1430. _do.chain(actions)(
  1431. function()
  1432. {
  1433. __postMessage({'statusCode':202, 'respIndex':resp});
  1434. },
  1435. function(err)
  1436. {
  1437. __postInternalErrorMsg(resp,err);
  1438. }
  1439. );
  1440. },
  1441. /* INTENT :
  1442. update a CS instance's attributes (position,...)
  1443. IN PRACTICE :
  1444. perform intent *or* possibly adjust uri and reqData and forward to
  1445. asworker
  1446. 1. retrieve the icon's parser
  1447. 2. execute parser to determine AS impacts
  1448. 3. if parsing produced an error, return it
  1449. 3. if there are AS impacts, simulate an edit-via-dialog update by
  1450. 'forwarding' the request (with modified reqData) to 'PUT *.instance'
  1451. *and* bundle requested CS update (for later handling)
  1452. 3. if there are no AS impacts, perform requested CS update and post
  1453. changelog */
  1454. 'PUT *.cs' :
  1455. function(resp,uri,reqData)
  1456. {
  1457. var id = __uri_to_id(uri),
  1458. icon = _utils.jsonp( _mmmk.read(id) ),
  1459. updd = this.__runParser(
  1460. icon['parser']['value'],
  1461. reqData['changes'],
  1462. icon );
  1463. if( updd && updd['$err'] )
  1464. return __postInternalErrorMsg(resp,updd['$err']);
  1465. if( updd )
  1466. this['PUT *.instance'](
  1467. resp,
  1468. uri,
  1469. {'changes':updd,
  1470. 'hitchhiker':{'cschanges':reqData['changes']}} );
  1471. else
  1472. {
  1473. var sn = __sequenceNumber();
  1474. this.__checkpointUserOperation(sn);
  1475. __postMessage(
  1476. {'statusCode':200,
  1477. 'changelog':
  1478. _mmmk.update(id,reqData['changes'])['changelog'].
  1479. concat('$segments' in reqData['changes'] ?
  1480. this.__positionLinkDecorators(id) :
  1481. []),
  1482. 'sequence#':sn,
  1483. 'respIndex':resp});
  1484. }
  1485. },
  1486. /* INTENT :
  1487. update a VisualObject's attributes
  1488. IN PRACTICE:
  1489. perform intent *or* possibly adjust uri and reqData and forward to
  1490. asworker
  1491. 1. parse + validate parameters
  1492. 2. retrieve VisualObject and its parsing function
  1493. 3. execute parsing function to determine AS impacts
  1494. 4. if parsing produced an error, return it
  1495. 4. if there are AS impacts, simulate an edit-via-dialog update by
  1496. 'forwarding' the request (with modified reqData) to 'PUT *.instance'
  1497. *and* bundle requested CS update (for later handling)
  1498. 4. if there are no AS impacts, perform the requested VisualObject update
  1499. and post changelog */
  1500. 'PUT *.vobject' :
  1501. function(resp,uri,reqData)
  1502. {
  1503. var matches = uri.match(/.*\/(.*)\.instance\/(.*)\.vobject/);
  1504. if( ! matches )
  1505. return __postBadReqErrorMsg(
  1506. resp,
  1507. 'bad uri for VisualObject :: '+uri);
  1508. var id = matches[1],
  1509. vid = matches[2],
  1510. vobjAttr = '$contents/value/nodes/'+vid;
  1511. if( (res = _mmmk.read(id,'$contents'))['$err'] )
  1512. return __postBadReqErrorMsg(resp,res['$err']);
  1513. var __vo__ = res['nodes'][vid],
  1514. parsingf = __vo__['parser']['value'],
  1515. updd = this.__runParser(
  1516. parsingf,
  1517. reqData['changes'],
  1518. __vo__ );
  1519. if( updd && updd['$err'] )
  1520. return __postInternalErrorMsg(resp,updd['$err']);
  1521. var _reqData = {};
  1522. for( var attr in reqData['changes'] )
  1523. _reqData[vobjAttr+'/'+attr] = reqData['changes'][attr];
  1524. if( updd )
  1525. this['PUT *.instance'](
  1526. resp,
  1527. uri,
  1528. {'changes':updd,
  1529. 'hitchhiker':{'cschanges':_reqData}} );
  1530. else
  1531. {
  1532. var sn = __sequenceNumber();
  1533. this.__checkpointUserOperation(sn);
  1534. __postMessage(
  1535. {'statusCode':200,
  1536. 'changelog':_mmmk.update(id,_reqData)['changelog'],
  1537. 'sequence#':sn,
  1538. 'respIndex':resp});
  1539. }
  1540. },
  1541. /* INTENT :
  1542. A) generate a metamodel from the current AS model and write it to disk
  1543. OR
  1544. B) generate a CS metamodel (i.e., an icon definition metamodel) from
  1545. the current AS and CS models and write it to disk
  1546. OR
  1547. C) generate pattern metamodels from AS and CS metamodels
  1548. IN PRACTICE:
  1549. A) adjust uri and forward to asworker
  1550. OR
  1551. B) adjust uri and forward to asworker + bundle CS model
  1552. OR
  1553. C) do the deed
  1554. C) if the uri is a pattern metamodel uri,
  1555. 1. setup sync/async action chaining
  1556. a) read AS metamodel + store contents
  1557. b) read contents of parent dir
  1558. 2. launch chain... on error, return error... on success,
  1559. a) setup another sync/async action chaining
  1560. i. read all CS metamodels + store contents
  1561. ii. call _mt.ramify() with AS and CS metamodel data
  1562. iii. write results to disk
  1563. b) launch chain... return success or error code
  1564. B) if the uri is an icon definition metamodel uri,
  1565. 1. setup sync/async action chaining
  1566. a) ask asworker to generate metamodel and write it to disk... asworker
  1567. request reqData includes the current CS model
  1568. 2. launch chain... return success code or error
  1569. A) otherwise,
  1570. 1. setup sync/async action chaining
  1571. a) ask asworker to generate metamodel and write it to disk
  1572. 2. launch chain... return success code or error */
  1573. 'PUT *.metamodel' :
  1574. function(resp,uri)
  1575. {
  1576. if( (matches = uri.match(/\.pattern\.metamodel/)) )
  1577. {
  1578. var matches = uri.match(/\/GET(((.*\/).*).pattern.metamodel)/),
  1579. RAMasmmPath = './users'+matches[1],
  1580. asmmPath = './users'+matches[2]+'.metamodel',
  1581. parentDir = './users'+matches[3],
  1582. asmm = undefined,
  1583. csmms = {},
  1584. actions =
  1585. [_fs.readFile(asmmPath,'utf8'),
  1586. function(data)
  1587. {
  1588. asmm = data;
  1589. return _fs.readdir(parentDir);
  1590. }];
  1591. _do.chain(actions)(
  1592. function(files)
  1593. {
  1594. files =
  1595. files.filter(
  1596. function(f)
  1597. {return f.match(/\..*Icons\.metamodel/);});
  1598. var ramActions = [__successContinuable()];
  1599. files.forEach(
  1600. function(f)
  1601. {
  1602. ramActions.push(
  1603. function()
  1604. {
  1605. return _fs.readFile(parentDir+f,'utf8');
  1606. },
  1607. function(data)
  1608. {
  1609. csmms[f] = data;
  1610. return __successContinuable();
  1611. });
  1612. });
  1613. ramActions.push(
  1614. function()
  1615. {
  1616. var res = _mt.ramify(_utils.jsonp(asmm),csmms);
  1617. asmm = res['asmm'];
  1618. csmms = res['csmms'];
  1619. return _fs.writeFile(
  1620. RAMasmmPath,
  1621. _utils.jsons(asmm,null,'\t'));
  1622. });
  1623. files.forEach(
  1624. function(f)
  1625. {
  1626. ramActions.push(
  1627. function()
  1628. {
  1629. var RAMf = parentDir +
  1630. f.match(/(.*)\.metamodel/)[1] +
  1631. '.pattern.metamodel';
  1632. return _fs.writeFile(
  1633. RAMf,
  1634. _utils.jsons(csmms[f],null,'\t'));
  1635. });
  1636. });
  1637. _do.chain(ramActions)(
  1638. function()
  1639. {
  1640. __postMessage({'statusCode':200,'respIndex':resp});
  1641. },
  1642. function(err) {__postInternalErrorMsg(resp,err);}
  1643. );
  1644. },
  1645. function(err) {__postInternalErrorMsg(resp,err);}
  1646. );
  1647. }
  1648. else
  1649. {
  1650. var matches = uri.match(/\/GET(((.*\/).*)\..*Icons.metamodel)/),
  1651. asmmPath = (matches ? ('./users'+matches[2]+'.metamodel') : undefined),
  1652. asmm = undefined;
  1653. aswid = this.__aswid;
  1654. actions = [];
  1655. if (asmmPath) {
  1656. actions = [
  1657. _fs.readFile(asmmPath,'utf8'),
  1658. function(data) {
  1659. asmm = _utils.jsonp(data);
  1660. return __successContinuable();
  1661. },
  1662. function(result) {
  1663. return __wHttpReq('PUT',
  1664. uri+'?wid='+aswid,
  1665. ({'csm':_mmmk.read(), 'asmm': asmm}));
  1666. }];
  1667. } else {
  1668. actions = [__wHttpReq('PUT',
  1669. uri+'?wid='+aswid,
  1670. undefined)];
  1671. }
  1672. _do.chain(actions)(
  1673. function() { __postMessage({'statusCode':200,'respIndex':resp}); },
  1674. function(err) {__postInternalErrorMsg(resp,err);}
  1675. );
  1676. }
  1677. },
  1678. /* write a bundle containing this CS model and its associated AS model to
  1679. disk
  1680. 1. setup sync/async action chaining
  1681. a) ask asworker for current model (AS)
  1682. 2. launch chain... on error, return error... on success, compare sequence#
  1683. of returned AS model with next expected sequence# from asworker
  1684. a) if AS model is too old, restart
  1685. b) if AS model is too recent, wait 200 ms and restart
  1686. c) otherwise,
  1687. i. extract path info
  1688. ii. return error on invalid path
  1689. iii. ask _mmmk for current model (CS)
  1690. iv. setup another sync/async action chaining
  1691. a) write bundled AS and CS models to disk
  1692. v. launch chain... return success or error code */
  1693. 'PUT *.model' :
  1694. function(resp,uri)
  1695. {
  1696. var self = this,
  1697. actions = [__wHttpReq('GET','/current.model?wid='+this.__aswid)];
  1698. _do.chain(actions)(
  1699. function(asdata)
  1700. {
  1701. var sn = asdata['sequence#'];
  1702. if( self.__nextASWSequenceNumber - 1 > sn )
  1703. self['PUT *.model'](resp,urin);
  1704. else if( self.__nextASWSequenceNumber - 1 < sn )
  1705. setTimeout(self['PUT *.model'], 200, resp, urin);
  1706. else
  1707. {
  1708. if( (res = _mmmk.read())['$err'] )
  1709. __postInternalErrorMsg(resp,res['$err']);
  1710. else
  1711. {
  1712. var path = './users'+uri.substring('/GET'.length),
  1713. dir = _path.dirname(path);
  1714. if( dir.match(/"/) )
  1715. throw 'illegal filename... these characters are not'+
  1716. ' allowed in filenames :: "';
  1717. var mData = {
  1718. 'csm':_utils.jsonp(res),
  1719. 'asm':_utils.jsonp(asdata['data'])},
  1720. writeActions =
  1721. [_fspp.mkdirs(dir),
  1722. function()
  1723. {
  1724. return _fs.writeFile(
  1725. path,
  1726. _utils.jsons(mData,null,'\t'));
  1727. }];
  1728. _do.chain(writeActions)(
  1729. function()
  1730. {
  1731. __postMessage(
  1732. {'statusCode':200,
  1733. 'respIndex':resp});
  1734. },
  1735. function(writeErr)
  1736. {
  1737. __postInternalErrorMsg(resp,writeErr);
  1738. }
  1739. );
  1740. }
  1741. }
  1742. },
  1743. function(err) {__postInternalErrorMsg(resp,err);}
  1744. );
  1745. },
  1746. /* INTENT :
  1747. validate the associated AS model
  1748. IN PRACTICE:
  1749. adjust uri and forward to asworker
  1750. 1. setup sync/async action chaining
  1751. a) ask asworker to validate its model
  1752. 2. launch chain... return success code or error */
  1753. 'GET /validatem' :
  1754. function(resp,uri)
  1755. {
  1756. var actions = [__wHttpReq('GET',uri+'?wid='+this.__aswid)];
  1757. _do.chain(actions)(
  1758. function()
  1759. {
  1760. __postMessage({'statusCode':200, 'respIndex':resp});
  1761. },
  1762. function(err) {__postInternalErrorMsg(resp,err);}
  1763. );
  1764. },
  1765. /* INTENT :
  1766. undo/redo the effects of a client's last not yet undone/redone action
  1767. IN PRACTICE:
  1768. adjust uri and forward asworker undo/redos to asworker, and handle
  1769. csworker undo/redos locally
  1770. 1. if next __handledSeqNums is a non-csworker sequence#,
  1771. a) if it's a batchEdit marker:
  1772. i. adjust __handledSeqNums['i'] to account for multiple undos/redos
  1773. ii. populate reqData['redo/undoUntil'] with batchEdit marker s.t.
  1774. asworker knows to undo/redo everything til specified marker
  1775. iii. populate hitchhiker['redo/undo'] with batchEdit marker s.t. when
  1776. asworker undo/redo changelog comes around, csworkers know until
  1777. where they should undo/redo
  1778. iv. forward request to asworker and return success code or error
  1779. a) if it's an asworker marker:
  1780. i. populate hitchhiker['redo/undo'] with asworker marker s.t. when
  1781. asworker undo/redo changelog comes around, csworkers know until
  1782. where they should undo/redo
  1783. ii. forward request to asworker and return success code or error */
  1784. 'POST /undo' :
  1785. function(resp,uri,reqData/*[undoUntil]*/)
  1786. {
  1787. if( this.__handledSeqNums['i'] == undefined )
  1788. this.__handledSeqNums['i'] = this.__handledSeqNums['#s'].length-1;
  1789. if( this.__handledSeqNums['#s'][this.__handledSeqNums['i']] )
  1790. this.__undoredo(
  1791. resp,
  1792. uri,
  1793. (reqData != undefined && 'undoUntil' in reqData ?
  1794. reqData['undoUntil'] :
  1795. this.__handledSeqNums['#s'][this.__handledSeqNums['i']--]),
  1796. 'undo');
  1797. else
  1798. __postMessage({'statusCode':200, 'respIndex':resp});
  1799. },
  1800. 'POST /redo' :
  1801. function(resp,uri)
  1802. {
  1803. if( this.__handledSeqNums['i'] == undefined )
  1804. this.__handledSeqNums['i'] = this.__handledSeqNums['#s'].length-1;
  1805. if( this.__handledSeqNums['#s'][this.__handledSeqNums['i']+1] )
  1806. this.__undoredo(
  1807. resp,
  1808. uri,
  1809. this.__handledSeqNums['#s'][++this.__handledSeqNums['i']],
  1810. 'redo');
  1811. else
  1812. __postMessage({'statusCode':200, 'respIndex':resp});
  1813. },
  1814. '__undoredo' :
  1815. function(resp,uri,sn,func)
  1816. {
  1817. if( ! sn.match(__wtype) )
  1818. {
  1819. var hitchhiker = {},
  1820. reqData = {'hitchhiker':hitchhiker},
  1821. actions = [__wHttpReq(
  1822. 'POST',
  1823. uri+'?wid='+this.__aswid,
  1824. reqData) ];
  1825. if( (matches = sn.match(/^bchkpt@([0-9]+)/)) )
  1826. {
  1827. if( func == 'undo' )
  1828. {
  1829. for( ;
  1830. ! this.__handledSeqNums['#s'][this.__handledSeqNums['i']].
  1831. match('^bchkpt@'+matches[1]);
  1832. this.__handledSeqNums['i']-- )
  1833. ;
  1834. this.__handledSeqNums['i']--;
  1835. reqData[func+'Until'] = hitchhiker[func] =
  1836. __batchCheckpoint(matches[1],true);
  1837. }
  1838. else
  1839. {
  1840. this.__handledSeqNums['i']++;
  1841. for( ;
  1842. ! this.__handledSeqNums['#s'][this.__handledSeqNums['i']].
  1843. match('^bchkpt@'+matches[1]);
  1844. this.__handledSeqNums['i']++ )
  1845. ;
  1846. reqData[func+'Until'] = hitchhiker[func] =
  1847. __batchCheckpoint(matches[1]);
  1848. }
  1849. }
  1850. else
  1851. hitchhiker[func] = sn;
  1852. _do.chain( actions )(
  1853. function()
  1854. {
  1855. __postMessage({'statusCode':202, 'respIndex':resp});
  1856. },
  1857. function(err) {__postInternalErrorMsg(resp,err);}
  1858. );
  1859. }
  1860. else
  1861. __postMessage(
  1862. {'statusCode':200,
  1863. 'changelog':_mmmk[func](sn)['changelog'],
  1864. 'sequence#':__sequenceNumber(),
  1865. 'respIndex':resp});
  1866. },
  1867. /* INTENT :
  1868. place an easily identifiable user-checkpoint in the journal
  1869. IN PRACTICE:
  1870. adjust uri and forward to asworker
  1871. 1. setup sync/async action chaining
  1872. a) forward request to asworker
  1873. 2. launch chain... return success code or error */
  1874. 'POST /batchCheckpoint' :
  1875. function(resp,uri,reqData)
  1876. {
  1877. var actions = [
  1878. __wHttpReq('POST',uri+'?wid='+this.__aswid,reqData)];
  1879. _do.chain(actions)(
  1880. function()
  1881. {
  1882. __postMessage({'statusCode':202, 'respIndex':resp});
  1883. },
  1884. function(err) {__postInternalErrorMsg(resp,err);}
  1885. );
  1886. },
  1887. /********************************** UTILS **********************************/
  1888. /* wrapper around reads to '__asid2csid'... needed because loading a model
  1889. (as opposed to creating it from scratch) doesn't populate this data
  1890. structure... this wrapper enables its lazy and transparent population as
  1891. read queries are made */
  1892. '__asid_to_csid' :
  1893. function(asid)
  1894. {
  1895. if( this.__asid2csid[asid] != undefined )
  1896. return this.__asid2csid[asid];
  1897. var csm = _utils.jsonp(_mmmk.read());
  1898. for( var csid in csm.nodes )
  1899. if( __uri_to_id(_mmmk.read(csid,'$asuri')) == asid )
  1900. return (this.__asid2csid[asid] = csid);
  1901. },
  1902. /* return a fullcstype from a fullastype */
  1903. '__astype_to_cstype' :
  1904. function(fullastype,isLink)
  1905. {
  1906. var matches = fullastype.match(/(.*)\/(.*)/),
  1907. asmm = matches[1],
  1908. astype = matches[2];
  1909. return this.__asmm2csmm[asmm]+'/'+astype+(isLink ? 'Link' : 'Icon');
  1910. },
  1911. /* return the CS instance uri associated to the AS instance described by the
  1912. given uri */
  1913. '__asuri_to_csuri' :
  1914. function(uri)
  1915. {
  1916. if( (asid = __uri_to_id(uri))['$err'] )
  1917. return asid;
  1918. return __id_to_uri(this.__asid_to_csid(asid));
  1919. },
  1920. /* add a checkpointing marker in mmmk and log the said marker as a
  1921. non-undo/redo operation (remove any undone operations from log first) */
  1922. '__checkpointUserOperation' :
  1923. function(sn)
  1924. {
  1925. _mmmk.setUserCheckpoint(sn);
  1926. if( this.__handledSeqNums['i'] != undefined )
  1927. {
  1928. this.__handledSeqNums['#s'].splice( this.__handledSeqNums['i']+1 );
  1929. this.__handledSeqNums['i'] = undefined;
  1930. }
  1931. this.__handledSeqNums['#s'].push(sn);
  1932. },
  1933. /* produce a bundle of internal state variables sufficient to fully clone
  1934. this instance
  1935. OR
  1936. use a provided bundle to overwrite this instance's internal state */
  1937. '__clone' :
  1938. function(clone)
  1939. {
  1940. if( clone )
  1941. {
  1942. this.__asmm2csmm = clone.__asmm2csmm;
  1943. this.__asid2csid = clone.__asid2csid;
  1944. this.__aswid = clone.__aswid;
  1945. this.__handledSeqNums = clone.__handledSeqNums;
  1946. this.__nextASWSequenceNumber = clone.__nextASWSequenceNumber;
  1947. this.__pendingChangelogs = clone.__pendingChangelogs;
  1948. this.__hitchhikerJournal = clone.__hitchhikerJournal;
  1949. }
  1950. else
  1951. return _utils.clone(
  1952. {'__asmm2csmm': this.__asmm2csmm,
  1953. '__asid2csid': this.__asid2csid,
  1954. '__aswid': this.__aswid,
  1955. '__handledSeqNums': this.__handledSeqNums,
  1956. '__nextASWSequenceNumber': this.__nextASWSequenceNumber,
  1957. '__pendingChangelogs': this.__pendingChangelogs,
  1958. '__hitchhikerJournal': this.__hitchhikerJournal});
  1959. },
  1960. /* return the AS instance uri associated to the CS instance described by the
  1961. given uri */
  1962. '__csuri_to_asuri' :
  1963. function(uri)
  1964. {
  1965. if( (csid = __uri_to_id(uri))['$err'] )
  1966. return csid;
  1967. else if( (asuri = _mmmk.read(csid,'$asuri'))['$err'] )
  1968. return asuri;
  1969. return asuri;
  1970. },
  1971. /* compute 'default' segments between the given icons (specified via uri) */
  1972. '__defaultSegments' :
  1973. function(src,dest)
  1974. {
  1975. var pos1 = _mmmk.read(__uri_to_id(src),'position'),
  1976. pos2 = _mmmk.read(__uri_to_id(dest),'position'),
  1977. middle = [pos2[0]-(pos2[0]-pos1[0])/2.0,
  1978. pos2[1]-(pos2[1]-pos1[1])/2.0];
  1979. return ['M'+pos1+'L'+middle, 'M'+middle+'L'+pos2];
  1980. },
  1981. /* compute the x,y center of the icons given by the specified AS uris */
  1982. '__nodesCenter' :
  1983. function(asuris)
  1984. {
  1985. var sumx = 0,
  1986. sumy = 0,
  1987. self = this;
  1988. asuris.forEach(
  1989. function(asuri)
  1990. {
  1991. var asid = __uri_to_id(asuri),
  1992. csid = self.__asid_to_csid(asid),
  1993. pos = _mmmk.read(csid,'position');
  1994. sumx += parseFloat(pos[0]);
  1995. sumy += parseFloat(pos[1]);
  1996. });
  1997. return [sumx/asuris.length, sumy/asuris.length];
  1998. },
  1999. /* run given code within given contexts
  2000. 1. setup a very stripped down version of _mmmk.__runDesignerCode() with
  2001. getAttr() and safe_eval() (see _mmmk.__runDesignerCode() for more
  2002. elaborate comments)
  2003. 2. safely evaluate code and return result
  2004. NOTE: getAttr() first checks the 'local' context and then the 'global'
  2005. context to find requested attributes... this enables such behaviours
  2006. as accessing 'new' attribute values as opposed to those stored in
  2007. _mmmk */
  2008. '__runParser' :
  2009. function(parser,local,global)
  2010. {
  2011. function getAttr(_attr)
  2012. {
  2013. if( _attr in local )
  2014. return local[_attr];
  2015. else if( !(_attr in global) || _attr.charAt(0) == '$')
  2016. throw 'invalid getAttr() attribute :: '+_attr;
  2017. return _utils.clone(global[_attr]['value']);
  2018. }
  2019. function safe_eval(code)
  2020. {
  2021. try {return eval(code);}
  2022. catch(err) {return {'$err':err};}
  2023. }
  2024. return safe_eval(parser);
  2025. },
  2026. /* returns the numeric part of sequence# of the form 'src#number' */
  2027. '__sn2int' :
  2028. function(sn)
  2029. {
  2030. return parseInt(sn.match(/.*#(\d*)/)[1]);
  2031. }
  2032. };