|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Generic; |
| 6 | +using System.Configuration; |
| 7 | +using System.Linq; |
| 8 | + |
| 9 | +namespace NuGet.Services.Validation.Orchestrator |
| 10 | +{ |
| 11 | + public static class TopologicalSort |
| 12 | + { |
| 13 | + /// <summary> |
| 14 | + /// Processors cannot run in parallel with other processors or even with other validators. Suppose you have the |
| 15 | + /// following validator graph (where --> indicates a validator dependent) |
| 16 | + /// |
| 17 | + /// ---> Validator B --- |
| 18 | + /// / \ |
| 19 | + /// Validator A --- ---> Validator D |
| 20 | + /// \ / |
| 21 | + /// ---> Validator C --- |
| 22 | + /// |
| 23 | + /// In this case, B and C cannot be processors. A and D can. Given a graph of validator dependencies and the |
| 24 | + /// list of validators that are processors, we use the following algorithm to determine whether it is possible |
| 25 | + /// for a processor to run in parallel with anything else. |
| 26 | + /// |
| 27 | + /// 1. Enumerate all valid orderings using topological sort. In our example above, this would be: |
| 28 | + /// - A B C D |
| 29 | + /// - A C B D |
| 30 | + /// 2. For each processor, verify that the position in all orderings is the same. |
| 31 | + /// - Note that A is always first and D is always fourth. |
| 32 | + /// |
| 33 | + /// This allows us to verify that a validator configuration is safe before orchestrator even starts accepting |
| 34 | + /// validation messages. |
| 35 | + /// </summary> |
| 36 | + /// <param name="validators">The validator configuration items.</param> |
| 37 | + /// <param name="cannotBeParallel">The names of validators that are also processors.</param> |
| 38 | + /// <exception cref="ConfigurationErrorsException"> |
| 39 | + /// Thrown if a cycle or parallel processor is found |
| 40 | + /// </exception> |
| 41 | + public static void Validate(IReadOnlyList<ValidationConfigurationItem> validators, IReadOnlyList<string> cannotBeParallel) |
| 42 | + { |
| 43 | + var allOrders = EnumerateAll(validators); |
| 44 | + if (!allOrders.Any()) |
| 45 | + { |
| 46 | + throw new ConfigurationErrorsException("No validation sequences were found. This indicates a cycle in the validation dependencies."); |
| 47 | + } |
| 48 | + |
| 49 | + // A dictionary mapping the name of the validator to its index in the first topological sort result. All |
| 50 | + // other results must have their processors at the same indexes. If this is true, that means that no |
| 51 | + // validators or processors can run in parallel with any processor. |
| 52 | + var nameToExpectedIndex = allOrders[0] |
| 53 | + .Select((x, i) => new { Name = x, Index = i }) |
| 54 | + .ToDictionary(x => x.Name, x => x.Index); |
| 55 | + |
| 56 | + foreach (var order in allOrders.Skip(1)) |
| 57 | + { |
| 58 | + foreach (var name in cannotBeParallel) |
| 59 | + { |
| 60 | + var index = nameToExpectedIndex[name]; |
| 61 | + var otherName = order[index]; |
| 62 | + if (otherName != name) |
| 63 | + { |
| 64 | + throw new ConfigurationErrorsException( |
| 65 | + $"The processor {name} could run in parallel with {otherName}. Processors must not run " + |
| 66 | + $"in parallel with any other validators."); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + public static List<List<string>> EnumerateAll(IReadOnlyList<ValidationConfigurationItem> validators) |
| 73 | + { |
| 74 | + // Build the graph. |
| 75 | + var graph = validators.ToDictionary(x => x.Name, x => new ValidatorNode(x.Name)); |
| 76 | + |
| 77 | + // Invert the node relationship. Validators specify what they depend on. Nodes in a directed graph to be |
| 78 | + // explored using topological sort should specify what their dependents are. |
| 79 | + foreach (var validator in validators) |
| 80 | + { |
| 81 | + foreach (var dependencyName in validator.RequiredValidations) |
| 82 | + { |
| 83 | + graph[validator.Name].InDegree++; |
| 84 | + graph[dependencyName].DependentValidations.Add(validator.Name); |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + // Enumerate all combindations. |
| 89 | + var allResults = new List<List<string>>(); |
| 90 | + AllTopologicalSort(graph, new List<string>(), allResults); |
| 91 | + |
| 92 | + return allResults; |
| 93 | + } |
| 94 | + |
| 95 | + /// <summary> |
| 96 | + /// Executes topological sort on the provided graph of validators. All possible results are enumerated and |
| 97 | + /// returned. |
| 98 | + /// </summary> |
| 99 | + /// <remarks> |
| 100 | + /// Source: https://www.geeksforgeeks.org/all-topological-sorts-of-a-directed-acyclic-graph/ |
| 101 | + /// </remarks> |
| 102 | + private static void AllTopologicalSort( |
| 103 | + IReadOnlyDictionary<string, ValidatorNode> graph, |
| 104 | + List<string> currentResult, |
| 105 | + List<List<string>> allResults) |
| 106 | + { |
| 107 | + var done = false; |
| 108 | + |
| 109 | + foreach (var node in graph.Values) |
| 110 | + { |
| 111 | + if (node.InDegree == 0 && !node.Visited) |
| 112 | + { |
| 113 | + foreach (var dependencyName in node.DependentValidations) |
| 114 | + { |
| 115 | + graph[dependencyName].InDegree--; |
| 116 | + } |
| 117 | + |
| 118 | + currentResult.Add(node.Name); |
| 119 | + node.Visited = true; |
| 120 | + |
| 121 | + // Recurse. |
| 122 | + AllTopologicalSort(graph, currentResult, allResults); |
| 123 | + |
| 124 | + node.Visited = false; |
| 125 | + currentResult.RemoveAt(currentResult.Count - 1); |
| 126 | + |
| 127 | + foreach (var dependencyName in node.DependentValidations) |
| 128 | + { |
| 129 | + graph[dependencyName].InDegree++; |
| 130 | + } |
| 131 | + |
| 132 | + done = true; |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + if (!done && currentResult.Count == graph.Count) |
| 137 | + { |
| 138 | + // Append a copy of the running result. |
| 139 | + allResults.Add(currentResult.ToList()); |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + private class ValidatorNode |
| 144 | + { |
| 145 | + public ValidatorNode(string name) |
| 146 | + { |
| 147 | + Name = name ?? throw new ArgumentNullException(nameof(name)); |
| 148 | + } |
| 149 | + |
| 150 | + public string Name { get; } |
| 151 | + public List<string> DependentValidations { get; } = new List<string>(); |
| 152 | + public int InDegree { get; set; } |
| 153 | + public bool Visited { get; set; } |
| 154 | + } |
| 155 | + } |
| 156 | +} |
0 commit comments