-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProject.cs
More file actions
911 lines (742 loc) · 28.3 KB
/
Copy pathProject.cs
File metadata and controls
911 lines (742 loc) · 28.3 KB
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
using NodeDev.Core.Class;
using NodeDev.Core.Connections;
using NodeDev.Core.Debugger;
using NodeDev.Core.Migrations;
using NodeDev.Core.Nodes;
using NodeDev.Core.Types;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("NodeDev.Tests")]
namespace NodeDev.Core;
public class Project
{
/// <summary>
/// Maximum time to wait for process output streams to be fully consumed after process exits.
/// </summary>
private static readonly TimeSpan OutputStreamTimeout = TimeSpan.FromSeconds(5);
internal record class SerializedProject(Guid Id, string NodeDevVersion, List<NodeClass.SerializedNodeClass> Classes, ProjectSettings Settings);
internal readonly Guid Id;
internal readonly string NodeDevVersion;
public static string CurrentNodeDevVersion => Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? throw new Exception("Unable to get current NodeDev version");
private readonly List<NodeClass> _Classes = [];
public IReadOnlyList<NodeClass> Classes => _Classes;
private readonly Dictionary<NodeClass, NodeClassType> NodeClassTypes = [];
public readonly TypeFactory TypeFactory;
public ProjectSettings Settings { get; private set; } = ProjectSettings.Default;
public NodeClassTypeCreator? NodeClassTypeCreator { get; private set; }
public GraphExecutor? GraphExecutor { get; set; }
internal Subject<(Graph Graph, bool RequireUIRefresh)> GraphChangedSubject { get; } = new();
internal Subject<(GraphExecutor Executor, Node Node, Connection Exec)> GraphNodeExecutingSubject { get; } = new();
internal Subject<(GraphExecutor Executor, Node Node, Connection Exec)> GraphNodeExecutedSubject { get; } = new();
internal Subject<bool> GraphExecutionChangedSubject { get; } = new();
internal Subject<string> ConsoleOutputSubject { get; } = new();
internal Subject<DebugCallbackEventArgs> DebugCallbackSubject { get; } = new();
internal Subject<bool> HardDebugStateChangedSubject { get; } = new();
internal Subject<NodeBreakpointInfo?> CurrentBreakpointSubject { get; } = new();
public IObservable<(Graph Graph, bool RequireUIRefresh)> GraphChanged => GraphChangedSubject.AsObservable();
public IObservable<(GraphExecutor Executor, Node Node, Connection Exec)> GraphNodeExecuting => GraphNodeExecutingSubject.AsObservable();
public IObservable<(GraphExecutor Executor, Node Node, Connection Exec)> GraphNodeExecuted => GraphNodeExecutedSubject.AsObservable();
public IObservable<bool> GraphExecutionChanged => GraphExecutionChangedSubject.AsObservable();
public IObservable<string> ConsoleOutput => ConsoleOutputSubject.AsObservable();
public IObservable<DebugCallbackEventArgs> DebugCallbacks => DebugCallbackSubject.AsObservable();
public IObservable<bool> HardDebugStateChanged => HardDebugStateChangedSubject.AsObservable();
public IObservable<NodeBreakpointInfo?> CurrentBreakpointChanged => CurrentBreakpointSubject.AsObservable();
public bool IsLiveDebuggingEnabled { get; private set; }
private DebugSessionEngine? _debugEngine;
private System.Diagnostics.Process? _debuggedProcess;
private NodeDev.Core.Debugger.BreakpointMappingInfo? _currentBreakpointMappings;
private NodeBreakpointInfo? _currentBreakpoint;
/// <summary>
/// Gets whether the project is currently being debugged with hard debugging (ICorDebug).
/// </summary>
public bool IsHardDebugging => _debugEngine?.IsAttached ?? false;
/// <summary>
/// Gets the process ID of the currently debugged process, or null if not debugging.
/// </summary>
public int? DebuggedProcessId => _debuggedProcess?.Id;
/// <summary>
/// Gets the current breakpoint that execution is paused at, or null if not paused at a breakpoint.
/// </summary>
public NodeBreakpointInfo? CurrentBreakpoint => _currentBreakpoint;
/// <summary>
/// Gets whether execution is currently paused at a breakpoint.
/// </summary>
public bool IsPausedAtBreakpoint => _currentBreakpoint != null;
public Project(Guid id, string? nodeDevVersion = null)
{
Id = id;
NodeDevVersion = nodeDevVersion ?? CurrentNodeDevVersion;
TypeFactory = new TypeFactory(this);
}
public IEnumerable<T> GetNodes<T>() where T : Node
{
return Classes.SelectMany(x => x.Methods).SelectMany(x => x.Graph.Nodes.Values).OfType<T>();
}
#region CreateNewDefaultProject
public static Project CreateNewDefaultProject()
{
return CreateNewDefaultProject(out _);
}
public static Project CreateNewDefaultProject(out NodeClassMethod main)
{
var project = new Project(Guid.NewGuid());
var programClass = new NodeClass("Program", "NewProject", project);
project.AddClass(programClass);
// Create the main method and add it to the project
main = new NodeClassMethod(programClass, "Main", project.TypeFactory.Get<int>(), true);
programClass.AddMethod(main, createEntryAndReturn: true);
// Now that the method is created with its entry and return nodes, we can set the default return value of 0
main.ReturnNodes.First().Inputs[1].UpdateTextboxText("0");
return project;
}
#endregion
#region AddClass
public void AddClass(NodeClass nodeClass)
{
_Classes.Add(nodeClass);
}
#endregion
#region Build
public string Build(BuildOptions buildOptions)
{
// Use unique name based on project ID to avoid conflicts when running tests in parallel
// Using "N" format avoids hyphens and is more efficient than Replace
var name = $"project_{Id:N}";
// Use Roslyn compilation
var compiler = new RoslynNodeClassCompiler(this, buildOptions);
var result = compiler.Compile();
// Store breakpoint mappings for debugger use
_currentBreakpointMappings = result.BreakpointMappings;
// Check if this is an executable (has a Program.Main method)
bool isExecutable = HasMainMethod();
Directory.CreateDirectory(buildOptions.OutputPath);
var fileExtension = isExecutable ? ".exe" : ".dll";
var filePath = Path.Combine(buildOptions.OutputPath, $"{name}{fileExtension}");
var pdbPath = Path.Combine(buildOptions.OutputPath, $"{name}.pdb");
// Write the PE and PDB to files
File.WriteAllBytes(filePath, result.PEBytes);
File.WriteAllBytes(pdbPath, result.PDBBytes);
// Read IL offsets from PDB for breakpoints
if (_currentBreakpointMappings != null && _currentBreakpointMappings.Breakpoints.Count > 0)
{
try
{
// For each unique class/method combination, read IL offsets
var methodGroups = _currentBreakpointMappings.Breakpoints
.GroupBy(bp => (bp.ClassName, bp.MethodName));
foreach (var group in methodGroups)
{
var offsets = Debugger.PdbSequencePointReader.ReadILOffsetsForVirtualLines(
filePath,
group.Key.ClassName,
group.Key.MethodName,
group.ToList()
);
// Update breakpoint info with IL offsets
foreach (var bp in group)
{
var key = $"{bp.SourceFile}:{bp.LineNumber}";
if (offsets.TryGetValue(key, out var offset))
{
bp.ILOffset = offset;
}
}
}
}
catch (Exception ex)
{
// Log error but don't fail the build
Console.WriteLine($"Warning: Failed to read IL offsets from PDB: {ex.Message}");
}
}
if (isExecutable)
{
// Create runtime config for executables
File.WriteAllText(Path.Combine(buildOptions.OutputPath, $"{name}.runtimeconfig.json"), @$"{{
""runtimeOptions"": {{
""tfm"": ""net{Environment.Version.Major}.{Environment.Version.Minor}"",
""framework"": {{
""name"": ""Microsoft.NETCore.App"",
""version"": ""{GetNetCoreVersion()}""
}}
}}
}}");
}
return filePath;
}
/// <summary>
/// Checks if the project has a static Main method in a Program class (indicating an executable)
/// </summary>
internal bool HasMainMethod()
{
var program = Classes.FirstOrDefault(x => x.Name == "Program");
var mainMethod = program?.Methods.FirstOrDefault(x => x.Name == "Main" && x.IsStatic);
return program != null && mainMethod != null;
}
private static string GetNetCoreVersion()
{
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.Location.Split(['/', '\\'], StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];
return "";
}
public AssemblyBuilder BuildAndGetAssembly(BuildOptions buildOptions)
{
CreateNodeClassTypeCreator(buildOptions);
if (NodeClassTypeCreator == null)
throw new NullReferenceException($"NodeClassTypeCreator should not be null after {nameof(CreateNodeClassTypeCreator)} was called, this shouldn't happen");
NodeClassTypeCreator.CreateProjectClassesAndAssembly();
var assembly = NodeClassTypeCreator.Assembly;
if (assembly == null)
throw new NullReferenceException("NodeClassTypeCreator.Assembly null after project was compiled, this shouldn't happen");
return assembly;
}
/// <summary>
/// Builds the project using Roslyn compilation (new approach)
/// </summary>
public Assembly BuildWithRoslyn(BuildOptions buildOptions)
{
var compiler = new RoslynNodeClassCompiler(this, buildOptions);
var result = compiler.Compile();
return result.Assembly;
}
/// <summary>
/// Gets the generated C# source code for a specific method by building it on-the-fly.
/// Uses the RoslynGraphBuilder to generate the method syntax directly.
/// </summary>
public string? GetGeneratedCSharpCode(NodeClassMethod method)
{
try
{
// Build the method syntax using RoslynGraphBuilder
var builder = new CodeGeneration.RoslynGraphBuilder(method.Graph, isDebug: true);
var methodSyntax = builder.BuildMethod();
// Convert the syntax node to a normalized string
return methodSyntax.NormalizeWhitespace().ToFullString();
}
catch (Exception)
{
return null;
}
}
#endregion
#region Run
/// <summary>
/// Locates the ScriptRunner executable in the build output directory.
/// ScriptRunner is a console application that serves as the target process for debugging.
/// </summary>
private static string FindScriptRunnerExecutable()
{
// Get the directory where NodeDev.Core assembly is located
string coreAssemblyLocation = Assembly.GetExecutingAssembly().Location;
string coreDirectory = Path.GetDirectoryName(coreAssemblyLocation) ?? throw new Exception("Unable to determine NodeDev.Core assembly directory");
// ScriptRunner should be in the same build output directory
string scriptRunnerDll = Path.Combine(coreDirectory, "NodeDev.ScriptRunner.dll");
if (File.Exists(scriptRunnerDll))
{
return scriptRunnerDll;
}
// If not found in the same directory, try looking in sibling directories (for development scenarios)
string? buildOutputRoot = Path.GetDirectoryName(coreDirectory);
if (buildOutputRoot != null)
{
string scriptRunnerPath = Path.Combine(buildOutputRoot, "NodeDev.ScriptRunner", "NodeDev.ScriptRunner.dll");
if (File.Exists(scriptRunnerPath))
{
return scriptRunnerPath;
}
}
throw new FileNotFoundException("ScriptRunner executable not found. Please ensure NodeDev.ScriptRunner is built and available.");
}
/// <summary>
/// Gets the path to the ScriptRunner executable.
/// This is useful for debugging infrastructure that needs to locate the runner.
/// </summary>
/// <returns>The full path to NodeDev.ScriptRunner.dll</returns>
public string GetScriptRunnerPath()
{
return FindScriptRunnerExecutable();
}
public object? Run(BuildOptions options, params object?[] inputs)
{
try
{
var assemblyPath = Build(options);
// Find the ScriptRunner executable
string scriptRunnerPath = FindScriptRunnerExecutable();
// Convert to absolute path to avoid confusion with working directory
string absoluteAssemblyPath = Path.GetFullPath(assemblyPath);
// Build arguments: ScriptRunner.dll path-to-user-dll [user-args...]
var userArgsString = string.Join(" ", inputs.Select(x => '"' + (x?.ToString() ?? "") + '"'));
var arguments = $"\"{scriptRunnerPath}\" \"{absoluteAssemblyPath}\"";
if (!string.IsNullOrEmpty(userArgsString))
{
arguments += $" {userArgsString}";
}
var processStartInfo = new System.Diagnostics.ProcessStartInfo()
{
FileName = "dotnet",
Arguments = arguments,
WorkingDirectory = Path.GetDirectoryName(absoluteAssemblyPath),
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
var process = System.Diagnostics.Process.Start(processStartInfo) ?? throw new Exception("Unable to start process");
// Use ManualResetEvents to track when async output handlers complete
// Using 'using' ensures proper disposal of unmanaged resources
using var outputComplete = new System.Threading.ManualResetEvent(false);
using var errorComplete = new System.Threading.ManualResetEvent(false);
// Notify that execution has started
GraphExecutionChangedSubject.OnNext(true);
// Capture output and error streams
// The null event signals end of stream
process.OutputDataReceived += (sender, e) =>
{
if (e.Data != null)
{
ConsoleOutputSubject.OnNext(e.Data + Environment.NewLine);
}
else
{
// End of stream
outputComplete.Set();
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data != null)
{
ConsoleOutputSubject.OnNext(e.Data + Environment.NewLine);
}
else
{
// End of stream
errorComplete.Set();
}
};
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
// Wait for output streams to be fully consumed (with timeout)
outputComplete.WaitOne(OutputStreamTimeout);
errorComplete.WaitOne(OutputStreamTimeout);
// Notify that execution has completed
GraphExecutionChangedSubject.OnNext(false);
return process.ExitCode;
}
catch (Exception)
{
// Notify that execution has completed even on error
GraphExecutionChangedSubject.OnNext(false);
return null;
}
finally
{
NodeClassTypeCreator = null;
GC.Collect();
}
}
/// <summary>
/// Runs the project with hard debugging (ICorDebug) attached.
/// </summary>
/// <param name="options">Build options to use.</param>
/// <param name="inputs">Input parameters for the main method.</param>
/// <returns>The exit code of the process, or null if execution failed.</returns>
public object? RunWithDebug(BuildOptions options, params object?[] inputs)
{
try
{
var assemblyPath = Build(options);
// Find the ScriptRunner executable
string scriptRunnerPath = FindScriptRunnerExecutable();
// Convert to absolute path to avoid confusion with working directory
string absoluteAssemblyPath = Path.GetFullPath(assemblyPath);
// Build arguments: ScriptRunner.dll --wait-for-debugger path-to-user-dll [user-args...]
var userArgsString = string.Join(" ", inputs.Select(x => '"' + (x?.ToString() ?? "") + '"'));
var arguments = $"\"{scriptRunnerPath}\" --wait-for-debugger \"{absoluteAssemblyPath}\"";
if (!string.IsNullOrEmpty(userArgsString))
{
arguments += $" {userArgsString}";
}
var processStartInfo = new System.Diagnostics.ProcessStartInfo()
{
FileName = "dotnet",
Arguments = arguments,
WorkingDirectory = Path.GetDirectoryName(absoluteAssemblyPath),
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
var process = System.Diagnostics.Process.Start(processStartInfo) ?? throw new Exception("Unable to start process");
_debuggedProcess = process;
// Use ManualResetEvents to track when async output handlers complete
using var outputComplete = new System.Threading.ManualResetEvent(false);
using var errorComplete = new System.Threading.ManualResetEvent(false);
// Notify that execution has started
GraphExecutionChangedSubject.OnNext(true);
// Capture output and error streams
process.OutputDataReceived += (sender, e) =>
{
if (e.Data != null)
{
ConsoleOutputSubject.OnNext(e.Data + Environment.NewLine);
}
else
{
outputComplete.Set();
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data != null)
{
ConsoleOutputSubject.OnNext(e.Data + Environment.NewLine);
}
else
{
errorComplete.Set();
}
};
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// Initialize debug engine
var shimPath = DbgShimResolver.TryResolve();
if (shimPath == null)
{
// Kill the process since we can't attach debugger
try { process.Kill(); } catch { }
throw new InvalidOperationException(
"DbgShim library not found. Debugging features are not available on this system.\n\n" +
"The DbgShim library is required for debugging and should be installed automatically via the Microsoft.Diagnostics.DbgShim NuGet package.\n" +
"Please ensure NuGet packages are properly restored.");
}
_debugEngine = new DebugSessionEngine(shimPath);
try
{
_debugEngine.Initialize();
// Set breakpoint mappings from the build
_debugEngine.SetBreakpointMappings(_currentBreakpointMappings);
// Set the delegate to check if a node should have a breakpoint
// This allows filtering breakpoints based on current node state
_debugEngine.ShouldSetBreakpointForNode = (nodeId) =>
{
var node = FindNodeById(nodeId);
return node?.HasBreakpoint ?? false;
};
}
catch (Exception ex)
{
// Kill the process since we can't attach debugger
try { process.Kill(); } catch { }
throw new InvalidOperationException($"Failed to initialize debug engine: {ex.Message}", ex);
}
// Subscribe to debug callbacks
_debugEngine.DebugCallback += (sender, args) =>
{
DebugCallbackSubject.OnNext(args);
};
// Subscribe to breakpoint hits
_debugEngine.BreakpointHit += (sender, bpInfo) =>
{
_currentBreakpoint = bpInfo;
CurrentBreakpointSubject.OnNext(bpInfo);
ConsoleOutputSubject.OnNext($"Breakpoint hit: {bpInfo.NodeName} in {bpInfo.ClassName}.{bpInfo.MethodName}" + Environment.NewLine);
};
// Use the process ID directly
int targetPid = process.Id;
// Wait for CLR to load with polling
const int maxAttempts = 20;
const int pollIntervalMs = 200;
string[]? clrs = null;
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
System.Threading.Thread.Sleep(pollIntervalMs);
try
{
clrs = _debugEngine.EnumerateCLRs(targetPid);
if (clrs.Length > 0) break;
}
catch (DebugEngineException)
{
// CLR not ready yet, keep trying
}
catch (Exception)
{
// Process may have exited
if (process.HasExited)
break;
}
}
if (clrs == null || clrs.Length == 0)
{
// Kill the process since we can't attach debugger
try { process.Kill(); } catch { }
string errorMsg = process.HasExited
? $"Target process exited unexpectedly (exit code: {process.ExitCode}) before CLR could be enumerated.\n\n" +
"The process may have crashed or completed too quickly for the debugger to attach."
: "Could not enumerate CLRs in the target process after multiple attempts.\n\n" +
"The CLR runtime may not have loaded, or the process may not be a valid .NET application.";
throw new InvalidOperationException(errorMsg);
}
// Attach debugger
try
{
var corDebug = _debugEngine.AttachToProcess(targetPid);
var debugProcess = _debugEngine.SetupDebugging(corDebug, targetPid);
// Notify that we're now debugging
HardDebugStateChangedSubject.OnNext(true);
ConsoleOutputSubject.OnNext("Debugger attached successfully." + Environment.NewLine);
}
catch (Exception ex) when (ex is not InvalidOperationException)
{
// Kill the process since we can't attach debugger
try { process.Kill(); } catch { }
throw new InvalidOperationException($"Failed to attach debugger to process: {ex.Message}", ex);
}
// Wait for the process to complete
process.WaitForExit();
// Wait for output streams to be fully consumed
outputComplete.WaitOne(OutputStreamTimeout);
errorComplete.WaitOne(OutputStreamTimeout);
// Detach debugger before notifying UI - this clears CurrentProcess
// so that IsHardDebugging returns false when UI re-evaluates state
_debugEngine?.Detach();
// Notify that debugging has stopped
HardDebugStateChangedSubject.OnNext(false);
GraphExecutionChangedSubject.OnNext(false);
return process.ExitCode;
}
catch (Exception ex)
{
ConsoleOutputSubject.OnNext($"Error during debug execution: {ex.Message}" + Environment.NewLine);
// Detach debugger before notifying UI - this clears CurrentProcess
// so that IsHardDebugging returns false when UI re-evaluates state
_debugEngine?.Detach();
HardDebugStateChangedSubject.OnNext(false);
GraphExecutionChangedSubject.OnNext(false);
return null;
}
finally
{
_debugEngine?.Dispose();
_debugEngine = null;
_debuggedProcess = null;
NodeClassTypeCreator = null;
GC.Collect();
}
}
/// <summary>
/// Stops the current debugging session by detaching the debugger and terminating the process.
/// </summary>
public void StopDebugging()
{
if (!IsHardDebugging)
return;
try
{
// Detach debugger first
_debugEngine?.Detach();
// Try to kill the process if it's still running
if (_debuggedProcess != null && !_debuggedProcess.HasExited)
{
try
{
_debuggedProcess.Kill();
_debuggedProcess.WaitForExit(5000); // Wait up to 5 seconds
}
catch
{
// Ignore errors if process is already gone
}
}
// Notify that debugging has stopped
HardDebugStateChangedSubject.OnNext(false);
GraphExecutionChangedSubject.OnNext(false);
ConsoleOutputSubject.OnNext("Debugging stopped by user." + Environment.NewLine);
}
finally
{
_debugEngine?.Dispose();
_debugEngine = null;
_debuggedProcess = null;
}
}
/// <summary>
/// Continues execution after a breakpoint or other pause event.
/// Only available when hard debugging is active and execution is paused.
/// </summary>
public void ContinueExecution()
{
if (!IsHardDebugging)
throw new InvalidOperationException("Cannot continue execution when not debugging.");
try
{
// Clear current breakpoint before continuing
_currentBreakpoint = null;
CurrentBreakpointSubject.OnNext(null);
_debugEngine?.Continue();
}
catch (Exception ex)
{
ConsoleOutputSubject.OnNext($"Failed to continue execution: {ex.Message}" + Environment.NewLine);
throw;
}
}
/// <summary>
/// Dynamically sets a breakpoint on a specific node during an active debug session.
/// This allows adding breakpoints after the process has started.
/// </summary>
/// <param name="nodeId">The ID of the node to set a breakpoint on.</param>
/// <returns>True if the breakpoint was set successfully, false otherwise.</returns>
public bool SetBreakpointForNode(string nodeId)
{
if (!IsHardDebugging)
throw new InvalidOperationException("Cannot set breakpoints when not debugging.");
if (_debugEngine == null)
return false;
// Find the node and ensure it has a breakpoint decoration
var node = FindNodeById(nodeId);
if (node == null)
return false;
// Set the breakpoint decoration if not already set
if (!node.HasBreakpoint)
node.ToggleBreakpoint();
// Tell the debug engine to set the breakpoint
return _debugEngine.SetBreakpointForNode(nodeId);
}
/// <summary>
/// Dynamically removes a breakpoint from a specific node during an active debug session.
/// </summary>
/// <param name="nodeId">The ID of the node to remove the breakpoint from.</param>
/// <returns>True if the breakpoint was removed successfully, false if it wasn't set.</returns>
public bool RemoveBreakpointForNode(string nodeId)
{
if (!IsHardDebugging)
throw new InvalidOperationException("Cannot remove breakpoints when not debugging.");
if (_debugEngine == null)
return false;
// Find the node and remove the breakpoint decoration
var node = FindNodeById(nodeId);
if (node != null && node.HasBreakpoint)
node.ToggleBreakpoint();
// Tell the debug engine to remove the breakpoint
return _debugEngine.RemoveBreakpointForNode(nodeId);
}
/// <summary>
/// Finds a node by its ID across all classes in the project.
/// </summary>
/// <param name="nodeId">The ID of the node to find.</param>
/// <returns>The node if found, null otherwise.</returns>
private Node? FindNodeById(string nodeId)
{
foreach (var nodeClass in Classes)
{
// Check methods
foreach (var method in nodeClass.Methods)
{
if (method.Graph?.Nodes.TryGetValue(nodeId, out var node) == true)
return node;
}
}
return null;
}
#endregion
#region GetCreatedClassType / GetNodeClassType
public NodeClassTypeCreator CreateNodeClassTypeCreator(BuildOptions options)
{
return NodeClassTypeCreator = new(this, options);
}
public Type GetCreatedClassType(NodeClass nodeClass)
{
if (NodeClassTypeCreator == null)
throw new Exception("NodeClassTypeCreator is null, is the project currently being run?");
if (NodeClassTypeCreator.GeneratedTypes.TryGetValue(GetNodeClassType(nodeClass), out var generatedType))
return generatedType.Type;
throw new Exception("Unable to get generated node class for provided class: " + nodeClass.Name);
}
public NodeClassType GetNodeClassType(NodeClass nodeClass, TypeBase[]? generics = null)
{
if (!NodeClassTypes.ContainsKey(nodeClass))
return NodeClassTypes[nodeClass] = new(nodeClass, generics ?? Array.Empty<TypeBase>());
return NodeClassTypes[nodeClass];
}
#endregion
#region Serialize / Deserialize
public string Serialize()
{
var serializedProject = new SerializedProject(Id, NodeDevVersion, Classes.Select(x => x.Serialize()).ToList(), Settings);
return JsonSerializer.Serialize(serializedProject, new JsonSerializerOptions()
{
WriteIndented = true
});
}
public static Project Deserialize(string serialized)
{
var document = JsonNode.Parse(serialized)?.AsObject() ?? throw new Exception("Unable to deserialize project");
var migrations = GetMigrationsRequired(document);
// Run the migrations that needs to change the literal JSON content before deserialization
foreach (var migration in migrations)
migration.PerformMigrationBeforeDeserialization(document);
var serializedProject = document.Deserialize<SerializedProject>() ?? throw new Exception("Unable to deserialize project");
var project = new Project(serializedProject.Id == default ? Guid.NewGuid() : serializedProject.Id);
var nodeClasses = new Dictionary<NodeClass, NodeClass.SerializedNodeClass>();
foreach (var nodeClassSerializedObj in serializedProject.Classes)
{
var nodeClass = NodeClass.Deserialize(nodeClassSerializedObj, project);
project._Classes.Add(nodeClass);
nodeClasses[nodeClass] = nodeClassSerializedObj;
}
// Run the migrations that need to alter the project now that it's deserialized as well as the classes
foreach (var migration in migrations)
migration.PerformMigrationAfterClassesDeserialization(project);
// will deserialize methods and properties but not any graphs
foreach (var nodeClass in nodeClasses)
nodeClass.Key.Deserialize_Step2(nodeClass.Value);
// deserialize graphs
foreach (var nodeClass in nodeClasses)
nodeClass.Key.Deserialize_Step3();
return project;
}
#endregion
#region Version Migrations
private static List<MigrationBase> GetMigrationsRequired(JsonObject projectJson)
{
if (string.IsNullOrEmpty(projectJson["NodeDevVersion"]?.ToString()) || !NuGet.Versioning.NuGetVersion.TryParse(projectJson["NodeDevVersion"]?.ToString(), out var current))
{
current = NuGet.Versioning.NuGetVersion.Parse("1.0.0");
projectJson["NodeDevVersion"] = "1.0.0";
}
return System.Reflection.Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => x.IsSubclassOf(typeof(MigrationBase)))
.Select(x => (MigrationBase)Activator.CreateInstance(x)!)
.Select(x => (Version: NuGet.Versioning.NuGetVersion.Parse(x.Version), Migration: x))
.Where(x => x.Version > current)
.OrderBy(x => x.Version)
.Select(x => x.Migration)
.ToList();
}
#endregion
#region Debugging
public void StopLiveDebugging()
{
IsLiveDebuggingEnabled = false;
// TODO Search through the executors tree and free up all unused executors
}
public void StartLiveDebugging()
{
IsLiveDebuggingEnabled = true;
}
#endregion
}