rules.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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 errors []string
  49. rules, ok := gr.eventMap[event]
  50. if ok {
  51. for _, rule := range rules {
  52. // Craete a GraphManager clone which can be used for queries only
  53. gmclone := gr.cloneGraphManager()
  54. gmclone.mutex.RLock()
  55. defer gmclone.mutex.RUnlock()
  56. // Handle the event
  57. err := rule.Handle(gmclone, trans, event, data...)
  58. if err != nil {
  59. if errors == nil {
  60. errors = make([]string, 0)
  61. }
  62. errors = append(errors, err.Error())
  63. }
  64. }
  65. }
  66. if errors != nil {
  67. return &util.GraphError{Type: util.ErrRule, Detail: strings.Join(errors, ";")}
  68. }
  69. return nil
  70. }
  71. /*
  72. Clone a given graph manager and insert a new RWMutex.
  73. */
  74. func (gr *graphRulesManager) cloneGraphManager() *Manager {
  75. return &Manager{gr.gm.gs, gr, gr.gm.nm, gr.gm.mapCache, &sync.RWMutex{}, &sync.Mutex{}}
  76. }
  77. /*
  78. SetGraphRule sets a GraphRule.
  79. */
  80. func (gr *graphRulesManager) SetGraphRule(rule Rule) {
  81. gr.rules[rule.Name()] = rule
  82. for _, handledEvent := range rule.Handles() {
  83. rules, ok := gr.eventMap[handledEvent]
  84. if !ok {
  85. rules = make(map[string]Rule)
  86. gr.eventMap[handledEvent] = rules
  87. }
  88. rules[rule.Name()] = rule
  89. }
  90. }
  91. /*
  92. GraphRules returns a list of all available graph rules.
  93. */
  94. func (gr *graphRulesManager) GraphRules() []string {
  95. ret := make([]string, 0, len(gr.rules))
  96. for rule := range gr.rules {
  97. ret = append(ret, rule)
  98. }
  99. sort.StringSlice(ret).Sort()
  100. return ret
  101. }
  102. // System rule SystemRuleDeleteNodeEdges
  103. // =====================================
  104. /*
  105. SystemRuleDeleteNodeEdges is a system rule to delete all edges when a node is
  106. deleted. Deletes also the other end if the cascading flag is set on the edge.
  107. */
  108. type SystemRuleDeleteNodeEdges struct {
  109. }
  110. /*
  111. Name returns the name of the rule.
  112. */
  113. func (r *SystemRuleDeleteNodeEdges) Name() string {
  114. return "system.deletenodeedges"
  115. }
  116. /*
  117. Handles returns a list of events which are handled by this rule.
  118. */
  119. func (r *SystemRuleDeleteNodeEdges) Handles() []int {
  120. return []int{EventNodeDeleted}
  121. }
  122. /*
  123. Handle handles an event.
  124. */
  125. func (r *SystemRuleDeleteNodeEdges) Handle(gm *Manager, trans Trans, event int, ed ...interface{}) error {
  126. part := ed[0].(string)
  127. node := ed[1].(data.Node)
  128. // Get all connected nodes and relationships
  129. nnodes, edges, err := gm.TraverseMulti(part, node.Key(), node.Kind(), ":::", false)
  130. if err != nil {
  131. return err
  132. }
  133. edgeRemovalCount := make(map[string]int) // Count of cascading last edges which are removed
  134. // Nodes which need to be checked if the last edge of a certain kind has been removed
  135. var nodeRemovalCheckNodes []data.Node
  136. var nodeRemovalCheckSpecs []string
  137. for i, edge := range edges {
  138. // Remove the edge in any case
  139. trans.RemoveEdge(part, edge.Key(), edge.Kind())
  140. // Remove the node on the other side if the edge is cascading on this end
  141. if edge.End1IsCascading() {
  142. if edge.End1IsCascadingLast() {
  143. // Only remove the node at the other end if all edges of this kind
  144. // have been removed from that node after this operation
  145. // Get edge spec from other side
  146. nodeOtherSide := nnodes[i]
  147. specOtherSide := edge.Spec(nodeOtherSide.Key())
  148. if c, ok := edgeRemovalCount[specOtherSide]; ok {
  149. edgeRemovalCount[specOtherSide] = c + 1
  150. } else {
  151. edgeRemovalCount[specOtherSide] = 1
  152. }
  153. nodeRemovalCheckSpecs = append(nodeRemovalCheckSpecs, specOtherSide)
  154. nodeRemovalCheckNodes = append(nodeRemovalCheckNodes, nodeOtherSide)
  155. } else {
  156. // No error handling at this point since only a wrong partition
  157. // name can cause an issue and this would have failed before
  158. trans.RemoveNode(part, nnodes[i].Key(), nnodes[i].Kind())
  159. }
  160. }
  161. }
  162. // Check cascading last edges
  163. for i, node := range nodeRemovalCheckNodes {
  164. specToCheck := nodeRemovalCheckSpecs[i]
  165. removalCount := edgeRemovalCount[specToCheck]
  166. if err == nil {
  167. _, edges, err = gm.TraverseMulti(part, node.Key(), node.Kind(), specToCheck, false)
  168. if len(edges)-removalCount == 0 {
  169. trans.RemoveNode(part, node.Key(), node.Kind())
  170. }
  171. }
  172. }
  173. return err
  174. }
  175. // System rule SystemRuleUpdateNodeStats
  176. // =====================================
  177. /*
  178. SystemRuleUpdateNodeStats is a system rule to update info entries such as
  179. known node or edge kinds in the MainDB.
  180. */
  181. type SystemRuleUpdateNodeStats struct {
  182. }
  183. /*
  184. Name returns the name of the rule.
  185. */
  186. func (r *SystemRuleUpdateNodeStats) Name() string {
  187. return "system.updatenodestats"
  188. }
  189. /*
  190. Handles returns a list of events which are handled by this rule.
  191. */
  192. func (r *SystemRuleUpdateNodeStats) Handles() []int {
  193. return []int{EventNodeCreated, EventNodeUpdated,
  194. EventEdgeCreated, EventEdgeUpdated}
  195. }
  196. /*
  197. Handle handles an event.
  198. */
  199. func (r *SystemRuleUpdateNodeStats) Handle(gm *Manager, trans Trans, event int, ed ...interface{}) error {
  200. attrMap := MainDBNodeAttrs
  201. if event == EventEdgeCreated {
  202. edge := ed[1].(data.Edge)
  203. updateNodeRels := func(key string, kind string) {
  204. spec := edge.Spec(key)
  205. specs := gm.getMainDBMap(MainDBNodeEdges + kind)
  206. if specs != nil {
  207. if _, ok := specs[spec]; !ok {
  208. specs[spec] = ""
  209. gm.storeMainDBMap(MainDBNodeEdges+kind, specs)
  210. }
  211. }
  212. }
  213. // Update stored relationships for both ends
  214. updateNodeRels(edge.End1Key(), edge.End1Kind())
  215. updateNodeRels(edge.End2Key(), edge.End2Kind())
  216. attrMap = MainDBEdgeAttrs
  217. }
  218. node := ed[1].(data.Node)
  219. kind := node.Kind()
  220. // Check if a new partition or kind was used
  221. if event == EventNodeCreated || event == EventEdgeCreated {
  222. part := ed[0].(string)
  223. updateMainDB := func(entry string, val string) {
  224. vals := gm.getMainDBMap(entry)
  225. if _, ok := vals[val]; !ok {
  226. vals[val] = ""
  227. gm.storeMainDBMap(entry, vals)
  228. }
  229. }
  230. updateMainDB(MainDBParts, part)
  231. if event == EventNodeCreated {
  232. updateMainDB(MainDBNodeKinds, kind)
  233. } else {
  234. updateMainDB(MainDBEdgeKinds, kind)
  235. }
  236. }
  237. storeAttrs := false
  238. attrs := gm.getMainDBMap(attrMap + kind)
  239. if attrs != nil {
  240. // Update stored node attributes
  241. for attr := range node.Data() {
  242. if _, ok := attrs[attr]; !ok {
  243. attrs[attr] = ""
  244. storeAttrs = true
  245. }
  246. }
  247. // Store attribute map if something was changed
  248. if storeAttrs {
  249. gm.storeMainDBMap(attrMap+kind, attrs)
  250. }
  251. }
  252. return nil
  253. }