|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using LaunchDarkly.Sdk.Server.Ai.Config; |
| 5 | + |
| 6 | +namespace LaunchDarkly.Sdk.Server.Ai.Graph; |
| 7 | + |
| 8 | +/// <summary> |
| 9 | +/// Represents a fully-resolved agent graph returned by |
| 10 | +/// <see cref="LdAiClient.AgentGraph"/>. When <see cref="Enabled"/> is false, all |
| 11 | +/// node collections are empty and traversal is a no-op; only <see cref="GetConfig"/> |
| 12 | +/// and <see cref="CreateTracker"/> remain meaningful. |
| 13 | +/// </summary> |
| 14 | +public sealed class AgentGraphDefinition |
| 15 | +{ |
| 16 | + private readonly AgentGraphFlagValue _flagValue; |
| 17 | + private readonly IReadOnlyDictionary<string, AgentGraphNode> _nodes; |
| 18 | + private readonly Func<AiGraphTracker> _createTracker; |
| 19 | + |
| 20 | + /// <summary> |
| 21 | + /// Whether the graph passed all validation checks. False if the flag's |
| 22 | + /// <c>_ldMeta.enabled</c> is false, the root is missing, any node is |
| 23 | + /// unreachable from the root, or any child agent config could not be fetched. |
| 24 | + /// </summary> |
| 25 | + public bool Enabled { get; } |
| 26 | + |
| 27 | + internal AgentGraphDefinition( |
| 28 | + AgentGraphFlagValue flagValue, |
| 29 | + IReadOnlyDictionary<string, AgentGraphNode> nodes, |
| 30 | + bool enabled, |
| 31 | + Func<AiGraphTracker> createTracker) |
| 32 | + { |
| 33 | + _flagValue = flagValue; |
| 34 | + _nodes = nodes; |
| 35 | + Enabled = enabled; |
| 36 | + _createTracker = createTracker; |
| 37 | + } |
| 38 | + |
| 39 | + /// <summary> |
| 40 | + /// Returns the root node of the graph, or null if the graph is disabled or has no root. |
| 41 | + /// </summary> |
| 42 | + public AgentGraphNode RootNode() => |
| 43 | + string.IsNullOrEmpty(_flagValue?.Root) ? null : GetNode(_flagValue.Root); |
| 44 | + |
| 45 | + /// <summary> |
| 46 | + /// Returns the node with the given key, or null if not found. |
| 47 | + /// </summary> |
| 48 | + public AgentGraphNode GetNode(string nodeKey) |
| 49 | + { |
| 50 | + if (nodeKey == null) return null; |
| 51 | + return _nodes.TryGetValue(nodeKey, out var node) ? node : null; |
| 52 | + } |
| 53 | + |
| 54 | + /// <summary> |
| 55 | + /// Returns the direct children of the given node by following its outgoing edges. |
| 56 | + /// Returns an empty list if the node is not found. |
| 57 | + /// </summary> |
| 58 | + public IReadOnlyList<AgentGraphNode> GetChildNodes(string nodeKey) |
| 59 | + { |
| 60 | + var node = GetNode(nodeKey); |
| 61 | + if (node == null) return Array.Empty<AgentGraphNode>(); |
| 62 | + |
| 63 | + return node.Edges |
| 64 | + .Select(edge => GetNode(edge.Key)) |
| 65 | + .Where(n => n != null) |
| 66 | + .ToList(); |
| 67 | + } |
| 68 | + |
| 69 | + /// <summary> |
| 70 | + /// Returns all nodes that have an outgoing edge pointing to the given node key. |
| 71 | + /// </summary> |
| 72 | + public IReadOnlyList<AgentGraphNode> GetParentNodes(string nodeKey) |
| 73 | + { |
| 74 | + return _nodes.Values |
| 75 | + .Where(node => node.Edges.Any(edge => edge.Key == nodeKey)) |
| 76 | + .ToList(); |
| 77 | + } |
| 78 | + |
| 79 | + /// <summary> |
| 80 | + /// Returns all nodes with no outgoing edges (leaf nodes). |
| 81 | + /// </summary> |
| 82 | + public IReadOnlyList<AgentGraphNode> TerminalNodes() => |
| 83 | + _nodes.Values.Where(n => n.IsTerminal).ToList(); |
| 84 | + |
| 85 | + /// <summary> |
| 86 | + /// Returns the raw flag value including LaunchDarkly metadata. Always non-null, |
| 87 | + /// even when <see cref="Enabled"/> is false. |
| 88 | + /// </summary> |
| 89 | + public AgentGraphFlagValue GetConfig() => _flagValue; |
| 90 | + |
| 91 | + /// <summary> |
| 92 | + /// Creates a new graph-level tracker for this invocation. |
| 93 | + /// </summary> |
| 94 | + public AiGraphTracker CreateTracker() => _createTracker(); |
| 95 | + |
| 96 | + /// <summary> |
| 97 | + /// Performs a breadth-first traversal of the graph starting from the root node. |
| 98 | + /// For each visited node, <paramref name="fn"/> is called with the node and the |
| 99 | + /// accumulated context dictionary. The return value of <paramref name="fn"/> is |
| 100 | + /// stored in the context under the node's key and passed to subsequent calls. |
| 101 | + /// Cycle-safe: each node is visited at most once. |
| 102 | + /// </summary> |
| 103 | + public void Traverse( |
| 104 | + Func<AgentGraphNode, Dictionary<string, object>, object> fn, |
| 105 | + Dictionary<string, object> initialContext = null) |
| 106 | + { |
| 107 | + var root = RootNode(); |
| 108 | + if (root == null) return; |
| 109 | + |
| 110 | + var context = initialContext ?? new Dictionary<string, object>(); |
| 111 | + |
| 112 | + var visited = new HashSet<string>(); |
| 113 | + var queue = new Queue<AgentGraphNode>(); |
| 114 | + queue.Enqueue(root); |
| 115 | + visited.Add(root.Key); |
| 116 | + |
| 117 | + while (queue.Count > 0) |
| 118 | + { |
| 119 | + var node = queue.Dequeue(); |
| 120 | + var result = fn(node, context); |
| 121 | + context[node.Key] = result; |
| 122 | + |
| 123 | + foreach (var child in GetChildNodes(node.Key)) |
| 124 | + { |
| 125 | + if (visited.Add(child.Key)) |
| 126 | + { |
| 127 | + queue.Enqueue(child); |
| 128 | + } |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + /// <summary> |
| 134 | + /// Performs a reverse breadth-first traversal: starts from terminal nodes and |
| 135 | + /// works upward toward the root. The root node is always processed last. |
| 136 | + /// Cycle-safe: each node is visited at most once. |
| 137 | + /// </summary> |
| 138 | + public void ReverseTraverse( |
| 139 | + Func<AgentGraphNode, Dictionary<string, object>, object> fn, |
| 140 | + Dictionary<string, object> initialContext = null) |
| 141 | + { |
| 142 | + if (_nodes.Count == 0) return; |
| 143 | + |
| 144 | + var context = initialContext ?? new Dictionary<string, object>(); |
| 145 | + |
| 146 | + var root = RootNode(); |
| 147 | + var visited = new HashSet<string>(); |
| 148 | + var queue = new Queue<AgentGraphNode>(); |
| 149 | + |
| 150 | + // Seed with terminal nodes (excluding root if it happens to be terminal and there are others) |
| 151 | + foreach (var terminal in TerminalNodes()) |
| 152 | + { |
| 153 | + if (root != null && terminal.Key == root.Key && _nodes.Count > 1) |
| 154 | + { |
| 155 | + continue; |
| 156 | + } |
| 157 | + if (visited.Add(terminal.Key)) |
| 158 | + { |
| 159 | + queue.Enqueue(terminal); |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + while (queue.Count > 0) |
| 164 | + { |
| 165 | + var node = queue.Dequeue(); |
| 166 | + |
| 167 | + // Defer root until the very end (unless it's the only node) |
| 168 | + if (root != null && node.Key == root.Key && _nodes.Count > 1) |
| 169 | + { |
| 170 | + continue; |
| 171 | + } |
| 172 | + |
| 173 | + var result = fn(node, context); |
| 174 | + context[node.Key] = result; |
| 175 | + |
| 176 | + foreach (var parent in GetParentNodes(node.Key)) |
| 177 | + { |
| 178 | + if (root != null && parent.Key == root.Key) |
| 179 | + { |
| 180 | + // Don't enqueue root yet — process it last |
| 181 | + continue; |
| 182 | + } |
| 183 | + if (visited.Add(parent.Key)) |
| 184 | + { |
| 185 | + queue.Enqueue(parent); |
| 186 | + } |
| 187 | + } |
| 188 | + } |
| 189 | + |
| 190 | + // Process root last |
| 191 | + if (root != null && _nodes.Count > 1 && visited.Count > 0) |
| 192 | + { |
| 193 | + var result = fn(root, context); |
| 194 | + context[root.Key] = result; |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + /// <summary> |
| 199 | + /// Builds the nodes dictionary from a parsed flag value and a map of pre-fetched |
| 200 | + /// agent configs, associating each node with its outgoing edges from the flag value. |
| 201 | + /// </summary> |
| 202 | + internal static IReadOnlyDictionary<string, AgentGraphNode> BuildNodes( |
| 203 | + AgentGraphFlagValue flagValue, |
| 204 | + IReadOnlyDictionary<string, LdAiAgentConfig> agentConfigs) |
| 205 | + { |
| 206 | + var nodes = new Dictionary<string, AgentGraphNode>(); |
| 207 | + var allKeys = CollectAllKeys(flagValue); |
| 208 | + |
| 209 | + foreach (var key in allKeys) |
| 210 | + { |
| 211 | + if (!agentConfigs.TryGetValue(key, out var config)) |
| 212 | + continue; |
| 213 | + |
| 214 | + var outgoingEdges = flagValue.Edges != null && flagValue.Edges.TryGetValue(key, out var edges) |
| 215 | + ? edges |
| 216 | + : (IReadOnlyList<GraphEdge>)Array.Empty<GraphEdge>(); |
| 217 | + |
| 218 | + nodes[key] = new AgentGraphNode(key, config, outgoingEdges); |
| 219 | + } |
| 220 | + |
| 221 | + return nodes; |
| 222 | + } |
| 223 | + |
| 224 | + /// <summary> |
| 225 | + /// Collects all unique node keys referenced in the flag value: the root, all |
| 226 | + /// edge source keys, and all edge target keys. |
| 227 | + /// </summary> |
| 228 | + internal static HashSet<string> CollectAllKeys(AgentGraphFlagValue flagValue) |
| 229 | + { |
| 230 | + var keys = new HashSet<string>(); |
| 231 | + |
| 232 | + if (!string.IsNullOrEmpty(flagValue?.Root)) |
| 233 | + { |
| 234 | + keys.Add(flagValue.Root); |
| 235 | + } |
| 236 | + |
| 237 | + if (flagValue?.Edges != null) |
| 238 | + { |
| 239 | + foreach (var kv in flagValue.Edges) |
| 240 | + { |
| 241 | + keys.Add(kv.Key); |
| 242 | + foreach (var edge in kv.Value) |
| 243 | + { |
| 244 | + keys.Add(edge.Key); |
| 245 | + } |
| 246 | + } |
| 247 | + } |
| 248 | + |
| 249 | + return keys; |
| 250 | + } |
| 251 | +} |
0 commit comments