csworker.js 74 KB

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