Tools:
DetonateFileIncriminationTool: Processes FileEntity (e.g., "lala.eml"), generates a screenshot, and produces an EmailEntity with the screenshot.
AnalyzeEmailScreenshotTool: Processes EmailEntity, requires a screenshot to classify as malicious/non-malicious, must wait for screenshot availability.
Constraints:
Tools run in parallel, but AnalyzeEmailScreenshotTool must wait for the screenshot without knowing about DetonateFileIncriminationTool.
No component (including orchestrator) should know specific tool requirements (e.g., screenshot dependency) beyond the entity itself.
Avoid dictionaries with magic strings (e.g., Metadata["Screenshot"]) for passing data like screenshots; prefer strongly-typed properties.
Goal: Design a system where:
Tools are fully decoupled, relying only on entities.
AnalyzeEmailScreenshotTool waits for the screenshot on EmailEntity without orchestrator involvement.
All tools execute in parallel, respecting dependencies implicitly via entity state.
Use EntityGraph to track entities and relationships.
Entities:
FileEntity, UrlEntity, EmailEntity (with Screenshot property for type-safe screenshot storage).
Deliverables:
Generic orchestrator to run tools in parallel based on entity types.
AnalyzeEmailScreenshotTool handles waiting for screenshot internally.
No magic strings; use strongly-typed Screenshot property on EmailEntity.
Assistant
Of course. This is an excellent problem that showcases modern asynchronous programming patterns in C# to achieve decoupled, parallel, and event-driven workflows. The key to solving this without "magic strings" and explicit orchestrator intervention is to embed the asynchronous waiting mechanism directly into the entity itself using a TaskCompletionSource.
Here is a complete, well-structured C# solution that meets all your requirements.
1. Core Concepts: The Entities
The entities are the data carriers. The EmailEntity is the most important one, as it will contain the logic for asynchronously providing the screenshot.
csharp
// --- Entities/BaseEntity.cs ---
public abstract class BaseEntity
{
public Guid Id { get; } = Guid.NewGuid();
public string Name { get; protected set; }
protected BaseEntity(string name)
{
Name = name;
}
}
// --- Entities/FileEntity.cs ---
public class FileEntity : BaseEntity
{
public FileEntity(string fileName) : base(fileName) { }
}
// --- Entities/UrlEntity.cs ---
public class UrlEntity : BaseEntity
{
public string Url { get; }
public UrlEntity(string url) : base(url)
{
Url = url;
}
}
// --- Entities/EmailEntity.cs ---
// This is the key component for decoupled waiting.
public class EmailEntity : BaseEntity
{
// A TaskCompletionSource is a promise of a future result.
// Tools can await its Task, and the producer can set the result when it's ready.
private readonly TaskCompletionSource<byte[]> _screenshotCompletionSource = new();
public string Subject { get; set; }
public EmailEntity(string name) : base(name) { }
/// <summary>
/// Property for the PRODUCER tool to set the screenshot data.
/// Setting this value completes the underlying Task, releasing any awaiters.
/// </summary>
public byte[] Screenshot
{
set
{
Console.WriteLine($"[Entity] Screenshot data received for Email '{Name}'. Notifying waiters.");
// This wakes up any code that is awaiting the GetScreenshotAsync() method.
_screenshotCompletionSource.TrySetResult(value);
}
}
/// <summary>
/// Method for the CONSUMER tool to asynchronously wait for the screenshot.
/// It returns a Task that completes only when the screenshot has been set.
/// </summary>
public Task<byte[]> GetScreenshotAsync()
{
return _screenshotCompletionSource.Task;
}
}
2. The EntityGraph
A simple, thread-safe container to hold all entities generated during the process.
csharp
// --- EntityGraph.cs ---
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
public class EntityGraph
{
private readonly ConcurrentDictionary<Guid, BaseEntity> _entities = new();
public void AddEntity(BaseEntity entity)
{
_entities.TryAdd(entity.Id, entity);
Console.WriteLine($"[Graph] Added {entity.GetType().Name}: {entity.Name}");
}
public IEnumerable<BaseEntity> GetAllEntities() => _entities.Values.ToList();
}
3. The Tools
Tools are decoupled and only know about the entity types they can process. The generic interface ITool<T> makes this strongly-typed.
csharp
// --- Tools/ITool.cs ---
// A generic interface for type-safe tool execution.
public interface ITool
{
string Name { get; }
// The orchestrator uses this to find out which entity type the tool processes.
Type ConsumesEntityType { get; }
Task ExecuteAsync(BaseEntity entity, EntityGraph graph);
}
// --- Tools/DetonateFileIncriminationTool.cs ---
public class DetonateFileIncriminationTool : ITool
{
public string Name => "File Detonator";
public Type ConsumesEntityType => typeof(FileEntity);
public async Task ExecuteAsync(BaseEntity entity, EntityGraph graph)
{
var fileEntity = (FileEntity)entity;
Console.WriteLine($"[{Name}] Starting detonation for '{fileEntity.Name}'...");
// 1. Simulate a long-running process (e.g., sandbox detonation)
await Task.Delay(2000);
// 2. Generate the screenshot and a new EmailEntity
var screenshotData = System.Text.Encoding.UTF8.GetBytes($"<SCREENSHOT_OF_{fileEntity.Name}>");
var emailEntity = new EmailEntity($"email_from_{fileEntity.Name}")
{
Subject = "Suspicious E-Mail Analysis"
};
Console.WriteLine($"[{Name}] Detonation complete for '{fileEntity.Name}'. Generated EmailEntity.");
// 3. Add the new entity to the graph for other tools to discover.
graph.AddEntity(emailEntity);
// 4. Set the screenshot property. This fulfills the "promise" in the EmailEntity.
// Any tool already awaiting this will now wake up and continue.
emailEntity.Screenshot = screenshotData;
}
}
// --- Tools/AnalyzeEmailScreenshotTool.cs ---
public class AnalyzeEmailScreenshotTool : ITool
{
public string Name => "Screenshot Analyzer";
public Type ConsumesEntityType => typeof(EmailEntity);
public async Task ExecuteAsync(BaseEntity entity, EntityGraph graph)
{
var emailEntity = (EmailEntity)entity;
Console.WriteLine($"[{Name}] Starting analysis for '{emailEntity.Name}'. Waiting for screenshot...");
// 1. Await the screenshot. This line will PAUSE execution of this tool
// instance until the screenshot is available on the entity.
// The tool doesn't know or care who provides it.
var screenshotData = await emailEntity.GetScreenshotAsync();
Console.WriteLine($"[{Name}] Screenshot received for '{emailEntity.Name}'. Resuming analysis.");
// 2. Simulate analysis work
await Task.Delay(1500);
string result = System.Text.Encoding.UTF8.GetString(screenshotData);
Console.WriteLine($"[{Name}] Analysis complete for '{emailEntity.Name}'. Result: MALICIOUS (based on '{result}')");
// This tool could also produce new entities (e.g., UrlEntity from email body)
// and add them to the graph, triggering further processing.
}
}
4. The Generic Orchestrator
The orchestrator's job is to run tools in parallel based on entity types without knowing any specific dependencies. It continues processing in rounds as long as new entities are created.
csharp
// --- Orchestrator.cs ---
public class Orchestrator
{
public async Task RunAsync(EntityGraph graph, IReadOnlyList<ITool> tools)
{
Console.WriteLine("[Orchestrator] Starting analysis workflow...");
var processedEntityIds = new HashSet<Guid>();
while (true)
{
// Find entities that haven't been processed yet
var newEntities = graph.GetAllEntities()
.Where(e => !processedEntityIds.Contains(e.Id))
.ToList();
if (!newEntities.Any())
{
Console.WriteLine("[Orchestrator] No new entities to process. Workflow complete.");
break;
}
Console.WriteLine($"[Orchestrator] Found {newEntities.Count} new entities to process in this round.");
var tasksInRound = new List<Task>();
foreach (var entity in newEntities)
{
// Mark as processed so we don't pick it up again in the next loop.
processedEntityIds.Add(entity.Id);
// Find all tools that can process this entity's type
var applicableTools = tools.Where(t => t.ConsumesEntityType.IsInstanceOfType(entity));
foreach (var tool in applicableTools)
{
Console.WriteLine($"[Orchestrator] Scheduling '{tool.Name}' for entity '{entity.Name}'.");
// Launch the tool's execution but don't wait for it here.
tasksInRound.Add(tool.ExecuteAsync(entity, graph));
}
}
// Await all tasks launched in this round to complete.
// This ensures we wait for all parallel work to finish before
// checking for newly generated entities in the next loop iteration.
await Task.WhenAll(tasksInRound);
Console.WriteLine("[Orchestrator] Finished processing round.");
}
}
}
5. Main Program to Run Everything
csharp
// --- Program.cs ---
class Program
{
static async Task Main(string[] args)
{
// 1. Setup initial state
var initialEntity = new FileEntity("lala.eml");
var graph = new EntityGraph();
graph.AddEntity(initialEntity);
// 2. Discover/register all available tools
var allTools = new List<ITool>
{
new DetonateFileIncriminationTool(),
new AnalyzeEmailScreenshotTool()
};
// 3. Create and run the orchestrator
var orchestrator = new Orchestrator();
await orchestrator.RunAsync(graph, allTools);
Console.WriteLine("\n--- Final State of Entity Graph ---");
foreach (var entity in graph.GetAllEntities())
{
Console.WriteLine($"- {entity.GetType().Name}: {entity.Name} (ID: {entity.Id})");
}
}
}
How to Run and Expected Output
Compile all these classes into a single C# project. When you run it, you will see output demonstrating the parallel and decoupled execution:
code
[Graph] Added FileEntity: lala.eml
[Orchestrator] Starting analysis workflow...
[Orchestrator] Found 1 new entities to process in this round.
[Orchestrator] Scheduling 'File Detonator' for entity 'lala.eml'.
[File Detonator] Starting detonation for 'lala.eml'...
[Orchestrator] Finished processing round.
[Orchestrator] Found 1 new entities to process in this round.
[Orchestrator] Scheduling 'Screenshot Analyzer' for entity 'email_from_lala.eml'.
[Screenshot Analyzer] Starting analysis for 'email_from_lala.eml'. Waiting for screenshot...
[File Detonator] Detonation complete for 'lala.eml'. Generated EmailEntity.
[Graph] Added EmailEntity: email_from_lala.eml
[Entity] Screenshot data received for Email 'email_from_lala.eml'. Notifying waiters.
[Screenshot Analyzer] Screenshot received for 'email_from_lala.eml'. Resuming analysis.
[Screenshot Analyzer] Analysis complete for 'email_from_lala.eml'. Result: MALICIOUS (based on '<SCREENSHOT_OF_lala.eml>')
[Orchestrator] Finished processing round.
[Orchestrator] No new entities to process. Workflow complete.
--- Final State of Entity Graph ---
- FileEntity: lala.eml (ID: ...)
- EmailEntity: email_from_lala.eml (ID: ...)
(Note: The exact order of console lines can vary slightly due to the nature of parallel execution, but the logical flow will be consistent.)
Summary of How Constraints Are Met:
Tools Fully Decoupled:AnalyzeEmailScreenshotTool only depends on the EmailEntity contract (GetScreenshotAsync), not on DetonateFileIncriminationTool.
Implicit Waiting:AnalyzeEmailScreenshotTool waits internally by awaiting the Task from emailEntity.GetScreenshotAsync(). The orchestrator is completely unaware of this waiting.
No Orchestrator Involvement in Dependencies: The orchestrator just matches tools to entity types and runs them. It has no special logic for screenshots.
No Magic Strings: The EmailEntity uses a strongly-typed Task<byte[]> via TaskCompletionSource to handle the screenshot data. There are no Metadata["Screenshot"] lookups.
Parallel Execution: The orchestrator launches all applicable tools for a given round using a "fire-and-forget" approach into a list of tasks and then uses Task.WhenAll to wait for that entire wave of work to complete. This ensures tools run concurrently while dependencies are implicitly managed by the entities themselves.