rules.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * EliasDB
  3. *
  4. * Copyright 2016 Matthias Ladkau. All rights reserved.
  5. *
  6. * This Source Code Form is subject to the terms of the Mozilla Public
  7. * License, v. 2.0. If a copy of the MPL was not distributed with this
  8. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9. */
  10. package graph
  11. import (
  12. "sort"
  13. "strings"
  14. "sync"
  15. "devt.de/krotik/eliasdb/graph/data"
  16. "devt.de/krotik/eliasdb/graph/util"
  17. )
  18. /*
  19. GraphRulesManager data structure
  20. */
  21. type graphRulesManager struct {
  22. gm *Manager // GraphManager which provides events
  23. rules map[string]Rule // Map of graph rules
  24. eventMap map[int]map[string]Rule // Map of events to graph rules
  25. }
  26. /*
  27. Rule models a graph rule.
  28. */
  29. type Rule interface {
  30. /*
  31. Name returns the name of the rule.
  32. */
  33. Name() string
  34. /*
  35. Handles returns a list of events which are handled by this rule.
  36. */
  37. Handles() []int
  38. /*
  39. Handle handles an event. The function should write all changes to the
  40. given transaction.
  41. */
  42. Handle(gm *Manager, trans Trans, event int, data ...interface{}) error
  43. }
  44. /*
  45. graphEvent main event handler which receives all graph related events.
  46. */
  47. func (gr *graphRulesManager) graphEvent(trans Trans, event int, data ...interface{}) error {
  48. var result error
  49. var errors []string
  50. rules, ok := gr.eventMap[event]
  51. handled := false // Flag to return a special handled error if no other error occured
  52. if ok {
  53. for _, rule := range rules {
  54. // Craete a GraphManager clone which can be used for queries only
  55. gmclone := gr.cloneGraphManager()
  56. gmclone.mutex.RLock()
  57. defer gmclone.mutex.RUnlock()
  58. // Handle the event
  59. err := rule.Handle(gmclone, trans, event, data...)
  60. if err != nil {
  61. if err == ErrEventHandled {
  62. handled = true
  63. } else {
  64. if errors == nil {
  65. errors = make([]string, 0)
  66. }
  67. errors = append(errors, err.Error())
  68. }
  69. }
  70. }
  71. }
  72. if errors != nil {
  73. return &util.GraphError{Type: util.ErrRule, Detail: strings.Join(errors, ";")}
  74. }
  75. if handled {
  76. result = ErrEventHandled
  77. }
  78. return result
  79. }
  80. /*
  81. Clone a given graph manager and insert a new RWMutex.
  82. */
  83. func (gr *graphRulesManager) cloneGraphManager() *Manager {
  84. return &Manager{gr.gm.gs, gr, gr.gm.nm, gr.gm.mapCache, &sync.RWMutex{}, &sync.Mutex{}}
  85. }
  86. /*
  87. SetGraphRule sets a GraphRule.
  88. */
  89. func (gr *graphRulesManager) SetGraphRule(rule Rule) {
  90. gr.rules[rule.Name()] = rule
  91. for _, handledEvent := range rule.Handles() {
  92. rules, ok := gr.eventMap[handledEvent]
  93. if !ok {
  94. rules = make(map[string]Rule)
  95. gr.eventMap[handledEvent] = rules
  96. }
  97. rules[rule.Name()] = rule
  98. }
  99. }
  100. /*
  101. GraphRules returns a list of all available graph rules.
  102. */
  103. func (gr *graphRulesManager) GraphRules() []string {
  104. ret := make([]string, 0, len(gr.rules))
  105. for rule := range gr.rules {
  106. ret = append(ret, rule)
  107. }
  108. sort.StringSlice(ret).Sort()
  109. return ret
  110. }
  111. // System rule SystemRuleDeleteNodeEdges
  112. // =====================================
  113. /*
  114. SystemRuleDeleteNodeEdges is a system rule to delete all edges when a node is
  115. deleted. Deletes also the other end if the cascading flag is set on the edge.
  116. */
  117. type SystemRuleDeleteNodeEdges struct {
  118. }
  119. /*
  120. Name returns the name of the rule.
  121. */
  122. func (r *SystemRuleDeleteNodeEdges) Name() string {
  123. return "system.deletenodeedges"
  124. }
  125. /*
  126. Handles returns a list of events which are handled by this rule.
  127. */
  128. func (r *SystemRuleDeleteNodeEdges) Handles() []int {
  129. return []int{EventNodeDeleted}
  130. }
  131. /*
  132. Handle handles an event.
  133. */
  134. func (r *SystemRuleDeleteNodeEdges) Handle(gm *Manager, trans Trans, event int, ed ...interface{}) error {
  135. part := ed[0].(string)
  136. node := ed[1].(data.Node)
  137. // Get all connected nodes and relationships
  138. nnodes, edges, err := gm.TraverseMulti(part, node.Key(), node.Kind(), ":::", false)
  139. if err != nil {
  140. return err
  141. }
  142. edgeRemovalCount := make(map[string]int) // Count of cascading last edges which are removed
  143. // Nodes which need to be checked if the last edge of a certain kind has been removed
  144. var nodeRemovalCheckNodes []data.Node
  145. var nodeRemovalCheckSpecs []string
  146. for i, edge := range edges {
  147. // Remove the edge in any case
  148. trans.RemoveEdge(part, edge.Key(), edge.Kind())
  149. // Remove the node on the other side if the edge is cascading on this end
  150. if edge.End1IsCascading() {
  151. if edge.End1IsCascadingLast() {
  152. // Only remove the node at the other end if all edges of this kind
  153. // have been removed from that node after this operation
  154. // Get edge spec from other side
  155. nodeOtherSide := nnodes[i]
  156. specOtherSide := edge.Spec(nodeOtherSide.Key())
  157. if c, ok := edgeRemovalCount[specOtherSide]; ok {
  158. edgeRemovalCount[specOtherSide] = c + 1
  159. } else {
  160. edgeRemovalCount[specOtherSide] = 1
  161. }
  162. nodeRemovalCheckSpecs = append(nodeRemovalCheckSpecs, specOtherSide)
  163. nodeRemovalCheckNodes = append(nodeRemovalCheckNodes, nodeOtherSide)
  164. } else {
  165. // No error handling at this point since only a wrong partition
  166. // name can cause an issue and this would have failed before
  167. trans.RemoveNode(part, nnodes[i].Key(), nnodes[i].Kind())
  168. }
  169. }
  170. }
  171. // Check cascading last edges
  172. for i, node := range nodeRemovalCheckNodes {
  173. specToCheck := nodeRemovalCheckSpecs[i]
  174. removalCount := edgeRemovalCount[specToCheck]
  175. if err == nil {
  176. _, edges, err = gm.TraverseMulti(part, node.Key(), node.Kind(), specToCheck, false)
  177. if len(edges)-removalCount == 0 {
  178. trans.RemoveNode(part, node.Key(), node.Kind())
  179. }
  180. }
  181. }
  182. return err
  183. }
  184. // System rule SystemRuleUpdateNodeStats
  185. // =====================================
  186. /*
  187. SystemRuleUpdateNodeStats is a system rule to update info entries such as
  188. known node or edge kinds in the MainDB.
  189. */
  190. type SystemRuleUpdateNodeStats struct {
  191. }
  192. /*
  193. Name returns the name of the rule.
  194. */
  195. func (r *SystemRuleUpdateNodeStats) Name() string {
  196. return "system.updatenodestats"
  197. }
  198. /*
  199. Handles returns a list of events which are handled by this rule.
  200. */
  201. func (r *SystemRuleUpdateNodeStats) Handles() []int {
  202. return []int{EventNodeCreated, EventNodeUpdated,
  203. EventEdgeCreated, EventEdgeUpdated}
  204. }
  205. /*
  206. Handle handles an event.
  207. */
  208. func (r *SystemRuleUpdateNodeStats) Handle(gm *Manager, trans Trans, event int, ed ...interface{}) error {
  209. attrMap := MainDBNodeAttrs
  210. if event == EventEdgeCreated {
  211. edge := ed[1].(data.Edge)
  212. updateNodeRels := func(key string, kind string) {
  213. spec := edge.Spec(key)
  214. specs := gm.getMainDBMap(MainDBNodeEdges + kind)
  215. if specs != nil {
  216. if _, ok := specs[spec]; !ok {
  217. specs[spec] = ""
  218. gm.storeMainDBMap(MainDBNodeEdges+kind, specs)
  219. }
  220. }
  221. }
  222. // Update stored relationships for both ends
  223. updateNodeRels(edge.End1Key(), edge.End1Kind())
  224. updateNodeRels(edge.End2Key(), edge.End2Kind())
  225. attrMap = MainDBEdgeAttrs
  226. }
  227. node := ed[1].(data.Node)
  228. kind := node.Kind()
  229. // Check if a new partition or kind was used
  230. if event == EventNodeCreated || event == EventEdgeCreated {
  231. part := ed[0].(string)
  232. updateMainDB := func(entry string, val string) {
  233. vals := gm.getMainDBMap(entry)
  234. if _, ok := vals[val]; !ok {
  235. vals[val] = ""
  236. gm.storeMainDBMap(entry, vals)
  237. }
  238. }
  239. updateMainDB(MainDBParts, part)
  240. if event == EventNodeCreated {
  241. updateMainDB(MainDBNodeKinds, kind)
  242. } else {
  243. updateMainDB(MainDBEdgeKinds, kind)
  244. }
  245. }
  246. storeAttrs := false
  247. attrs := gm.getMainDBMap(attrMap + kind)
  248. if attrs != nil {
  249. // Update stored node attributes
  250. for attr := range node.Data() {
  251. if _, ok := attrs[attr]; !ok {
  252. attrs[attr] = ""
  253. storeAttrs = true
  254. }
  255. }
  256. // Store attribute map if something was changed
  257. if storeAttrs {
  258. gm.storeMainDBMap(attrMap+kind, attrs)
  259. }
  260. }
  261. return nil
  262. }