/
service.ts
849 lines (772 loc) · 22.1 KB
/
service.ts
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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { KernelSpec, Session } from '@jupyterlab/services';
import { IDisposable } from '@lumino/disposable';
import { ISignal, Signal } from '@lumino/signaling';
import { DebugProtocol } from 'vscode-debugprotocol';
import { Debugger } from './debugger';
import { VariablesModel } from './panels/variables/model';
import { IDebugger } from './tokens';
/**
* A concrete implementation of the IDebugger interface.
*/
export class DebuggerService implements IDebugger, IDisposable {
/**
* Instantiate a new DebuggerService.
*
* @param options The instantiation options for a DebuggerService.
*/
constructor(options: DebuggerService.IOptions) {
this._config = options.config;
// Avoids setting session with invalid client
// session should be set only when a notebook or
// a console get the focus.
// TODO: also checks that the notebook or console
// runs a kernel with debugging ability
this._session = null;
this._specsManager = options.specsManager ?? null;
this._model = new Debugger.Model();
this._debuggerSources = options.debuggerSources ?? null;
}
/**
* Signal emitted for debug event messages.
*/
get eventMessage(): ISignal<IDebugger, IDebugger.ISession.Event> {
return this._eventMessage;
}
/**
* Whether the debug service is disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* Whether the current debugger is started.
*/
get isStarted(): boolean {
return this._session?.isStarted ?? false;
}
/**
* Returns the debugger service's model.
*/
get model(): IDebugger.Model.IService {
return this._model;
}
/**
* Returns the current debug session.
*/
get session(): IDebugger.ISession | null {
return this._session;
}
/**
* Sets the current debug session to the given parameter.
*
* @param session - the new debugger session.
*/
set session(session: IDebugger.ISession | null) {
if (this._session === session) {
return;
}
if (this._session) {
this._session.dispose();
}
this._session = session;
this._session?.eventMessage.connect((_, event) => {
if (event.event === 'stopped') {
this._model.stoppedThreads.add(event.body.threadId);
void this._getAllFrames();
} else if (event.event === 'continued') {
this._model.stoppedThreads.delete(event.body.threadId);
this._clearModel();
this._clearSignals();
}
this._eventMessage.emit(event);
});
this._sessionChanged.emit(session);
}
/**
* Signal emitted upon session changed.
*/
get sessionChanged(): ISignal<IDebugger, IDebugger.ISession | null> {
return this._sessionChanged;
}
/**
* Dispose the debug service.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._isDisposed = true;
Signal.clearData(this);
}
/**
* Computes an id based on the given code.
*
* @param code The source code.
*/
getCodeId(code: string): string {
try {
return this._config.getCodeId(
code,
this.session?.connection?.kernel?.name ?? ''
);
} catch {
return '';
}
}
/**
* Whether there exists a thread in stopped state.
*/
hasStoppedThreads(): boolean {
return this._model?.stoppedThreads.size > 0 ?? false;
}
/**
* Request whether debugging is available for the session connection.
*
* @param connection The session connection.
*/
async isAvailable(connection: Session.ISessionConnection): Promise<boolean> {
if (!this._specsManager) {
return true;
}
await this._specsManager.ready;
const kernel = connection?.kernel;
if (!kernel) {
return false;
}
const name = kernel.name;
if (!this._specsManager.specs?.kernelspecs[name]) {
return true;
}
return !!(
this._specsManager.specs.kernelspecs[name]?.metadata?.['debugger'] ??
false
);
}
/**
* Clear all the breakpoints for the current session.
*/
async clearBreakpoints(): Promise<void> {
if (this.session?.isStarted !== true) {
return;
}
this._model.breakpoints.breakpoints.forEach((_, path, map) => {
void this._setBreakpoints([], path);
});
let bpMap = new Map<string, IDebugger.IBreakpoint[]>();
this._model.breakpoints.restoreBreakpoints(bpMap);
}
/**
* Continues the execution of the current thread.
*/
async continue(): Promise<void> {
try {
if (!this.session) {
throw new Error('No active debugger session');
}
await this.session.sendRequest('continue', {
threadId: this._currentThread()
});
this._model.stoppedThreads.delete(this._currentThread());
this._clearModel();
this._clearSignals();
} catch (err) {
console.error('Error:', err.message);
}
}
/**
* Retrieve the content of a source file.
*
* @param source The source object containing the path to the file.
*/
async getSource(source: DebugProtocol.Source): Promise<IDebugger.Source> {
if (!this.session) {
throw new Error('No active debugger session');
}
const reply = await this.session.sendRequest('source', {
source,
sourceReference: source.sourceReference ?? 0
});
return { ...reply.body, path: source.path ?? '' };
}
/**
* Evaluate an expression.
*
* @param expression The expression to evaluate as a string.
*/
async evaluate(
expression: string
): Promise<DebugProtocol.EvaluateResponse['body'] | null> {
if (!this.session) {
throw new Error('No active debugger session');
}
const frameId = this.model.callstack.frame?.id;
const reply = await this.session.sendRequest('evaluate', {
context: 'repl',
expression,
frameId
});
if (!reply.success) {
return null;
}
// get the frames to retrieve the latest state of the variables
this._clearModel();
await this._getAllFrames();
return reply.body;
}
/**
* Makes the current thread run again for one step.
*/
async next(): Promise<void> {
try {
if (!this.session) {
throw new Error('No active debugger session');
}
await this.session.sendRequest('next', {
threadId: this._currentThread()
});
} catch (err) {
console.error('Error:', err.message);
}
}
/**
* Request variables for a given variable reference.
*
* @param variablesReference The variable reference to request.
*/
async inspectVariable(
variablesReference: number
): Promise<DebugProtocol.Variable[]> {
if (!this.session) {
throw new Error('No active debugger session');
}
const reply = await this.session.sendRequest('variables', {
variablesReference
});
return reply.body.variables;
}
/**
* Requests all the defined variables and display them in the
* table view.
*/
async displayDefinedVariables(): Promise<void> {
if (!this.session) {
throw new Error('No active debugger session');
}
const inspectReply = await this.session.sendRequest('inspectVariables', {});
const variables = inspectReply.body.variables;
const variableScopes = [
{
name: 'Globals',
variables: variables
}
];
this._model.variables.scopes = variableScopes;
}
/**
* Restart the debugger.
*/
async restart(): Promise<void> {
const { breakpoints } = this._model.breakpoints;
await this.stop();
await this.start();
await this._restoreBreakpoints(breakpoints);
}
/**
* Restore the state of a debug session.
*
* @param autoStart - If true, starts the debugger if it has not been started.
*/
async restoreState(autoStart: boolean): Promise<void> {
if (!this.model || !this.session) {
return;
}
const reply = await this.session.restoreState();
const { body } = reply;
const breakpoints = this._mapBreakpoints(reply.body.breakpoints);
const stoppedThreads = new Set(reply.body.stoppedThreads);
this._config.setHashParams({
kernel: this.session?.connection?.kernel?.name ?? '',
method: body.hashMethod,
seed: body.hashSeed
});
this._config.setTmpFileParams({
kernel: this.session?.connection?.kernel?.name ?? '',
prefix: body.tmpFilePrefix,
suffix: body.tmpFileSuffix
});
this._model.stoppedThreads = stoppedThreads;
if (!this.isStarted && (autoStart || stoppedThreads.size !== 0)) {
await this.start();
}
if (this.isStarted || autoStart) {
this._model.title = this.isStarted
? this.session?.connection?.name || '-'
: '-';
}
if (this._debuggerSources) {
const filtered = this._filterBreakpoints(breakpoints);
this._model.breakpoints.restoreBreakpoints(filtered);
} else {
this._model.breakpoints.restoreBreakpoints(breakpoints);
}
if (stoppedThreads.size !== 0) {
await this._getAllFrames();
} else if (this.isStarted) {
this._clearModel();
this._clearSignals();
}
}
/**
* Starts a debugger.
* Precondition: !isStarted
*/
start(): Promise<void> {
if (!this.session) {
throw new Error('No active debugger session');
}
return this.session.start();
}
/**
* Makes the current thread step in a function / method if possible.
*/
async stepIn(): Promise<void> {
try {
if (!this.session) {
throw new Error('No active debugger session');
}
await this.session.sendRequest('stepIn', {
threadId: this._currentThread()
});
} catch (err) {
console.error('Error:', err.message);
}
}
/**
* Makes the current thread step out a function / method if possible.
*/
async stepOut(): Promise<void> {
try {
if (!this.session) {
throw new Error('No active debugger session');
}
await this.session.sendRequest('stepOut', {
threadId: this._currentThread()
});
} catch (err) {
console.error('Error:', err.message);
}
}
/**
* Stops the debugger.
* Precondition: isStarted
*/
async stop(): Promise<void> {
if (!this.session) {
throw new Error('No active debugger session');
}
await this.session.stop();
if (this._model) {
this._model.clear();
}
}
/**
* Update all breakpoints at once.
*
* @param code - The code in the cell where the breakpoints are set.
* @param breakpoints - The list of breakpoints to set.
* @param path - Optional path to the file where to set the breakpoints.
*/
async updateBreakpoints(
code: string,
breakpoints: IDebugger.IBreakpoint[],
path?: string
): Promise<void> {
if (!this.session?.isStarted) {
return;
}
if (!path) {
path = (await this._dumpCell(code)).body.sourcePath;
}
const state = await this.session.restoreState();
const localBreakpoints = breakpoints
.filter(({ line }) => typeof line === 'number')
.map(({ line }) => ({ line: line! }));
const remoteBreakpoints = this._mapBreakpoints(state.body.breakpoints);
// Set the local copy of breakpoints to reflect only editors that exist.
if (this._debuggerSources) {
const filtered = this._filterBreakpoints(remoteBreakpoints);
this._model.breakpoints.restoreBreakpoints(filtered);
} else {
this._model.breakpoints.restoreBreakpoints(remoteBreakpoints);
}
// Set the kernel's breakpoints for this path.
const reply = await this._setBreakpoints(localBreakpoints, path);
const updatedBreakpoints = reply.body.breakpoints.filter(
(val, _, arr) => arr.findIndex(el => el.line === val.line) > -1
);
// Update the local model and finish kernel configuration.
this._model.breakpoints.setBreakpoints(path, updatedBreakpoints);
await this.session.sendRequest('configurationDone', {});
}
/**
* Get the debugger state
*
* @returns Debugger state
*/
getDebuggerState(): IDebugger.State {
const breakpoints = this._model.breakpoints.breakpoints;
let cells: string[] = [];
for (const id of breakpoints.keys()) {
const editorList = this._debuggerSources!.find({
focus: false,
kernel: this.session?.connection?.kernel?.name ?? '',
path: this._session?.connection?.path ?? '',
source: id
});
const tmp_cells = editorList.map(e => e.model.value.text);
cells = cells.concat(tmp_cells);
}
return { cells, breakpoints };
}
/**
* Restore the debugger state
*
* @param state Debugger state
* @returns Whether the state has been restored successfully or not
*/
async restoreDebuggerState(state: IDebugger.State): Promise<boolean> {
await this.start();
for (const cell of state.cells) {
await this._dumpCell(cell);
}
const breakpoints = new Map<string, IDebugger.IBreakpoint[]>();
const kernel = this.session?.connection?.kernel?.name ?? '';
const { prefix, suffix } = this._config.getTmpFileParams(kernel);
for (const item of state.breakpoints) {
const [id, list] = item;
const unsuffixedId = id.substr(0, id.length - suffix.length);
const codeHash = unsuffixedId.substr(unsuffixedId.lastIndexOf('/') + 1);
const newId = prefix.concat(codeHash).concat(suffix);
breakpoints.set(newId, list);
}
await this._restoreBreakpoints(breakpoints);
const config = await this.session!.sendRequest('configurationDone', {});
await this.restoreState(false);
return config.success;
}
/**
* Clear the current model.
*/
private _clearModel(): void {
this._model.callstack.frames = [];
this._model.variables.scopes = [];
}
/**
* Clear the signals set on the model.
*/
private _clearSignals(): void {
this._model.callstack.currentFrameChanged.disconnect(
this._onCurrentFrameChanged,
this
);
this._model.variables.variableExpanded.disconnect(
this._onVariableExpanded,
this
);
}
/**
* Map a list of scopes to a list of variables.
*
* @param scopes The list of scopes.
* @param variables The list of variables.
*/
private _convertScopes(
scopes: DebugProtocol.Scope[],
variables: DebugProtocol.Variable[][]
): IDebugger.IScope[] {
if (!variables || !scopes) {
return [];
}
return scopes.map((scope, i) => {
return {
name: scope.name,
variables: variables[i].map(variable => {
return { ...variable };
})
};
});
}
/**
* Get the current thread from the model.
*/
private _currentThread(): number {
// TODO: ask the model for the current thread ID
return 1;
}
/**
* Dump the content of a cell.
*
* @param code The source code to dump.
*/
private async _dumpCell(
code: string
): Promise<IDebugger.ISession.IDumpCellResponse> {
if (!this.session) {
throw new Error('No active debugger session');
}
return this.session.sendRequest('dumpCell', { code });
}
/**
* Filter breakpoints and only return those associated with a known editor.
*
* @param breakpoints - Map of breakpoints.
*
*/
private _filterBreakpoints(
breakpoints: Map<string, IDebugger.IBreakpoint[]>
): Map<string, IDebugger.IBreakpoint[]> {
if (!this._debuggerSources) {
return breakpoints;
}
let bpMapForRestore = new Map<string, IDebugger.IBreakpoint[]>();
for (const collection of breakpoints) {
const [id, list] = collection;
list.forEach(() => {
this._debuggerSources!.find({
focus: false,
kernel: this.session?.connection?.kernel?.name ?? '',
path: this._session?.connection?.path ?? '',
source: id
}).forEach(() => {
if (list.length > 0) {
bpMapForRestore.set(id, list);
}
});
});
}
return bpMapForRestore;
}
/**
* Get all the frames from the kernel.
*/
private async _getAllFrames(): Promise<void> {
this._model.callstack.currentFrameChanged.connect(
this._onCurrentFrameChanged,
this
);
this._model.variables.variableExpanded.connect(
this._onVariableExpanded,
this
);
const stackFrames = await this._getFrames(this._currentThread());
this._model.callstack.frames = stackFrames;
}
/**
* Get all the frames for the given thread id.
*
* @param threadId The thread id.
*/
private async _getFrames(
threadId: number
): Promise<DebugProtocol.StackFrame[]> {
if (!this.session) {
throw new Error('No active debugger session');
}
const reply = await this.session.sendRequest('stackTrace', {
threadId
});
const stackFrames = reply.body.stackFrames;
return stackFrames;
}
/**
* Get all the scopes for the given frame.
*
* @param frame The frame.
*/
private async _getScopes(
frame: DebugProtocol.StackFrame
): Promise<DebugProtocol.Scope[]> {
if (!this.session) {
throw new Error('No active debugger session');
}
if (!frame) {
return [];
}
const reply = await this.session.sendRequest('scopes', {
frameId: frame.id
});
return reply.body.scopes;
}
/**
* Get the variables for a given scope.
*
* @param scope The scope to get variables for.
*/
private async _getVariables(
scope: DebugProtocol.Scope
): Promise<DebugProtocol.Variable[]> {
if (!this.session) {
throw new Error('No active debugger session');
}
if (!scope) {
return [];
}
const reply = await this.session.sendRequest('variables', {
variablesReference: scope.variablesReference
});
return reply.body.variables;
}
/**
* Process the list of breakpoints from the server and return as a map.
*
* @param breakpoints - The list of breakpoints from the kernel.
*
*/
private _mapBreakpoints(
breakpoints: IDebugger.ISession.IDebugInfoBreakpoints[]
): Map<string, IDebugger.IBreakpoint[]> {
if (!breakpoints.length) {
return new Map<string, IDebugger.IBreakpoint[]>();
}
return breakpoints.reduce(
(
map: Map<string, IDebugger.IBreakpoint[]>,
val: IDebugger.ISession.IDebugInfoBreakpoints
) => {
const { breakpoints, source } = val;
map.set(
source,
breakpoints.map(point => ({
...point,
source: { path: source },
verified: true
}))
);
return map;
},
new Map<string, IDebugger.IBreakpoint[]>()
);
}
/**
* Handle a change of the current active frame.
*
* @param _ The callstack model
* @param frame The frame.
*/
private async _onCurrentFrameChanged(
_: IDebugger.Model.ICallstack,
frame: IDebugger.IStackFrame
): Promise<void> {
if (!frame) {
return;
}
const scopes = await this._getScopes(frame);
const variables = await Promise.all(
scopes.map(scope => this._getVariables(scope))
);
const variableScopes = this._convertScopes(scopes, variables);
this._model.variables.scopes = variableScopes;
}
/**
* Handle a variable expanded event and request variables from the kernel.
*
* @param _ The variables model.
* @param variable The expanded variable.
*/
private async _onVariableExpanded(
_: VariablesModel,
variable: DebugProtocol.Variable
): Promise<DebugProtocol.Variable[]> {
if (!this.session) {
throw new Error('No active debugger session');
}
const reply = await this.session.sendRequest('variables', {
variablesReference: variable.variablesReference
});
let newVariable = { ...variable, expanded: true };
reply.body.variables.forEach((variable: DebugProtocol.Variable) => {
newVariable = { [variable.name]: variable, ...newVariable };
});
const newScopes = this._model.variables.scopes.map(scope => {
const findIndex = scope.variables.findIndex(
ele => ele.variablesReference === variable.variablesReference
);
scope.variables[findIndex] = newVariable;
return { ...scope };
});
this._model.variables.scopes = [...newScopes];
return reply.body.variables;
}
/**
* Set the breakpoints for a given file.
*
* @param breakpoints The list of breakpoints to set.
* @param path The path to where to set the breakpoints.
*/
private async _setBreakpoints(
breakpoints: DebugProtocol.SourceBreakpoint[],
path: string
): Promise<DebugProtocol.SetBreakpointsResponse> {
if (!this.session) {
throw new Error('No active debugger session');
}
return await this.session.sendRequest('setBreakpoints', {
breakpoints: breakpoints,
source: { path },
sourceModified: false
});
}
/**
* Re-send the breakpoints to the kernel and update the model.
*
* @param breakpoints The map of breakpoints to send
*/
private async _restoreBreakpoints(
breakpoints: Map<string, IDebugger.IBreakpoint[]>
): Promise<void> {
for (const [source, points] of breakpoints) {
console.log(source);
await this._setBreakpoints(
points
.filter(({ line }) => typeof line === 'number')
.map(({ line }) => ({ line: line! })),
source
);
}
this._model.breakpoints.restoreBreakpoints(breakpoints);
}
private _config: IDebugger.IConfig;
private _debuggerSources: IDebugger.ISources | null;
private _eventMessage = new Signal<IDebugger, IDebugger.ISession.Event>(this);
private _isDisposed = false;
private _model: IDebugger.Model.IService;
private _session: IDebugger.ISession | null;
private _sessionChanged = new Signal<IDebugger, IDebugger.ISession | null>(
this
);
private _specsManager: KernelSpec.IManager | null;
}
/**
* A namespace for `DebuggerService` statics.
*/
export namespace DebuggerService {
/**
* Instantiation options for a `DebuggerService`.
*/
export interface IOptions {
/**
* The configuration instance with hash method.
*/
config: IDebugger.IConfig;
/**
* The optional debugger sources instance.
*/
debuggerSources?: IDebugger.ISources | null;
/**
* The optional kernel specs manager.
*/
specsManager?: KernelSpec.IManager | null;
}
}