-
Notifications
You must be signed in to change notification settings - Fork 35
/
dag.go
1337 lines (1127 loc) · 34.6 KB
/
dag.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package dag implements directed acyclic graphs (DAGs).
package dag
import (
"fmt"
"sync"
"github.com/google/uuid"
)
// IDInterface describes the interface a type must implement in order to
// explicitly specify vertex id.
//
// Objects of types not implementing this interface will receive automatically
// generated ids (as of adding them to the graph).
type IDInterface interface {
ID() string
}
// DAG implements the data structure of the DAG.
type DAG struct {
muDAG sync.RWMutex
vertices map[interface{}]string
vertexIds map[string]interface{}
inboundEdge map[interface{}]map[interface{}]struct{}
outboundEdge map[interface{}]map[interface{}]struct{}
muCache sync.RWMutex
verticesLocked *dMutex
ancestorsCache map[interface{}]map[interface{}]struct{}
descendantsCache map[interface{}]map[interface{}]struct{}
options Options
}
// NewDAG creates / initializes a new DAG.
func NewDAG() *DAG {
return &DAG{
vertices: make(map[interface{}]string),
vertexIds: make(map[string]interface{}),
inboundEdge: make(map[interface{}]map[interface{}]struct{}),
outboundEdge: make(map[interface{}]map[interface{}]struct{}),
verticesLocked: newDMutex(),
ancestorsCache: make(map[interface{}]map[interface{}]struct{}),
descendantsCache: make(map[interface{}]map[interface{}]struct{}),
options: defaultOptions(),
}
}
// AddVertex adds the vertex v to the DAG. AddVertex returns an error, if v is
// nil, v is already part of the graph, or the id of v is already part of the
// graph.
func (d *DAG) AddVertex(v interface{}) (string, error) {
d.muDAG.Lock()
defer d.muDAG.Unlock()
return d.addVertex(v)
}
func (d *DAG) addVertex(v interface{}) (string, error) {
var id string
if i, ok := v.(IDInterface); ok {
id = i.ID()
} else {
id = uuid.New().String()
}
err := d.addVertexByID(id, v)
return id, err
}
// AddVertexByID adds the vertex v and the specified id to the DAG.
// AddVertexByID returns an error, if v is nil, v is already part of the graph,
// or the specified id is already part of the graph.
func (d *DAG) AddVertexByID(id string, v interface{}) error {
d.muDAG.Lock()
defer d.muDAG.Unlock()
return d.addVertexByID(id, v)
}
func (d *DAG) addVertexByID(id string, v interface{}) error {
vHash := d.hashVertex(v)
// sanity checking
if v == nil {
return VertexNilError{}
}
if _, exists := d.vertices[vHash]; exists {
return VertexDuplicateError{v}
}
if _, exists := d.vertexIds[id]; exists {
return IDDuplicateError{id}
}
d.vertices[vHash] = id
d.vertexIds[id] = v
return nil
}
// GetVertex returns a vertex by its id. GetVertex returns an error, if id is
// the empty string or unknown.
func (d *DAG) GetVertex(id string) (interface{}, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
if id == "" {
return nil, IDEmptyError{}
}
v, exists := d.vertexIds[id]
if !exists {
return nil, IDUnknownError{id}
}
return v, nil
}
// DeleteVertex deletes the vertex with the given id. DeleteVertex also
// deletes all attached edges (inbound and outbound). DeleteVertex returns
// an error, if id is empty or unknown.
func (d *DAG) DeleteVertex(id string) error {
d.muDAG.Lock()
defer d.muDAG.Unlock()
if err := d.saneID(id); err != nil {
return err
}
v := d.vertexIds[id]
vHash := d.hashVertex(v)
// get descendents and ancestors as they are now
descendants := copyMap(d.getDescendants(vHash))
ancestors := copyMap(d.getAncestors(vHash))
// delete v in outbound edges of parents
if _, exists := d.inboundEdge[vHash]; exists {
for parent := range d.inboundEdge[vHash] {
delete(d.outboundEdge[parent], vHash)
}
}
// delete v in inbound edges of children
if _, exists := d.outboundEdge[vHash]; exists {
for child := range d.outboundEdge[vHash] {
delete(d.inboundEdge[child], vHash)
}
}
// delete in- and outbound of v itself
delete(d.inboundEdge, vHash)
delete(d.outboundEdge, vHash)
// for v and all its descendants delete cached ancestors
for descendant := range descendants {
delete(d.ancestorsCache, descendant)
}
delete(d.ancestorsCache, vHash)
// for v and all its ancestors delete cached descendants
for ancestor := range ancestors {
delete(d.descendantsCache, ancestor)
}
delete(d.descendantsCache, vHash)
// delete v itself
delete(d.vertices, vHash)
delete(d.vertexIds, id)
return nil
}
// AddEdge adds an edge between srcID and dstID. AddEdge returns an
// error, if srcID or dstID are empty strings or unknown, if the edge
// already exists, or if the new edge would create a loop.
func (d *DAG) AddEdge(srcID, dstID string) error {
d.muDAG.Lock()
defer d.muDAG.Unlock()
if err := d.saneID(srcID); err != nil {
return err
}
if err := d.saneID(dstID); err != nil {
return err
}
if srcID == dstID {
return SrcDstEqualError{srcID, dstID}
}
src := d.vertexIds[srcID]
srcHash := d.hashVertex(src)
dst := d.vertexIds[dstID]
dstHash := d.hashVertex(dst)
// if the edge is already known, there is nothing else to do
if d.isEdge(srcHash, dstHash) {
return EdgeDuplicateError{srcID, dstID}
}
// get descendents and ancestors as they are now
descendants := copyMap(d.getDescendants(dstHash))
ancestors := copyMap(d.getAncestors(srcHash))
if _, exists := descendants[srcHash]; exists {
return EdgeLoopError{srcID, dstID}
}
// prepare d.outbound[src], iff needed
if _, exists := d.outboundEdge[srcHash]; !exists {
d.outboundEdge[srcHash] = make(map[interface{}]struct{})
}
// dst is a child of src
d.outboundEdge[srcHash][dstHash] = struct{}{}
// prepare d.inboundEdge[dst], iff needed
if _, exists := d.inboundEdge[dstHash]; !exists {
d.inboundEdge[dstHash] = make(map[interface{}]struct{})
}
// src is a parent of dst
d.inboundEdge[dstHash][srcHash] = struct{}{}
// for dst and all its descendants delete cached ancestors
for descendant := range descendants {
delete(d.ancestorsCache, descendant)
}
delete(d.ancestorsCache, dstHash)
// for src and all its ancestors delete cached descendants
for ancestor := range ancestors {
delete(d.descendantsCache, ancestor)
}
delete(d.descendantsCache, srcHash)
return nil
}
// IsEdge returns true, if there exists an edge between srcID and dstID.
// IsEdge returns false, if there is no such edge. IsEdge returns an error,
// if srcID or dstID are empty, unknown, or the same.
func (d *DAG) IsEdge(srcID, dstID string) (bool, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
if err := d.saneID(srcID); err != nil {
return false, err
}
if err := d.saneID(dstID); err != nil {
return false, err
}
if srcID == dstID {
return false, SrcDstEqualError{srcID, dstID}
}
src := d.vertexIds[srcID]
dst := d.vertexIds[dstID]
return d.isEdge(d.hashVertex(src), d.hashVertex(dst)), nil
}
func (d *DAG) isEdge(srcHash, dstHash interface{}) bool {
if _, exists := d.outboundEdge[srcHash]; !exists {
return false
}
if _, exists := d.outboundEdge[srcHash][dstHash]; !exists {
return false
}
if _, exists := d.inboundEdge[dstHash]; !exists {
return false
}
if _, exists := d.inboundEdge[dstHash][srcHash]; !exists {
return false
}
return true
}
// DeleteEdge deletes the edge between srcID and dstID. DeleteEdge
// returns an error, if srcID or dstID are empty or unknown, or if,
// there is no edge between srcID and dstID.
func (d *DAG) DeleteEdge(srcID, dstID string) error {
d.muDAG.Lock()
defer d.muDAG.Unlock()
if err := d.saneID(srcID); err != nil {
return err
}
if err := d.saneID(dstID); err != nil {
return err
}
if srcID == dstID {
return SrcDstEqualError{srcID, dstID}
}
src := d.vertexIds[srcID]
srcHash := d.hashVertex(src)
dst := d.vertexIds[dstID]
dstHash := d.hashVertex(dst)
if !d.isEdge(srcHash, dstHash) {
return EdgeUnknownError{srcID, dstID}
}
// get descendents and ancestors as they are now
descendants := copyMap(d.getDescendants(srcHash))
ancestors := copyMap(d.getAncestors(dstHash))
// delete outbound and inbound
delete(d.outboundEdge[srcHash], dstHash)
delete(d.inboundEdge[dstHash], srcHash)
// for src and all its descendants delete cached ancestors
for descendant := range descendants {
delete(d.ancestorsCache, descendant)
}
delete(d.ancestorsCache, srcHash)
// for dst and all its ancestors delete cached descendants
for ancestor := range ancestors {
delete(d.descendantsCache, ancestor)
}
delete(d.descendantsCache, dstHash)
return nil
}
// GetOrder returns the number of vertices in the graph.
func (d *DAG) GetOrder() int {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
return d.getOrder()
}
func (d *DAG) getOrder() int {
return len(d.vertices)
}
// GetSize returns the number of edges in the graph.
func (d *DAG) GetSize() int {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
return d.getSize()
}
func (d *DAG) getSize() int {
count := 0
for _, value := range d.outboundEdge {
count += len(value)
}
return count
}
// GetLeaves returns all vertices without children.
func (d *DAG) GetLeaves() map[string]interface{} {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
return d.getLeaves()
}
func (d *DAG) getLeaves() map[string]interface{} {
leaves := make(map[string]interface{})
for v := range d.vertices {
dstIDs, ok := d.outboundEdge[v]
if !ok || len(dstIDs) == 0 {
id := d.vertices[v]
leaves[id] = v
}
}
return leaves
}
// IsLeaf returns true, if the vertex with the given id has no children. IsLeaf
// returns an error, if id is empty or unknown.
func (d *DAG) IsLeaf(id string) (bool, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
if err := d.saneID(id); err != nil {
return false, err
}
return d.isLeaf(id), nil
}
func (d *DAG) isLeaf(id string) bool {
v := d.vertexIds[id]
vHash := d.hashVertex(v)
dstIDs, ok := d.outboundEdge[vHash]
if !ok || len(dstIDs) == 0 {
return true
}
return false
}
// GetRoots returns all vertices without parents.
func (d *DAG) GetRoots() map[string]interface{} {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
return d.getRoots()
}
func (d *DAG) getRoots() map[string]interface{} {
roots := make(map[string]interface{})
for vHash := range d.vertices {
srcIDs, ok := d.inboundEdge[vHash]
if !ok || len(srcIDs) == 0 {
id := d.vertices[vHash]
roots[id] = vHash
}
}
return roots
}
// IsRoot returns true, if the vertex with the given id has no parents. IsRoot
// returns an error, if id is empty or unknown.
func (d *DAG) IsRoot(id string) (bool, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
if err := d.saneID(id); err != nil {
return false, err
}
return d.isRoot(id), nil
}
func (d *DAG) isRoot(id string) bool {
v := d.vertexIds[id]
vHash := d.hashVertex(v)
srcIDs, ok := d.inboundEdge[vHash]
if !ok || len(srcIDs) == 0 {
return true
}
return false
}
// GetVertices returns all vertices.
func (d *DAG) GetVertices() map[string]interface{} {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
out := make(map[string]interface{})
for id, value := range d.vertexIds {
out[id] = value
}
return out
}
// GetParents returns the all parents of the vertex with the id
// id. GetParents returns an error, if id is empty or unknown.
func (d *DAG) GetParents(id string) (map[string]interface{}, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
if err := d.saneID(id); err != nil {
return nil, err
}
v := d.vertexIds[id]
vHash := d.hashVertex(v)
parents := make(map[string]interface{})
for pv := range d.inboundEdge[vHash] {
pid := d.vertices[pv]
parents[pid] = pv
}
return parents, nil
}
// GetChildren returns all children of the vertex with the id
// id. GetChildren returns an error, if id is empty or unknown.
func (d *DAG) GetChildren(id string) (map[string]interface{}, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
return d.getChildren(id)
}
func (d *DAG) getChildren(id string) (map[string]interface{}, error) {
if err := d.saneID(id); err != nil {
return nil, err
}
v := d.vertexIds[id]
vHash := d.hashVertex(v)
children := make(map[string]interface{})
for cv := range d.outboundEdge[vHash] {
cid := d.vertices[cv]
children[cid] = cv
}
return children, nil
}
// GetAncestors return all ancestors of the vertex with the id id. GetAncestors
// returns an error, if id is empty or unknown.
//
// Note, in order to get the ancestors, GetAncestors populates the ancestor-
// cache as needed. Depending on order and size of the sub-graph of the vertex
// with id id this may take a long time and consume a lot of memory.
func (d *DAG) GetAncestors(id string) (map[string]interface{}, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
if err := d.saneID(id); err != nil {
return nil, err
}
v := d.vertexIds[id]
vHash := d.hashVertex(v)
ancestors := make(map[string]interface{})
for av := range d.getAncestors(vHash) {
aid := d.vertices[av]
ancestors[aid] = av
}
return ancestors, nil
}
func (d *DAG) getAncestors(vHash interface{}) map[interface{}]struct{} {
// in the best case we have already a populated cache
d.muCache.RLock()
cache, exists := d.ancestorsCache[vHash]
d.muCache.RUnlock()
if exists {
return cache
}
// lock this vertex to work on it exclusively
d.verticesLocked.lock(vHash)
defer d.verticesLocked.unlock(vHash)
// now as we have locked this vertex, check (again) that no one has
// meanwhile populated the cache
d.muCache.RLock()
cache, exists = d.ancestorsCache[vHash]
d.muCache.RUnlock()
if exists {
return cache
}
// as there is no cache, we start from scratch and collect all ancestors locally
cache = make(map[interface{}]struct{})
var mu sync.Mutex
if parents, ok := d.inboundEdge[vHash]; ok {
// for each parent collect its ancestors
for parent := range parents {
parentAncestors := d.getAncestors(parent)
mu.Lock()
for ancestor := range parentAncestors {
cache[ancestor] = struct{}{}
}
cache[parent] = struct{}{}
mu.Unlock()
}
}
// remember the collected descendents
d.muCache.Lock()
d.ancestorsCache[vHash] = cache
d.muCache.Unlock()
return cache
}
// GetOrderedAncestors returns all ancestors of the vertex with id id
// in a breath-first order. Only the first occurrence of each vertex is
// returned. GetOrderedAncestors returns an error, if id is empty or
// unknown.
//
// Note, there is no order between sibling vertices. Two consecutive runs of
// GetOrderedAncestors may return different results.
func (d *DAG) GetOrderedAncestors(id string) ([]string, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
ids, _, err := d.AncestorsWalker(id)
if err != nil {
return nil, err
}
var ancestors []string
for aid := range ids {
ancestors = append(ancestors, aid)
}
return ancestors, nil
}
// AncestorsWalker returns a channel and subsequently returns / walks all
// ancestors of the vertex with id id in a breath first order. The second
// channel returned may be used to stop further walking. AncestorsWalker
// returns an error, if id is empty or unknown.
//
// Note, there is no order between sibling vertices. Two consecutive runs of
// AncestorsWalker may return different results.
func (d *DAG) AncestorsWalker(id string) (chan string, chan bool, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
if err := d.saneID(id); err != nil {
return nil, nil, err
}
ids := make(chan string)
signal := make(chan bool, 1)
go func() {
d.muDAG.RLock()
v := d.vertexIds[id]
vHash := d.hashVertex(v)
d.walkAncestors(vHash, ids, signal)
d.muDAG.RUnlock()
close(ids)
close(signal)
}()
return ids, signal, nil
}
func (d *DAG) walkAncestors(vHash interface{}, ids chan string, signal chan bool) {
var fifo []interface{}
visited := make(map[interface{}]struct{})
for parent := range d.inboundEdge[vHash] {
visited[parent] = struct{}{}
fifo = append(fifo, parent)
}
for {
if len(fifo) == 0 {
return
}
top := fifo[0]
fifo = fifo[1:]
for parent := range d.inboundEdge[top] {
if _, exists := visited[parent]; !exists {
visited[parent] = struct{}{}
fifo = append(fifo, parent)
}
}
select {
case <-signal:
return
default:
ids <- d.vertices[top]
}
}
}
// GetDescendants return all descendants of the vertex with id id.
// GetDescendants returns an error, if id is empty or unknown.
//
// Note, in order to get the descendants, GetDescendants populates the
// descendants-cache as needed. Depending on order and size of the sub-graph
// of the vertex with id id this may take a long time and consume a lot
// of memory.
func (d *DAG) GetDescendants(id string) (map[string]interface{}, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
if err := d.saneID(id); err != nil {
return nil, err
}
v := d.vertexIds[id]
vHash := d.hashVertex(v)
descendants := make(map[string]interface{})
for dv := range d.getDescendants(vHash) {
did := d.vertices[dv]
descendants[did] = dv
}
return descendants, nil
}
func (d *DAG) getDescendants(vHash interface{}) map[interface{}]struct{} {
// in the best case we have already a populated cache
d.muCache.RLock()
cache, exists := d.descendantsCache[vHash]
d.muCache.RUnlock()
if exists {
return cache
}
// lock this vertex to work on it exclusively
d.verticesLocked.lock(vHash)
defer d.verticesLocked.unlock(vHash)
// now as we have locked this vertex, check (again) that no one has
// meanwhile populated the cache
d.muCache.RLock()
cache, exists = d.descendantsCache[vHash]
d.muCache.RUnlock()
if exists {
return cache
}
// as there is no cache, we start from scratch and collect all descendants
// locally
cache = make(map[interface{}]struct{})
var mu sync.Mutex
if children, ok := d.outboundEdge[vHash]; ok {
// for each child use a goroutine to collect its descendants
//var waitGroup sync.WaitGroup
//waitGroup.Add(len(children))
for child := range children {
//go func(child interface{}, mu *sync.Mutex, cache map[interface{}]bool) {
childDescendants := d.getDescendants(child)
mu.Lock()
for descendant := range childDescendants {
cache[descendant] = struct{}{}
}
cache[child] = struct{}{}
mu.Unlock()
//waitGroup.Done()
//}(child, &mu, cache)
}
//waitGroup.Wait()
}
// remember the collected descendents
d.muCache.Lock()
d.descendantsCache[vHash] = cache
d.muCache.Unlock()
return cache
}
// GetOrderedDescendants returns all descendants of the vertex with id id
// in a breath-first order. Only the first occurrence of each vertex is
// returned. GetOrderedDescendants returns an error, if id is empty or
// unknown.
//
// Note, there is no order between sibling vertices. Two consecutive runs of
// GetOrderedDescendants may return different results.
func (d *DAG) GetOrderedDescendants(id string) ([]string, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
ids, _, err := d.DescendantsWalker(id)
if err != nil {
return nil, err
}
var descendants []string
for did := range ids {
descendants = append(descendants, did)
}
return descendants, nil
}
// GetDescendantsGraph returns a new DAG consisting of the vertex with id id and
// all its descendants (i.e. the subgraph). GetDescendantsGraph also returns the
// id of the (copy of the) given vertex within the new graph (i.e. the id of the
// single root of the new graph). GetDescendantsGraph returns an error, if id is
// empty or unknown.
//
// Note, the new graph is a copy of the relevant part of the original graph.
func (d *DAG) GetDescendantsGraph(id string) (*DAG, string, error) {
// recursively add the current vertex and all its descendants
return d.getRelativesGraph(id, false)
}
// GetAncestorsGraph returns a new DAG consisting of the vertex with id id and
// all its ancestors (i.e. the subgraph). GetAncestorsGraph also returns the id
// of the (copy of the) given vertex within the new graph (i.e. the id of the
// single leaf of the new graph). GetAncestorsGraph returns an error, if id is
// empty or unknown.
//
// Note, the new graph is a copy of the relevant part of the original graph.
func (d *DAG) GetAncestorsGraph(id string) (*DAG, string, error) {
// recursively add the current vertex and all its ancestors
return d.getRelativesGraph(id, true)
}
func (d *DAG) getRelativesGraph(id string, asc bool) (*DAG, string, error) {
// sanity checking
if id == "" {
return nil, "", IDEmptyError{}
}
v, exists := d.vertexIds[id]
vHash := d.hashVertex(v)
if !exists {
return nil, "", IDUnknownError{id}
}
// create a new dag
newDAG := NewDAG()
// protect the graph from modification
d.muDAG.RLock()
defer d.muDAG.RUnlock()
// recursively add the current vertex and all its relatives
newId, err := d.getRelativesGraphRec(vHash, newDAG, make(map[interface{}]string), asc)
return newDAG, newId, err
}
func (d *DAG) getRelativesGraphRec(vHash interface{}, newDAG *DAG, visited map[interface{}]string, asc bool) (newId string, err error) {
// copy this vertex to the new graph
if newId, err = newDAG.AddVertex(vHash); err != nil {
return
}
// mark this vertex as visited
visited[vHash] = newId
// get the direct relatives (depending on the direction either parents or children)
var relatives map[interface{}]struct{}
var ok bool
if asc {
relatives, ok = d.inboundEdge[vHash]
} else {
relatives, ok = d.outboundEdge[vHash]
}
// for all direct relatives in the original graph
if ok {
for relative := range relatives {
// if we haven't seen this relative
relativeId, exists := visited[relative]
if !exists {
// recursively add this relative
if relativeId, err = d.getRelativesGraphRec(relative, newDAG, visited, asc); err != nil {
return
}
}
// add edge to this relative (depending on the direction)
var srcID, dstID string
if asc {
srcID, dstID = relativeId, newId
} else {
srcID, dstID = newId, relativeId
}
if err = newDAG.AddEdge(srcID, dstID); err != nil {
return
}
}
}
return
}
// DescendantsWalker returns a channel and subsequently returns / walks all
// descendants of the vertex with id in a breath first order. The second
// channel returned may be used to stop further walking. DescendantsWalker
// returns an error, if id is empty or unknown.
//
// Note, there is no order between sibling vertices. Two consecutive runs of
// DescendantsWalker may return different results.
func (d *DAG) DescendantsWalker(id string) (chan string, chan bool, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
if err := d.saneID(id); err != nil {
return nil, nil, err
}
ids := make(chan string)
signal := make(chan bool, 1)
go func() {
d.muDAG.RLock()
v := d.vertexIds[id]
vHash := d.hashVertex(v)
d.walkDescendants(vHash, ids, signal)
d.muDAG.RUnlock()
close(ids)
close(signal)
}()
return ids, signal, nil
}
func (d *DAG) walkDescendants(vHash interface{}, ids chan string, signal chan bool) {
var fifo []interface{}
visited := make(map[interface{}]struct{})
for child := range d.outboundEdge[vHash] {
visited[child] = struct{}{}
fifo = append(fifo, child)
}
for {
if len(fifo) == 0 {
return
}
top := fifo[0]
fifo = fifo[1:]
for child := range d.outboundEdge[top] {
if _, exists := visited[child]; !exists {
visited[child] = struct{}{}
fifo = append(fifo, child)
}
}
select {
case <-signal:
return
default:
ids <- d.vertices[top]
}
}
}
// FlowResult describes the data to be passed between vertices in a DescendantsFlow.
type FlowResult struct {
// The id of the vertex that produced this result.
ID string
// The actual result.
Result interface{}
// Any error. Note, DescendantsFlow does not care about this error. It is up to
// the FlowCallback of downstream vertices to handle the error as needed - if
// needed.
Error error
}
// FlowCallback is the signature of the (callback-) function to call for each
// vertex within a DescendantsFlow, after all its parents have finished their
// work. The parameters of the function are the (complete) DAG, the current
// vertex ID, and the results of all its parents. An instance of FlowCallback
// should return a result or an error.
type FlowCallback func(d *DAG, id string, parentResults []FlowResult) (interface{}, error)
// DescendantsFlow traverses descendants of the vertex with the ID startID. For
// the vertex itself and each of its descendant it executes the given (callback-)
// function providing it the results of its respective parents. The (callback-)
// function is only executed after all parents have finished their work.
func (d *DAG) DescendantsFlow(startID string, inputs []FlowResult, callback FlowCallback) ([]FlowResult, error) {
d.muDAG.RLock()
defer d.muDAG.RUnlock()
// Get IDs of all descendant vertices.
flowIDs, errDes := d.GetDescendants(startID)
if errDes != nil {
return []FlowResult{}, errDes
}
// inputChannels provides for input channels for each of the descendant vertices (+ the start-vertex).
inputChannels := make(map[string]chan FlowResult, len(flowIDs)+1)
// Iterate vertex IDs and create an input channel for each of them and a single
// output channel for leaves. Note, this "pre-flight" is needed to ensure we
// really have an input channel regardless of how we traverse the tree and spawn
// workers.
leafCount := 0
if len(flowIDs) == 0 {
leafCount = 1
}
for id := range flowIDs {
// Get all parents of this vertex.
parents, errPar := d.GetParents(id)
if errPar != nil {
return []FlowResult{}, errPar
}
// Create a buffered input channel that has capacity for all parent results.
inputChannels[id] = make(chan FlowResult, len(parents))
if d.isLeaf(id) {
leafCount += 1
}
}
// outputChannel caries the results of leaf vertices.
outputChannel := make(chan FlowResult, leafCount)
// To also process the start vertex and to have its results being passed to its
// children, add it to the vertex IDs. Also add an input channel for the start
// vertex and feed the inputs to this channel.
flowIDs[startID] = struct{}{}
inputChannels[startID] = make(chan FlowResult, len(inputs))
for _, i := range inputs {
inputChannels[startID] <- i
}
wg := sync.WaitGroup{}
// Iterate all vertex IDs (now incl. start vertex) and handle each worker (incl.
// inputs and outputs) in a separate goroutine.
for id := range flowIDs {
// Get all children of this vertex that later need to be notified. Note, we
// collect all children before the goroutine to be able to release the read
// lock as early as possible.
children, errChildren := d.GetChildren(id)
if errChildren != nil {
return []FlowResult{}, errChildren
}
// Remember to wait for this goroutine.
wg.Add(1)
go func(id string) {
// Get this vertex's input channel.
// Note, only concurrent read here, which is fine.
c := inputChannels[id]
// Await all parent inputs and stuff them into a slice.
parentCount := cap(c)
parentResults := make([]FlowResult, parentCount)
for i := 0; i < parentCount; i++ {
parentResults[i] = <-c
}
// Execute the worker.
result, errWorker := callback(d, id, parentResults)
// Wrap the worker's result into a FlowResult.
flowResult := FlowResult{