forked from uber-go/dig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.go
466 lines (400 loc) · 12.6 KB
/
graph.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
// Copyright (c) 2019 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package dot
import (
"fmt"
"reflect"
)
// ErrorType of a constructor or group is updated when they fail to build.
type ErrorType int
const (
noError ErrorType = iota
rootCause
transitiveFailure
)
// CtorID is a unique numeric identifier for constructors.
type CtorID uintptr
// Ctor encodes a constructor provided to the container for the DOT graph.
type Ctor struct {
Name string
Package string
File string
Line int
ID CtorID
Params []*Param
GroupParams []*Group
Results []*Result
ErrorType ErrorType
}
// removeParam deletes the dependency on the provided result's nodeKey.
// This is used to prune links to results of deleted constructors.
func (c *Ctor) removeParam(k nodeKey) {
var pruned []*Param
for _, p := range c.Params {
if k != p.nodeKey() {
pruned = append(pruned, p)
}
}
c.Params = pruned
}
type nodeKey struct {
t reflect.Type
name string
group string
}
// Node is a single node in a graph and is embedded into Params and Results.
type Node struct {
Type reflect.Type
Name string
Group string
}
func (n *Node) nodeKey() nodeKey {
return nodeKey{t: n.Type, name: n.Name, group: n.Group}
}
// Param is a parameter node in the graph. Parameters are the input to constructors.
type Param struct {
*Node
Optional bool
}
// Result is a result node in the graph. Results are the output of constructors.
type Result struct {
*Node
// GroupIndex is added to differentiate grouped values from one another.
// Since grouped values have the same type and group, their Node / string
// representations are the same so we need indices to uniquely identify
// the values.
GroupIndex int
}
// Group is a group node in the graph. Group represents an fx value group.
type Group struct {
// Type is the type of values in the group.
Type reflect.Type
Name string
Results []*Result
ErrorType ErrorType
}
func (g *Group) nodeKey() nodeKey {
return nodeKey{t: g.Type, group: g.Name}
}
// TODO(rhang): Avoid linear search to discover group results that should be pruned.
func (g *Group) removeResult(r *Result) {
var pruned []*Result
for _, rg := range g.Results {
if r.GroupIndex != rg.GroupIndex {
pruned = append(pruned, rg)
}
}
g.Results = pruned
}
// Graph is the DOT-format graph in a Container.
type Graph struct {
Ctors []*Ctor
ctorMap map[CtorID]*Ctor
Groups []*Group
groupMap map[nodeKey]*Group
consumers map[nodeKey][]*Ctor
Failed *FailedNodes
}
// FailedNodes is the nodes that failed in the graph.
type FailedNodes struct {
// RootCauses is a list of the point of failures. They are the root causes
// of failed invokes and can be either missing types (not provided) or
// error types (error providing).
RootCauses []*Result
// TransitiveFailures is the list of nodes that failed to build due to
// missing/failed dependencies.
TransitiveFailures []*Result
// ctors is a collection of failed constructors IDs that are populated as the graph is
// traversed for errors.
ctors map[CtorID]struct{}
// Groups is a collection of failed groupKeys that is populated as the graph is traversed
// for errors.
groups map[nodeKey]struct{}
}
// NewGraph creates an empty graph.
func NewGraph() *Graph {
return &Graph{
ctorMap: make(map[CtorID]*Ctor),
groupMap: make(map[nodeKey]*Group),
consumers: make(map[nodeKey][]*Ctor),
Failed: &FailedNodes{
ctors: make(map[CtorID]struct{}),
groups: make(map[nodeKey]struct{}),
},
}
}
// NewGroup creates a new group with information in the groupKey.
func NewGroup(k nodeKey) *Group {
return &Group{
Type: k.t,
Name: k.group,
}
}
// AddCtor adds the constructor with paramList and resultList into the graph.
func (dg *Graph) AddCtor(c *Ctor, paramList []*Param, resultList []*Result) {
var (
params []*Param
groupParams []*Group
)
// Loop through the paramList to separate them into regular params and
// grouped params. For grouped params, we use getGroup to find the actual
// group.
for _, param := range paramList {
if param.Group == "" {
// Not a value group.
params = append(params, param)
continue
}
k := nodeKey{t: param.Type.Elem(), group: param.Group}
group := dg.getGroup(k)
groupParams = append(groupParams, group)
}
for _, result := range resultList {
// If the result is a grouped value, we want to update its GroupIndex
// and add it to the Group.
if result.Group != "" {
dg.addToGroup(result, c.ID)
}
}
c.Params = params
c.GroupParams = groupParams
c.Results = resultList
// Track which constructors consume a parameter.
for _, p := range paramList {
k := p.nodeKey()
dg.consumers[k] = append(dg.consumers[k], c)
}
dg.Ctors = append(dg.Ctors, c)
dg.ctorMap[c.ID] = c
}
func (dg *Graph) failNode(r *Result, isRootCause bool) {
if isRootCause {
dg.addRootCause(r)
} else {
dg.addTransitiveFailure(r)
}
}
// AddMissingNodes adds missing nodes to the list of failed Results in the graph.
func (dg *Graph) AddMissingNodes(results []*Result) {
// The failure(s) are root causes if there are no other failures.
isRootCause := len(dg.Failed.RootCauses) == 0
for _, r := range results {
dg.failNode(r, isRootCause)
}
}
// FailNodes adds results to the list of failed Results in the graph, and
// updates the state of the constructor with the given id accordingly.
func (dg *Graph) FailNodes(results []*Result, id CtorID) {
// This failure is the root cause if there are no other failures.
isRootCause := len(dg.Failed.RootCauses) == 0
dg.Failed.ctors[id] = struct{}{}
for _, r := range results {
dg.failNode(r, isRootCause)
}
if c, ok := dg.ctorMap[id]; ok {
if isRootCause {
c.ErrorType = rootCause
} else {
c.ErrorType = transitiveFailure
}
}
}
// FailGroupNodes finds and adds the failed grouped nodes to the list of failed
// Results in the graph, and updates the state of the group and constructor
// with the given id accordingly.
func (dg *Graph) FailGroupNodes(name string, t reflect.Type, id CtorID) {
// This failure is the root cause if there are no other failures.
isRootCause := len(dg.Failed.RootCauses) == 0
k := nodeKey{t: t, group: name}
group := dg.getGroup(k)
// If the ctor does not exist it cannot be failed.
if _, ok := dg.ctorMap[id]; !ok {
return
}
// Track which constructors and groups have failed.
dg.Failed.ctors[id] = struct{}{}
dg.Failed.groups[k] = struct{}{}
for _, r := range dg.ctorMap[id].Results {
if r.Type == t && r.Group == name {
dg.failNode(r, isRootCause)
}
}
if c, ok := dg.ctorMap[id]; ok {
if isRootCause {
group.ErrorType = rootCause
c.ErrorType = rootCause
} else {
group.ErrorType = transitiveFailure
c.ErrorType = transitiveFailure
}
}
}
// getGroup finds the group by nodeKey from the graph. If it is not available,
// a new group is created and returned.
func (dg *Graph) getGroup(k nodeKey) *Group {
g, ok := dg.groupMap[k]
if !ok {
g = NewGroup(k)
dg.groupMap[k] = g
dg.Groups = append(dg.Groups, g)
}
return g
}
// addToGroup adds a newly provided grouped result to the appropriate group.
func (dg *Graph) addToGroup(r *Result, id CtorID) {
k := nodeKey{t: r.Type, group: r.Group}
group := dg.getGroup(k)
r.GroupIndex = len(group.Results)
group.Results = append(group.Results, r)
}
// PruneSuccess removes elements from the graph that do not have failed results.
// Removing elements that do not have failing results makes the graph easier to debug,
// since non-failing nodes and edges can clutter the graph and don't help the user debug.
func (dg *Graph) PruneSuccess() {
dg.pruneCtors(dg.Failed.ctors)
dg.pruneGroups(dg.Failed.groups)
}
// pruneCtors removes constructors from the graph that do not have failing Results.
func (dg *Graph) pruneCtors(failed map[CtorID]struct{}) {
var pruned []*Ctor
for _, c := range dg.Ctors {
if _, ok := failed[c.ID]; ok {
pruned = append(pruned, c)
continue
}
// If a constructor is deleted, the constructor's stale result references need to
// be removed from that result's Group and/or consuming constructor.
dg.pruneCtorParams(c, dg.consumers)
dg.pruneGroupResults(c, dg.groupMap)
delete(dg.ctorMap, c.ID)
}
dg.Ctors = pruned
}
// pruneGroups removes groups from the graph that do not have failing results.
func (dg *Graph) pruneGroups(failed map[nodeKey]struct{}) {
var pruned []*Group
for _, g := range dg.Groups {
k := g.nodeKey()
if _, ok := failed[k]; ok {
pruned = append(pruned, g)
continue
}
delete(dg.groupMap, k)
}
dg.Groups = pruned
dg.pruneCtorGroupParams(dg.groupMap)
}
// pruneCtorParams removes results of the constructor argument that are still referenced in the
// Params of constructors that consume those results. If the results in the constructor are found
// in the params of a consuming constructor that result should be removed.
func (dg *Graph) pruneCtorParams(c *Ctor, consumers map[nodeKey][]*Ctor) {
for _, r := range c.Results {
for _, ctor := range consumers[r.nodeKey()] {
ctor.removeParam(r.nodeKey())
}
}
}
// pruneCtorGroupParams removes constructor results that are still referenced in the GroupParams of
// constructors that consume those results.
func (dg *Graph) pruneCtorGroupParams(groups map[nodeKey]*Group) {
for _, c := range dg.Ctors {
var pruned []*Group
for _, gp := range c.GroupParams {
k := gp.nodeKey()
if _, ok := groups[k]; ok {
pruned = append(pruned, gp)
}
}
c.GroupParams = pruned
}
}
// pruneGroupResults removes results of the constructor argument that are still referenced in
// the Group object that contains that result. If a group no longer exists references to that
// should should be removed.
func (dg *Graph) pruneGroupResults(c *Ctor, groups map[nodeKey]*Group) {
for _, r := range c.Results {
k := r.nodeKey()
if k.group == "" {
continue
}
g, ok := groups[k]
if ok {
g.removeResult(r)
}
}
}
// String implements fmt.Stringer for Param.
func (p *Param) String() string {
if p.Name != "" {
return fmt.Sprintf("%v[name=%v]", p.Type.String(), p.Name)
}
return p.Type.String()
}
// String implements fmt.Stringer for Result.
func (r *Result) String() string {
switch {
case r.Name != "":
return fmt.Sprintf("%v[name=%v]", r.Type.String(), r.Name)
case r.Group != "":
return fmt.Sprintf("%v[group=%v]%v", r.Type.String(), r.Group, r.GroupIndex)
default:
return r.Type.String()
}
}
// String implements fmt.Stringer for Group.
func (g *Group) String() string {
return fmt.Sprintf("[type=%v group=%v]", g.Type.String(), g.Name)
}
// Attributes composes and returns a string of the Result node's attributes.
func (r *Result) Attributes() string {
switch {
case r.Name != "":
return fmt.Sprintf(`label=<%v<BR /><FONT POINT-SIZE="10">Name: %v</FONT>>`, r.Type, r.Name)
case r.Group != "":
return fmt.Sprintf(`label=<%v<BR /><FONT POINT-SIZE="10">Group: %v</FONT>>`, r.Type, r.Group)
default:
return fmt.Sprintf(`label=<%v>`, r.Type)
}
}
// Attributes composes and returns a string of the Group node's attributes.
func (g *Group) Attributes() string {
attr := fmt.Sprintf(`shape=diamond label=<%v<BR /><FONT POINT-SIZE="10">Group: %v</FONT>>`, g.Type, g.Name)
if g.ErrorType != noError {
attr += " color=" + g.ErrorType.Color()
}
return attr
}
// Color returns the color representation of each ErrorType.
func (s ErrorType) Color() string {
switch s {
case rootCause:
return "red"
case transitiveFailure:
return "orange"
default:
return "black"
}
}
func (dg *Graph) addRootCause(r *Result) {
dg.Failed.RootCauses = append(dg.Failed.RootCauses, r)
}
func (dg *Graph) addTransitiveFailure(r *Result) {
dg.Failed.TransitiveFailures = append(dg.Failed.TransitiveFailures, r)
}