csworker.js 72 KB

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