-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathDapDebugger.cs
More file actions
1437 lines (1242 loc) · 51.9 KB
/
DapDebugger.cs
File metadata and controls
1437 lines (1242 loc) · 51.9 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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GitHub.DistributedTask.WebApi;
using GitHub.Runner.Common;
using GitHub.Runner.Sdk;
using Microsoft.DevTunnels.Connections;
using Microsoft.DevTunnels.Contracts;
using Microsoft.DevTunnels.Management;
using Newtonsoft.Json;
namespace GitHub.Runner.Worker.Dap
{
/// <summary>
/// Stores information about a completed step for stack trace display.
/// </summary>
internal sealed class CompletedStepInfo
{
public string DisplayName { get; set; }
public TaskResult? Result { get; set; }
public int FrameId { get; set; }
}
/// <summary>
/// Single public facade for the Debug Adapter Protocol subsystem.
/// Owns the full transport, handshake, step-level pauses, variable
/// inspection, reconnection, and cancellation flow.
/// </summary>
public sealed class DapDebugger : RunnerService, IDapDebugger
{
private const int _defaultTimeoutMinutes = 15;
private const string _timeoutEnvironmentVariable = "ACTIONS_RUNNER_DAP_CONNECTION_TIMEOUT";
private const int _defaultTunnelConnectTimeoutSeconds = 30;
private const string _tunnelConnectTimeoutSeconds = "ACTIONS_RUNNER_DAP_TUNNEL_CONNECT_TIMEOUT_SECONDS";
private const string _contentLengthHeader = "Content-Length: ";
private const int _maxMessageSize = 10 * 1024 * 1024; // 10 MB
private const int _maxHeaderLineLength = 8192; // 8 KB
private const int _connectionRetryDelayMilliseconds = 500;
// Thread ID for the single job execution thread
private const int _jobThreadId = 1;
// Frame ID for the current step (always 1)
private const int _currentFrameId = 1;
// Frame IDs for completed steps start at 1000
private const int _completedFrameIdBase = 1000;
private TcpListener _listener;
private TcpClient _client;
private NetworkStream _stream;
private readonly SemaphoreSlim _sendLock = new SemaphoreSlim(1, 1);
private int _nextSeq = 1;
private Task _connectionLoopTask;
private volatile DapSessionState _state = DapSessionState.NotStarted;
private CancellationTokenRegistration? _cancellationRegistration;
private bool _isFirstStep = true;
// Dev Tunnel relay host for remote debugging
private TunnelRelayTunnelHost _tunnelRelayHost;
private WebSocketDapBridge _webSocketBridge;
// Cancellation source for the connection loop, cancelled in StopAsync
// so AcceptTcpClientAsync unblocks cleanly without relying on listener disposal.
private CancellationTokenSource _loopCts;
// When true, skip tunnel relay startup (unit tests only)
internal bool SkipTunnelRelay { get; set; }
// When true, skip the public websocket bridge and expose the raw DAP
// listener directly on the configured tunnel port (unit tests only).
internal bool SkipWebSocketBridge { get; set; }
// Synchronization for step execution
private TaskCompletionSource<DapCommand> _commandTcs;
private readonly object _stateLock = new object();
// Session readiness — signaled when configurationDone is received
private TaskCompletionSource<bool> _readyTcs;
// Whether to pause before the next step (set by 'next' command)
private bool _pauseOnNextStep = true;
// Current execution context
private IStep _currentStep;
private IExecutionContext _jobContext;
private int _currentStepIndex;
// Track completed steps for stack trace
private readonly List<CompletedStepInfo> _completedSteps = new List<CompletedStepInfo>();
private int _nextCompletedFrameId = _completedFrameIdBase;
// Client connection tracking for reconnection support
private volatile bool _isClientConnected;
// Scope/variable inspection provider — reusable by future DAP features
private DapVariableProvider _variableProvider;
// REPL command executor for run() commands
private DapReplExecutor _replExecutor;
public bool IsActive =>
_state == DapSessionState.Ready ||
_state == DapSessionState.Paused ||
_state == DapSessionState.Running;
internal DapSessionState State => _state;
internal int InternalDapPort => (_listener?.LocalEndpoint as IPEndPoint)?.Port ?? 0;
public override void Initialize(IHostContext hostContext)
{
base.Initialize(hostContext);
_variableProvider = new DapVariableProvider(hostContext.SecretMasker);
_replExecutor = new DapReplExecutor(hostContext, SendOutput);
Trace.Info("DapDebugger initialized");
}
public async Task StartAsync(IExecutionContext jobContext)
{
ArgUtil.NotNull(jobContext, nameof(jobContext));
var debuggerConfig = jobContext.Global.Debugger;
if (!debuggerConfig.HasValidTunnel)
{
throw new ArgumentException(
"Debugger requires valid tunnel configuration (tunnelId, clusterId, hostToken, port).");
}
Trace.Info($"Starting DAP debugger on port {debuggerConfig.Tunnel.Port}");
_jobContext = jobContext;
_readyTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var dapPort = SkipWebSocketBridge ? debuggerConfig.Tunnel.Port : 0;
_listener = new TcpListener(IPAddress.Loopback, dapPort);
_listener.Start();
if (SkipWebSocketBridge)
{
Trace.Info($"DAP debugger listening on {_listener.LocalEndpoint}");
}
else
{
Trace.Info($"Internal DAP debugger listening on {_listener.LocalEndpoint}");
_webSocketBridge = new WebSocketDapBridge();
_webSocketBridge.Initialize(HostContext);
_webSocketBridge.Configure(debuggerConfig.Tunnel.Port, InternalDapPort);
_webSocketBridge.Start();
}
// Start Dev Tunnel relay so remote clients reach the local DAP port.
// The relay is torn down explicitly in StopAsync (after the DAP session
// is closed) so we do NOT pass the job cancellation token here — that
// would race with the DAP shutdown and drop the transport mid-protocol.
if (!SkipTunnelRelay)
{
await StartTunnelRelayAsync(debuggerConfig);
}
_state = DapSessionState.WaitingForConnection;
_loopCts = CancellationTokenSource.CreateLinkedTokenSource(jobContext.CancellationToken);
_connectionLoopTask = ConnectionLoopAsync(_loopCts.Token);
_cancellationRegistration = jobContext.CancellationToken.Register(() =>
{
Trace.Info("Job cancellation requested, unblocking pending waits.");
_readyTcs?.TrySetCanceled();
_commandTcs?.TrySetResult(DapCommand.Disconnect);
});
Trace.Info($"DAP debugger started on port {debuggerConfig.Tunnel.Port}");
}
private async Task StartTunnelRelayAsync(DebuggerConfig config)
{
Trace.Info($"Starting Dev Tunnel relay (tunnel={config.Tunnel.TunnelId}, cluster={config.Tunnel.ClusterId})");
var userAgents = HostContext.UserAgents.ToArray();
var httpHandler = HostContext.CreateHttpClientHandler();
httpHandler.AllowAutoRedirect = false;
var managementClient = new TunnelManagementClient(
userAgents,
() => Task.FromResult<AuthenticationHeaderValue>(new AuthenticationHeaderValue("tunnel", config.Tunnel.HostToken)),
tunnelServiceUri: null,
httpHandler);
var tunnel = new Tunnel
{
TunnelId = config.Tunnel.TunnelId,
ClusterId = config.Tunnel.ClusterId,
AccessTokens = new Dictionary<string, string>
{
[TunnelAccessScopes.Host] = config.Tunnel.HostToken
},
Ports = new[]
{
new TunnelPort { PortNumber = config.Tunnel.Port }
},
};
_tunnelRelayHost = new TunnelRelayTunnelHost(managementClient, HostContext.GetTrace("DevTunnelRelay").Source);
var tunnelConnectTimeoutSeconds = ResolveTunnelConnectTimeout();
using var connectCts = new CancellationTokenSource(TimeSpan.FromSeconds(tunnelConnectTimeoutSeconds));
Trace.Info($"Connecting to Dev Tunnel relay (timeout: {tunnelConnectTimeoutSeconds}s)");
await _tunnelRelayHost.ConnectAsync(tunnel, connectCts.Token);
Trace.Info("Dev Tunnel relay started");
}
public async Task WaitUntilReadyAsync()
{
if (_state == DapSessionState.NotStarted || _listener == null || _jobContext == null)
{
return;
}
var timeoutMinutes = ResolveTimeout();
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromMinutes(timeoutMinutes));
try
{
Trace.Info($"Waiting for debugger client connection (timeout: {timeoutMinutes} minutes)...");
using (timeoutCts.Token.Register(() => _readyTcs?.TrySetCanceled()))
{
await _readyTcs.Task;
}
Trace.Info("DAP debugger ready.");
}
catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested && !_jobContext.CancellationToken.IsCancellationRequested)
{
throw new TimeoutException($"No debugger client connected within {timeoutMinutes} minutes.");
}
}
public async Task OnJobCompletedAsync()
{
if (_state != DapSessionState.NotStarted)
{
try
{
OnJobCompleted();
}
catch (Exception ex)
{
Trace.Warning($"DAP OnJobCompleted error: {ex.Message}");
}
}
await StopAsync();
}
public async Task StopAsync()
{
if (_cancellationRegistration.HasValue)
{
_cancellationRegistration.Value.Dispose();
_cancellationRegistration = null;
}
try
{
if (_listener != null || _tunnelRelayHost != null || _connectionLoopTask != null)
{
Trace.Info("Stopping DAP debugger");
}
// Tear down Dev Tunnel relay FIRST — it may hold connections to the
// local port and must be fully disposed before we release the listener,
// otherwise the next worker can't bind the same port.
if (_tunnelRelayHost != null)
{
Trace.Info("Stopping Dev Tunnel relay");
var disposeTask = _tunnelRelayHost.DisposeAsync().AsTask();
if (await Task.WhenAny(disposeTask, Task.Delay(10_000)) != disposeTask)
{
Trace.Warning("Dev Tunnel relay dispose timed out after 10s");
}
else
{
Trace.Info("Dev Tunnel relay stopped");
}
_tunnelRelayHost = null;
}
if (_webSocketBridge != null)
{
Trace.Info("Stopping WebSocket DAP bridge");
var shutdownTask = _webSocketBridge.ShutdownAsync();
if (await Task.WhenAny(shutdownTask, Task.Delay(5_000)) != shutdownTask)
{
Trace.Warning("WebSocket DAP bridge shutdown timed out after 5s");
_ = shutdownTask.ContinueWith(
t => Trace.Error($"WebSocket DAP bridge shutdown faulted: {t.Exception?.GetBaseException().Message}"),
TaskContinuationOptions.OnlyOnFaulted);
}
else
{
Trace.Info("WebSocket DAP bridge stopped");
}
_webSocketBridge = null;
}
CleanupConnection();
// Cancel the connection loop first so AcceptTcpClientAsync unblocks
// cleanly, then stop the listener once nothing is using it.
try { _loopCts?.Cancel(); }
catch { /* best effort */ }
try { _listener?.Stop(); }
catch { /* best effort */ }
if (_connectionLoopTask != null)
{
try
{
await Task.WhenAny(_connectionLoopTask, Task.Delay(5000));
}
catch { /* best effort */ }
}
}
catch (Exception ex)
{
Trace.Error("Error stopping DAP debugger");
Trace.Error(ex);
}
lock (_stateLock)
{
if (_state != DapSessionState.NotStarted && _state != DapSessionState.Terminated)
{
_state = DapSessionState.Terminated;
}
}
_isClientConnected = false;
_listener = null;
_client = null;
_stream = null;
_readyTcs = null;
_connectionLoopTask = null;
_loopCts?.Dispose();
_loopCts = null;
_webSocketBridge = null;
}
public async Task OnStepStartingAsync(IStep step)
{
if (!IsActive)
{
return;
}
try
{
bool isFirst = _isFirstStep;
_isFirstStep = false;
await OnStepStartingAsync(step, isFirst);
}
catch (Exception ex)
{
Trace.Warning($"DAP OnStepStarting error: {ex.Message}");
}
}
public void OnStepCompleted(IStep step)
{
if (!IsActive)
{
return;
}
try
{
var result = step.ExecutionContext?.Result;
Trace.Info("Step completed");
// Add to completed steps list for stack trace
lock (_stateLock)
{
if (_state != DapSessionState.Ready &&
_state != DapSessionState.Paused &&
_state != DapSessionState.Running)
{
return;
}
_completedSteps.Add(new CompletedStepInfo
{
DisplayName = step.DisplayName,
Result = result,
FrameId = _nextCompletedFrameId++
});
}
}
catch (Exception ex)
{
Trace.Warning($"DAP OnStepCompleted error: {ex.Message}");
}
}
internal async Task HandleMessageAsync(string messageJson, CancellationToken cancellationToken)
{
Request request = null;
try
{
request = JsonConvert.DeserializeObject<Request>(messageJson);
if (request == null)
{
Trace.Warning("Failed to deserialize DAP request");
return;
}
if (!string.Equals(request.Type, "request", StringComparison.OrdinalIgnoreCase))
{
Trace.Warning("Received DAP message that was not a request");
return;
}
Trace.Info("Handling DAP request");
Response response;
if (request.Command == "evaluate")
{
response = await HandleEvaluateAsync(request, cancellationToken);
}
else
{
response = request.Command switch
{
"initialize" => HandleInitialize(request),
"attach" => HandleAttach(request),
"configurationDone" => HandleConfigurationDone(request),
"disconnect" => HandleDisconnect(request),
"threads" => HandleThreads(request),
"stackTrace" => HandleStackTrace(request),
"scopes" => HandleScopes(request),
"variables" => HandleVariables(request),
"continue" => HandleContinue(request),
"next" => HandleNext(request),
"setBreakpoints" => HandleSetBreakpoints(request),
"setExceptionBreakpoints" => HandleSetExceptionBreakpoints(request),
"completions" => HandleCompletions(request),
"stepIn" => CreateResponse(request, false, "Step In is not supported. Actions jobs debug at the step level - use 'next' to advance to the next step.", body: null),
"stepOut" => CreateResponse(request, false, "Step Out is not supported. Actions jobs debug at the step level - use 'continue' to resume.", body: null),
"stepBack" => CreateResponse(request, false, "Step Back is not yet supported.", body: null),
"reverseContinue" => CreateResponse(request, false, "Reverse Continue is not yet supported.", body: null),
"pause" => CreateResponse(request, false, "Pause is not supported. The debugger pauses automatically at step boundaries.", body: null),
_ => CreateResponse(request, false, $"Unsupported command: {request.Command}", body: null)
};
}
response.RequestSeq = request.Seq;
response.Command = request.Command;
SendResponse(response);
if (request.Command == "initialize")
{
SendEvent(new Event
{
EventType = "initialized"
});
Trace.Info("Sent initialized event");
}
}
catch (Exception ex)
{
Trace.Error($"Error handling DAP request ({ex.GetType().Name})");
if (request != null)
{
var maskedMessage = HostContext?.SecretMasker?.MaskSecrets(ex.Message) ?? ex.Message;
var errorResponse = CreateResponse(request, false, maskedMessage, body: null);
errorResponse.RequestSeq = request.Seq;
errorResponse.Command = request.Command;
SendResponse(errorResponse);
}
}
}
internal void HandleClientConnected()
{
_isClientConnected = true;
Trace.Info("Client connected to debug session");
// If we're paused, re-send the stopped event so the new client
// knows the current state (important for reconnection)
string description = null;
lock (_stateLock)
{
if (_state == DapSessionState.Paused && _currentStep != null)
{
description = $"Stopped before step: {_currentStep.DisplayName}";
}
}
if (description != null)
{
Trace.Info("Re-sending stopped event to reconnected client");
SendStoppedEvent("step", description);
}
}
internal void HandleClientDisconnected()
{
_isClientConnected = false;
Trace.Info("Client disconnected from debug session");
// Intentionally do NOT release the command TCS here.
// The session stays paused, waiting for a client to reconnect.
// The debugger's connection loop will accept a new client and
// call HandleClientConnected, which re-sends the stopped event.
}
private async Task ConnectionLoopAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
try
{
Trace.Info("Waiting for debug client connection...");
_client = await _listener.AcceptTcpClientAsync(cancellationToken);
_stream = _client.GetStream();
var remoteEndPoint = _client.Client.RemoteEndPoint;
Trace.Info($"Debug client connected from {remoteEndPoint}");
HandleClientConnected();
// Enter message processing loop until client disconnects or cancellation is requested
await ProcessMessagesAsync(cancellationToken);
Trace.Info("Client disconnected, waiting for reconnection...");
HandleClientDisconnected();
CleanupConnection();
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
CleanupConnection();
if (cancellationToken.IsCancellationRequested)
{
break;
}
// If the listener has been stopped, don't retry.
if (_listener == null || !_listener.Server.IsBound)
{
Trace.Info("Listener stopped, exiting connection loop");
break;
}
Trace.Error("Debugger connection error");
Trace.Error(ex);
try
{
await Task.Delay(_connectionRetryDelayMilliseconds, cancellationToken);
}
catch (OperationCanceledException)
{
break;
}
}
}
Trace.Info("Connection loop ended");
}
private void CleanupConnection()
{
_sendLock.Wait();
try
{
try { _stream?.Close(); } catch { /* best effort */ }
try { _client?.Close(); } catch { /* best effort */ }
_stream = null;
_client = null;
}
finally
{
_sendLock.Release();
}
}
private async Task ProcessMessagesAsync(CancellationToken cancellationToken)
{
Trace.Info("Starting DAP message processing loop");
try
{
while (!cancellationToken.IsCancellationRequested && _client?.Connected == true)
{
var json = await ReadMessageAsync(cancellationToken);
if (json == null)
{
Trace.Info("Client disconnected (end of stream)");
break;
}
await HandleMessageAsync(json, cancellationToken);
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
Trace.Info("Message processing cancelled");
}
catch (IOException ex)
{
Trace.Info($"Connection closed ({ex.GetType().Name})");
}
catch (Exception ex)
{
Trace.Error($"Error in message loop ({ex.GetType().Name})");
}
Trace.Info("DAP message processing loop ended");
}
private async Task<string> ReadMessageAsync(CancellationToken cancellationToken)
{
int contentLength = -1;
while (true)
{
var line = await ReadLineAsync(cancellationToken);
if (line == null)
{
return null;
}
if (line.Length == 0)
{
break;
}
if (line.StartsWith(_contentLengthHeader, StringComparison.OrdinalIgnoreCase))
{
var lengthStr = line.Substring(_contentLengthHeader.Length).Trim();
if (!int.TryParse(lengthStr, out contentLength))
{
throw new InvalidDataException($"Invalid Content-Length: {lengthStr}");
}
}
}
if (contentLength < 0)
{
throw new InvalidDataException("Missing Content-Length header");
}
if (contentLength > _maxMessageSize)
{
throw new InvalidDataException($"Message size {contentLength} exceeds maximum allowed size of {_maxMessageSize}");
}
var buffer = new byte[contentLength];
var totalRead = 0;
while (totalRead < contentLength)
{
var bytesRead = await _stream.ReadAsync(buffer, totalRead, contentLength - totalRead, cancellationToken);
if (bytesRead == 0)
{
throw new EndOfStreamException("Connection closed while reading message body");
}
totalRead += bytesRead;
}
var json = Encoding.UTF8.GetString(buffer);
Trace.Verbose("Received DAP message body");
return json;
}
private async Task<string> ReadLineAsync(CancellationToken cancellationToken)
{
var lineBuilder = new StringBuilder();
var buffer = new byte[1];
var previousWasCr = false;
while (true)
{
var bytesRead = await _stream.ReadAsync(buffer, 0, 1, cancellationToken);
if (bytesRead == 0)
{
return lineBuilder.Length > 0 ? lineBuilder.ToString() : null;
}
var c = (char)buffer[0];
if (c == '\n' && previousWasCr)
{
if (lineBuilder.Length > 0 && lineBuilder[lineBuilder.Length - 1] == '\r')
{
lineBuilder.Length--;
}
return lineBuilder.ToString();
}
previousWasCr = c == '\r';
lineBuilder.Append(c);
if (lineBuilder.Length > _maxHeaderLineLength)
{
throw new InvalidDataException($"Header line exceeds maximum length of {_maxHeaderLineLength}");
}
}
}
/// <summary>
/// Serializes and writes a DAP message with Content-Length framing.
/// Must be called within the _sendLock.
///
/// Secret masking is intentionally NOT applied here at the serialization
/// layer. Masking the raw JSON would corrupt protocol envelope fields
/// (type, event, command, seq) if a secret collides with those strings.
/// Instead, each DAP producer masks user-visible text at the point of
/// construction via the runner's SecretMasker. See DapVariableProvider,
/// DapReplExecutor, and DapDebugger for the call sites.
/// </summary>
private void SendMessageInternal(ProtocolMessage message)
{
var json = JsonConvert.SerializeObject(message, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
var bodyBytes = Encoding.UTF8.GetBytes(json);
var header = $"Content-Length: {bodyBytes.Length}\r\n\r\n";
var headerBytes = Encoding.ASCII.GetBytes(header);
_stream.Write(headerBytes, 0, headerBytes.Length);
_stream.Write(bodyBytes, 0, bodyBytes.Length);
_stream.Flush();
Trace.Verbose("Sent DAP message");
}
private void SendMessage(ProtocolMessage message)
{
try
{
_sendLock.Wait();
try
{
if (_stream == null)
{
Trace.Warning("Cannot send message: no client connected");
return;
}
message.Seq = _nextSeq++;
SendMessageInternal(message);
}
finally
{
_sendLock.Release();
}
Trace.Info("Sent message");
}
catch (Exception ex)
{
Trace.Warning($"Failed to send message ({ex.GetType().Name})");
}
}
private void SendEvent(Event evt)
{
SendMessage(evt);
}
private void SendResponse(Response response)
{
SendMessage(response);
}
private void SendOutput(string category, string text)
{
SendEvent(new Event
{
EventType = "output",
Body = new OutputEventBody
{
Category = category,
Output = text
}
});
}
internal async Task OnStepStartingAsync(IStep step, bool isFirstStep)
{
bool pauseOnNextStep;
CancellationToken cancellationToken;
lock (_stateLock)
{
if (_state != DapSessionState.Ready &&
_state != DapSessionState.Paused &&
_state != DapSessionState.Running)
{
return;
}
_currentStep = step;
_currentStepIndex = _completedSteps.Count;
pauseOnNextStep = _pauseOnNextStep;
cancellationToken = _jobContext?.CancellationToken ?? CancellationToken.None;
}
// Reset variable references so stale nested refs from the
// previous step are not served to the client.
_variableProvider?.Reset();
// Determine if we should pause
bool shouldPause = isFirstStep || pauseOnNextStep;
if (!shouldPause)
{
Trace.Info("Step starting without debugger pause");
return;
}
var reason = isFirstStep ? "entry" : "step";
var description = isFirstStep
? $"Stopped at job entry: {step.DisplayName}"
: $"Stopped before step: {step.DisplayName}";
Trace.Info("Step starting with debugger pause");
// Send stopped event to debugger (only if client is connected)
SendStoppedEvent(reason, description);
// Wait for debugger command
await WaitForCommandAsync(cancellationToken);
}
internal void OnJobCompleted()
{
Trace.Info("Job completed, sending terminated event");
int exitCode;
lock (_stateLock)
{
if (_state == DapSessionState.Terminated)
{
Trace.Info("Session already terminated, skipping OnJobCompleted events");
return;
}
_state = DapSessionState.Terminated;
exitCode = _jobContext?.Result == TaskResult.Succeeded ? 0 : 1;
}
SendEvent(new Event
{
EventType = "terminated",
Body = new TerminatedEventBody()
});
SendEvent(new Event
{
EventType = "exited",
Body = new ExitedEventBody
{
ExitCode = exitCode
}
});
}
private Response HandleInitialize(Request request)
{
if (request.Arguments != null)
{
try
{
request.Arguments.ToObject<InitializeRequestArguments>();
Trace.Info("Initialize arguments received");
}
catch (Exception ex)
{
Trace.Warning($"Failed to parse initialize arguments ({ex.GetType().Name})");
}
}
lock (_stateLock)
{
_state = DapSessionState.Initializing;
}
// Build capabilities — MVP only supports configurationDone
var capabilities = new Capabilities
{
SupportsConfigurationDoneRequest = true,
SupportsEvaluateForHovers = true,
// All other capabilities are false for MVP
SupportsFunctionBreakpoints = false,
SupportsConditionalBreakpoints = false,
SupportsStepBack = false,
SupportsSetVariable = false,
SupportsRestartFrame = false,
SupportsGotoTargetsRequest = false,
SupportsStepInTargetsRequest = false,
SupportsCompletionsRequest = true,
SupportsModulesRequest = false,
SupportsTerminateRequest = false,
SupportTerminateDebuggee = false,
SupportsDelayedStackTraceLoading = false,
SupportsLoadedSourcesRequest = false,
SupportsProgressReporting = false,
SupportsRunInTerminalRequest = false,
SupportsCancelRequest = false,
SupportsExceptionOptions = false,
SupportsValueFormattingOptions = false,
SupportsExceptionInfoRequest = false,
};
Trace.Info("Initialize request handled, capabilities sent");
return CreateResponse(request, true, body: capabilities);
}
private Response HandleAttach(Request request)
{
Trace.Info("Attach request handled");
return CreateResponse(request, true, body: null);
}
private Response HandleConfigurationDone(Request request)
{
lock (_stateLock)
{
_state = DapSessionState.Ready;
}
_readyTcs.TrySetResult(true);
Trace.Info("Configuration done, debug session is ready");
return CreateResponse(request, true, body: null);
}
private Response HandleDisconnect(Request request)
{
Trace.Info("Disconnect request received");
lock (_stateLock)
{
_state = DapSessionState.Terminated;
// Release any blocked step execution
_commandTcs?.TrySetResult(DapCommand.Disconnect);
}
return CreateResponse(request, true, body: null);
}
private Response HandleThreads(Request request)
{
IExecutionContext jobContext;
lock (_stateLock)
{
jobContext = _jobContext;
}
var threadName = jobContext != null
? MaskUserVisibleText($"Job: {jobContext.GetGitHubContext("job") ?? "workflow job"}")
: "Job Thread";
var body = new ThreadsResponseBody
{
Threads = new List<Thread>
{
new Thread
{
Id = _jobThreadId,
Name = threadName
}
}
};
return CreateResponse(request, true, body: body);
}
private Response HandleStackTrace(Request request)
{
IStep currentStep;
int currentStepIndex;
CompletedStepInfo[] completedSteps;