-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathhandler.ts
431 lines (374 loc) · 11.7 KB
/
handler.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
import { ISessionContext } from '@jupyterlab/apputils';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import { IExecuteResult } from '@jupyterlab/nbformat';
import { IRenderMimeRegistry } from '@jupyterlab/rendermime';
import { KernelMessage, Kernel } from '@jupyterlab/services';
import {
IExecuteInputMsg,
IExecuteReplyMsg,
IExecuteRequestMsg
} from '@jupyterlab/services/lib/kernel/messages';
import { Signal, ISignal } from '@lumino/signaling';
import { JSONModel, DataModel } from '@lumino/datagrid';
import { IVariableInspector } from './tokens';
import { KernelConnector } from './kernelconnector';
abstract class AbstractHandler implements IVariableInspector.IInspectable {
private _isDisposed = false;
private _disposed = new Signal<this, void>(this);
protected _inspected = new Signal<
IVariableInspector.IInspectable,
IVariableInspector.IVariableInspectorUpdate
>(this);
protected _connector: KernelConnector;
protected _rendermime: IRenderMimeRegistry | null = null;
private _enabled: boolean;
constructor(connector: KernelConnector) {
this._connector = connector;
this._enabled = false;
}
get enabled(): boolean {
return this._enabled;
}
set enabled(value: boolean) {
this._enabled = value;
}
get disposed(): ISignal<this, void> {
return this._disposed;
}
get isDisposed(): boolean {
return this._isDisposed;
}
get inspected(): ISignal<
IVariableInspector.IInspectable,
IVariableInspector.IVariableInspectorUpdate
> {
return this._inspected;
}
get rendermime(): IRenderMimeRegistry | null {
return this._rendermime;
}
abstract performInspection(): void;
abstract performMatrixInspection(
varName: string,
maxRows: number
): Promise<DataModel>;
abstract performWidgetInspection(
varName: string
): Kernel.IShellFuture<
KernelMessage.IExecuteRequestMsg,
KernelMessage.IExecuteReplyMsg
>;
dispose(): void {
if (this.isDisposed) {
return;
}
this._isDisposed = true;
this._disposed.emit();
Signal.clearData(this);
}
performDelete(varName: string): void {
//noop
}
}
/**
* An object that handles code inspection.
*/
export class VariableInspectionHandler extends AbstractHandler {
private _initScript: string;
private _queryCommand: string;
private _matrixQueryCommand: string;
private _widgetQueryCommand: string;
private _deleteCommand: string;
private _changeSettingsCommand:
| ((settings: IVariableInspector.ISettings) => string)
| undefined;
private _ready: Promise<void>;
private _id: string;
private _setting: ISettingRegistry.ISettings;
constructor(options: VariableInspectionHandler.IOptions) {
super(options.connector);
this._id = options.id;
this._rendermime = options.rendermime ?? null;
this._queryCommand = options.queryCommand;
this._matrixQueryCommand = options.matrixQueryCommand;
this._widgetQueryCommand = options.widgetQueryCommand;
this._changeSettingsCommand = options.changeSettingsCommand;
this._deleteCommand = options.deleteCommand;
this._initScript = options.initScript;
this._setting = options.setting;
this._ready = this._connector.ready.then(() => {
this._initOnKernel().then((msg: KernelMessage.IExecuteReplyMsg) => {
this.performSettingsChange();
this._connector.iopubMessage.connect(this._queryCall);
return;
});
});
const onKernelReset = (sender: unknown, kernelReady: Promise<void>) => {
const title: IVariableInspector.IVariableTitle = {
contextName: '<b>Waiting for kernel...</b> '
};
this._inspected.emit({
title: title,
payload: []
} as IVariableInspector.IVariableInspectorUpdate);
this._ready = kernelReady.then(() => {
this._initOnKernel().then((msg: KernelMessage.IExecuteReplyMsg) => {
this.performSettingsChange();
this._connector.iopubMessage.connect(this._queryCall);
this.performInspection();
});
});
};
this._setting.changed.connect(async () => {
await this._ready;
this.performSettingsChange();
this.performInspection();
});
this._connector.kernelRestarted.connect(onKernelReset);
this._connector.kernelChanged.connect(onKernelReset);
}
get id(): string {
return this._id;
}
get ready(): Promise<void> {
return this._ready;
}
/**
* Performs an inspection by sending an execute request with the query command to the kernel.
*/
performInspection(): void {
if (!this.enabled) {
return;
}
const content: KernelMessage.IExecuteRequestMsg['content'] = {
code: this._queryCommand,
stop_on_error: false,
store_history: false
};
this._connector.fetch(content, this._handleQueryResponse);
}
/**
* Performs an inspection of a Jupyter Widget
*/
performWidgetInspection(
varName: string
): Kernel.IShellFuture<IExecuteRequestMsg, IExecuteReplyMsg> {
const request: KernelMessage.IExecuteRequestMsg['content'] = {
code: this._widgetQueryCommand + '(' + varName + ')',
stop_on_error: false,
store_history: false
};
return this._connector.execute(request);
}
/**
* Performs an inspection of the specified matrix.
*/
performMatrixInspection(
varName: string,
maxRows = 100000
): Promise<DataModel> {
const request: KernelMessage.IExecuteRequestMsg['content'] = {
code: this._matrixQueryCommand + '(' + varName + ', ' + maxRows + ')',
stop_on_error: false,
store_history: false
};
const con = this._connector;
return new Promise((resolve, reject) => {
con.fetch(request, (response: KernelMessage.IIOPubMessage) => {
const msgType = response.header.msg_type;
switch (msgType) {
case 'execute_result': {
const payload = response.content as IExecuteResult;
let content: string = payload.data['text/plain'] as string;
content = content.replace(/^'|'$/g, '');
content = content.replace(/\\"/g, '"');
content = content.replace(/\\'/g, "\\\\'");
const modelOptions = JSON.parse(content) as JSONModel.IOptions;
const jsonModel = new JSONModel(modelOptions);
resolve(jsonModel);
break;
}
case 'error':
const error = response as KernelMessage.IErrorMsg;
reject(error);
break;
default:
break;
}
});
});
}
/**
* Send a kernel request to delete a variable from the global environment
*/
performDelete(varName: string): void {
const content: KernelMessage.IExecuteRequestMsg['content'] = {
code: this._deleteCommand + "('" + varName + "')",
stop_on_error: false,
store_history: false
};
this._connector.fetch(content, this._handleQueryResponse);
}
/**
* Send a kernel request to change settings
*/
performSettingsChange(): void {
if (!this._changeSettingsCommand) {
return;
}
const settings: IVariableInspector.ISettings = {
maxItems: this._setting.get('maxItems').composite as number
};
const content: KernelMessage.IExecuteRequestMsg['content'] = {
code: this._changeSettingsCommand(settings),
stop_on_error: false,
store_history: false
};
this._connector.fetch(content, this._handleQueryResponse);
}
/**
* Initializes the kernel by running the set up script located at _initScriptPath.
*/
private _initOnKernel(): Promise<KernelMessage.IExecuteReplyMsg> {
const content: KernelMessage.IExecuteRequestMsg['content'] = {
code: this._initScript,
stop_on_error: false,
silent: true
};
return this._connector.fetch(content, () => {
//no op
});
}
/*
* Handle query response. Emit new signal containing the IVariableInspector.IInspectorUpdate object.
* (TODO: query resp. could be forwarded to panel directly)
*/
private _handleQueryResponse = (
response: KernelMessage.IIOPubMessage
): void => {
const msgType = response.header.msg_type;
switch (msgType) {
case 'execute_result': {
const payload = response.content as IExecuteResult;
let content: string = payload.data['text/plain'] as string;
if (content.slice(0, 1) === "'" || content.slice(0, 1) === '"') {
content = content.slice(1, -1);
content = content.replace(/\\"/g, '"').replace(/\\'/g, "'");
}
const update = JSON.parse(content) as IVariableInspector.IVariable[];
const title = {
contextName: '',
kernelName: this._connector.kernelName || ''
};
this._inspected.emit({ title: title, payload: update });
break;
}
case 'display_data': {
const payloadDisplay = response.content as IExecuteResult;
let contentDisplay: string = payloadDisplay.data[
'text/plain'
] as string;
if (
contentDisplay.slice(0, 1) === "'" ||
contentDisplay.slice(0, 1) === '"'
) {
contentDisplay = contentDisplay.slice(1, -1);
contentDisplay = contentDisplay
.replace(/\\"/g, '"')
.replace(/\\'/g, "'");
}
const updateDisplay = JSON.parse(
contentDisplay
) as IVariableInspector.IVariable[];
const titleDisplay = {
contextName: '',
kernelName: this._connector.kernelName || ''
};
this._inspected.emit({ title: titleDisplay, payload: updateDisplay });
break;
}
default:
break;
}
};
/*
* Invokes a inspection if the signal emitted from specified session is an 'execute_input' msg.
*/
private _queryCall = (
sess: ISessionContext,
msg: KernelMessage.IMessage
): void => {
const msgType = msg.header.msg_type;
switch (msgType) {
case 'execute_input': {
const code = (msg as IExecuteInputMsg).content.code;
if (
!(code === this._queryCommand) &&
!(code === this._matrixQueryCommand) &&
!code.startsWith(this._widgetQueryCommand)
) {
this.performInspection();
}
break;
}
default:
break;
}
};
}
/**
* A name space for inspection handler statics.
*/
export namespace VariableInspectionHandler {
/**
* The instantiation options for an inspection handler.
*/
export interface IOptions {
connector: KernelConnector;
rendermime?: IRenderMimeRegistry;
queryCommand: string;
matrixQueryCommand: string;
widgetQueryCommand: string;
changeSettingsCommand?(settings: IVariableInspector.ISettings): string;
deleteCommand: string;
initScript: string;
id: string;
setting: ISettingRegistry.ISettings;
}
}
export class DummyHandler extends AbstractHandler {
constructor(connector: KernelConnector) {
super(connector);
}
performInspection(): void {
const title: IVariableInspector.IVariableTitle = {
contextName: '. <b>Language currently not supported.</b> ',
kernelName: this._connector.kernelName || ''
};
this._inspected.emit({
title: title,
payload: []
} as IVariableInspector.IVariableInspectorUpdate);
}
performMatrixInspection(
varName: string,
maxRows: number
): Promise<DataModel> {
return new Promise((resolve, reject) => {
reject('Cannot inspect matrices w/ the DummyHandler!');
});
}
performWidgetInspection(
varName: string
): Kernel.IShellFuture<
KernelMessage.IExecuteRequestMsg,
KernelMessage.IExecuteReplyMsg
> {
const request: KernelMessage.IExecuteRequestMsg['content'] = {
code: '',
stop_on_error: false,
store_history: false
};
return this._connector.execute(request);
}
}