-
Notifications
You must be signed in to change notification settings - Fork 949
/
Copy pathabstract-debugger-client.ts
668 lines (618 loc) · 22.4 KB
/
abstract-debugger-client.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
namespace gdjs {
const logger = new gdjs.Logger('Debugger client');
const originalConsole = {
log: console.log,
info: console.info,
debug: console.debug,
warn: console.warn,
error: console.error,
};
/**
* A function used to replace circular references with a new value.
* @param key - The key corresponding to the value.
* @param value - The value.
* @returns The new value.
*/
type DebuggerClientCycleReplacer = (key: string, value: any) => any;
/**
* Generates a JSON serializer that prevent circular references and stop if maxDepth is reached.
* @param [replacer] - A function called for each property on the object or array being stringified, with the property key and its value, and that returns the new value. If not specified, values are not altered.
* @param [cycleReplacer] - Function used to replace circular references with a new value.
* @param [maxDepth] - The maximum depth, after which values are replaced by a string ("[Max depth reached]"). If not specified, there is no maximum depth.
*/
const depthLimitedSerializer = (
replacer?: DebuggerClientCycleReplacer,
cycleReplacer?: DebuggerClientCycleReplacer,
maxDepth?: number
): DebuggerClientCycleReplacer => {
const stack: Array<string> = [],
keys: Array<string> = [];
if (cycleReplacer === undefined || cycleReplacer === null) {
cycleReplacer = function (key, value) {
if (stack[0] === value) {
return '[Circular ~]';
}
return (
'[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'
);
};
}
return function (key: string, value: any): any {
if (stack.length > 0) {
const thisPos = stack.indexOf(this);
~thisPos ? stack.splice(thisPos + 1) : stack.push(this);
~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key);
if (maxDepth != null && thisPos > maxDepth) {
return '[Max depth reached]';
} else {
if (~stack.indexOf(value)) {
value = (cycleReplacer as DebuggerClientCycleReplacer).call(
this,
key,
value
);
}
}
} else {
stack.push(value);
}
return replacer == null ? value : replacer.call(this, key, value);
};
};
/**
* This is an alternative to JSON.stringify that ensure that circular references
* are replaced by a placeholder.
*
* @param obj - The object to serialize.
* @param [replacer] - A function called for each property on the object or array being stringified, with the property key and its value, and that returns the new value. If not specified, values are not altered.
* @param [maxDepth] - The maximum depth, after which values are replaced by a string ("[Max depth reached]"). If not specified, there is no maximum depth.
* @param [spaces] - The number of spaces for indentation.
* @param [cycleReplacer] - Function used to replace circular references with a new value.
*/
const circularSafeStringify = (
obj: any,
replacer?: DebuggerClientCycleReplacer,
maxDepth?: number,
spaces?: number,
cycleReplacer?: DebuggerClientCycleReplacer
) => {
return JSON.stringify(
obj,
depthLimitedSerializer(replacer, cycleReplacer, maxDepth),
spaces
);
};
/** Replacer function for JSON.stringify to convert Error objects into plain objects that can be logged. */
const errorReplacer = (_, value: any) => {
if (value instanceof Error) {
// See https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify
const errorObject = {};
Object.getOwnPropertyNames(value).forEach((prop) => {
errorObject[prop] = value[prop];
});
return errorObject;
}
// Return the value unchanged if it's not an Error object.
return value;
};
const buildGameCrashReport = (
exception: Error,
runtimeGame: gdjs.RuntimeGame
) => {
const sceneNames = runtimeGame.getSceneStack().getAllSceneNames();
const currentScene = runtimeGame.getSceneStack().getCurrentScene();
return {
type: 'javascript-uncaught-exception',
exception,
platformInfo: runtimeGame.getPlatformInfo(),
playerId: runtimeGame.getPlayerId(),
sessionId: runtimeGame.getSessionId(),
isPreview: runtimeGame.isPreview(),
gdevelop: {
previewContext: runtimeGame.getAdditionalOptions().previewContext,
isNativeMobileApp: runtimeGame.getAdditionalOptions().nativeMobileApp,
versionWithHash: runtimeGame.getAdditionalOptions()
.gdevelopVersionWithHash,
environment: runtimeGame.getAdditionalOptions().environment,
},
game: {
gameId: gdjs.projectData.properties.projectUuid,
name: runtimeGame.getGameData().properties.name || '',
packageName: runtimeGame.getGameData().properties.packageName || '',
version: runtimeGame.getGameData().properties.version || '',
location: window.location.href,
projectTemplateSlug: runtimeGame.getAdditionalOptions()
.projectTemplateSlug,
sourceGameId: runtimeGame.getAdditionalOptions().sourceGameId,
},
gameState: {
sceneNames,
isWebGLSupported: runtimeGame.getRenderer().isWebGLSupported(),
hasPixiRenderer: !!runtimeGame.getRenderer().getPIXIRenderer(),
hasThreeRenderer: !!runtimeGame.getRenderer().getThreeRenderer(),
resourcesTotalCount: runtimeGame.getGameData().resources.resources
.length,
antialiasingMode: runtimeGame.getAntialiasingMode(),
isAntialisingEnabledOnMobile: runtimeGame.isAntialisingEnabledOnMobile(),
scriptFiles: runtimeGame.getAdditionalOptions().scriptFiles,
currentSceneTimeFromStart: currentScene
? currentScene.getTimeManager().getTimeFromStart()
: null,
gdjsKeys: Object.keys(gdjs).slice(0, 1000),
},
};
};
/**
* The base class describing a debugger client, that can be used to inspect
* a runtime game (dump its state) or alter it.
*/
export abstract class AbstractDebuggerClient {
_runtimegame: gdjs.RuntimeGame;
_hotReloader: gdjs.HotReloader;
_originalConsole = originalConsole;
_inGameDebugger: gdjs.InGameDebugger;
_hasLoggedUncaughtException = false;
constructor(runtimeGame: RuntimeGame) {
this._runtimegame = runtimeGame;
this._hotReloader = new gdjs.HotReloader(runtimeGame);
this._inGameDebugger = new gdjs.InGameDebugger(runtimeGame);
const redirectJsLog = (
type: 'info' | 'warning' | 'error',
...messages: any[]
) => {
this.log(
'JavaScript',
messages.reduce((accumulator, value) => accumulator + value, ''),
type,
false
);
};
// Hook the console logging functions to log to the Debugger as well
console.log = (...messages: any[]) => {
originalConsole.log(...messages);
redirectJsLog('info', ...messages);
};
console.debug = (...messages: any[]) => {
originalConsole.debug(...messages);
redirectJsLog('info', ...messages);
};
console.info = (...messages: any[]) => {
originalConsole.info(...messages);
redirectJsLog('info', ...messages);
};
console.warn = (...messages: any[]) => {
originalConsole.warn(...messages);
redirectJsLog('warning', ...messages);
};
console.error = (...messages: any[]) => {
originalConsole.error(...messages);
redirectJsLog('error', ...messages);
};
// Overwrite the default GDJS log outputs so that they
// both go to the console (or wherever they were configured to go)
// and sent to the remote debugger.
const existingLoggerOutput = gdjs.Logger.getLoggerOutput();
gdjs.Logger.setLoggerOutput({
log: (
group: string,
message: string,
type: 'info' | 'warning' | 'error' = 'info',
internal = true
) => {
existingLoggerOutput.log(group, message, type, internal);
this.log(group, message, type, internal);
},
});
}
/**
* Should be called by derived class to handle a command
* received from the debugger server.
*
* @param data An object containing the command to do.
*/
protected handleCommand(data: any) {
const that = this;
const runtimeGame = this._runtimegame;
if (!data || !data.command) {
// Not a command that's meant to be handled by the debugger, return silently to
// avoid polluting the console.
return;
}
if (data.command === 'play') {
runtimeGame.pause(false);
} else if (data.command === 'pause') {
runtimeGame.pause(true);
that.sendRuntimeGameDump();
} else if (data.command === 'refresh') {
that.sendRuntimeGameDump();
} else if (data.command === 'getStatus') {
that.sendRuntimeGameStatus();
} else if (data.command === 'set') {
that.set(data.path, data.newValue);
} else if (data.command === 'call') {
that.call(data.path, data.args);
} else if (data.command === 'profiler.start') {
runtimeGame.startCurrentSceneProfiler(function (stoppedProfiler) {
that.sendProfilerOutput(
stoppedProfiler.getFramesAverageMeasures(),
stoppedProfiler.getStats()
);
that.sendProfilerStopped();
});
that.sendProfilerStarted();
} else if (data.command === 'profiler.stop') {
runtimeGame.stopCurrentSceneProfiler();
} else if (data.command === 'hotReload') {
that._hotReloader.hotReload().then((logs) => {
that.sendHotReloaderLogs(logs);
// TODO: if fatal error, should probably reload. The editor should handle this
// as it knows the current scene to show.
});
} else if (data.command === 'switchForInGameEdition') {
if (!this._runtimegame.isInGameEdition()) return;
const sceneName = data.sceneName || null;
const externalLayoutName = data.externalLayoutName || null;
if (!sceneName) {
logger.warn('No scene name specified, switchForInGameEdition aborted');
return;
}
const runtimeGameOptions = this._runtimegame.getAdditionalOptions();
if (runtimeGameOptions.initialRuntimeGameStatus) {
// Skip changing the scene if we're already on the state that is being requested.
if (
runtimeGameOptions.initialRuntimeGameStatus.sceneName ===
sceneName &&
runtimeGameOptions.initialRuntimeGameStatus
.injectedExternalLayoutName === externalLayoutName
) {
return;
}
}
runtimeGame
.getSceneStack()
.replace({
sceneName,
externalLayoutName,
skipCreatingInstancesFromScene: !!externalLayoutName,
clear: true,
});
// Update initialRuntimeGameStatus so that a hard reload
// will come back to the same state, and so that we can check later
// if the game is already on the state that is being requested.
runtimeGameOptions.initialRuntimeGameStatus = {
isPaused: runtimeGame.isPaused(),
isInGameEdition: runtimeGame.isInGameEdition(),
sceneName: sceneName,
injectedExternalLayoutName: externalLayoutName,
skipCreatingInstancesFromScene: !!externalLayoutName,
};
} else if (data.command === 'updateInstances') {
// TODO: do an update/partial hot reload of the instances
} else if (data.command === 'hardReload') {
// This usually means that the preview was modified so much that an entire reload
// is needed, or that the runtime itself could have been modified.
try {
const reloadUrl = new URL(location.href);
// Construct the initial status to be restored.
const initialRuntimeGameStatus = this._runtimegame.getAdditionalOptions()
.initialRuntimeGameStatus;
const runtimeGameStatus: RuntimeGameStatus = {
isPaused: this._runtimegame.isPaused(),
isInGameEdition: this._runtimegame.isInGameEdition(),
sceneName: initialRuntimeGameStatus?.sceneName || null,
injectedExternalLayoutName:
initialRuntimeGameStatus?.injectedExternalLayoutName || null,
skipCreatingInstancesFromScene:
initialRuntimeGameStatus?.skipCreatingInstancesFromScene || false,
};
reloadUrl.searchParams.set(
'runtimeGameStatus',
JSON.stringify(runtimeGameStatus)
);
location.replace(reloadUrl);
} catch (error) {
logger.error(
'Could not reload the game with the new initial status',
error
);
location.reload();
}
} else {
logger.info(
'Unknown command "' + data.command + '" received by the debugger.'
);
}
}
/**
* Should be re-implemented by derived class to send a stringified message object
* to the debugger server.
* @param message
*/
protected abstract _sendMessage(message: string): void;
static isErrorComingFromJavaScriptCode(exception: Error | null): boolean {
if (!exception || !exception.stack) return false;
return exception.stack.includes('GDJSInlineCode');
}
async _reportCrash(exception: Error) {
const gameCrashReport = buildGameCrashReport(
exception,
this._runtimegame
);
// Let a debugger server know about the crash.
this._sendMessage(
circularSafeStringify(
{
command: 'game.crashed',
payload: gameCrashReport,
},
errorReplacer
)
);
// Send the report to the APIs, if allowed.
if (
!this._runtimegame.getAdditionalOptions().crashReportUploadLevel ||
this._runtimegame.getAdditionalOptions().crashReportUploadLevel ===
'none' ||
(this._runtimegame.getAdditionalOptions().crashReportUploadLevel ===
'exclude-javascript-code-events' &&
AbstractDebuggerClient.isErrorComingFromJavaScriptCode(exception))
) {
return;
}
const rootApi = this._runtimegame.isUsingGDevelopDevelopmentEnvironment()
? 'https://api-dev.gdevelop.io'
: 'https://api.gdevelop.io';
const baseUrl = `${rootApi}/analytics`;
try {
await fetch(`${baseUrl}/game-crash-report`, {
body: circularSafeStringify(gameCrashReport, errorReplacer),
method: 'POST',
});
} catch (error) {
logger.error('Error while sending the crash report:', error);
}
}
onUncaughtException(exception: Error): void {
logger.error('Uncaught exception: ' + exception);
this._inGameDebugger.setUncaughtException(exception);
if (!this._hasLoggedUncaughtException) {
// Only log an uncaught exception once, to avoid spamming the debugger server
// in case of an exception at each frame.
this._hasLoggedUncaughtException = true;
this._reportCrash(exception);
}
}
/**
* Send a message (a log) to debugger server.
*/
log(
group: string,
message: string,
type: 'info' | 'warning' | 'error',
internal: boolean
) {
this._sendMessage(
JSON.stringify({
command: 'console.log',
payload: {
message,
type,
group,
internal,
timestamp: performance.now(),
},
})
);
}
/**
* Update a value, specified by a path starting from the {@link RuntimeGame} instance.
* @param path - The path to the variable, starting from {@link RuntimeGame}.
* @param newValue - The new value.
* @return Was the operation successful?
*/
set(path: string[], newValue: any): boolean {
if (!path || !path.length) {
logger.warn('No path specified, set operation from debugger aborted');
return false;
}
let object = this._runtimegame;
let currentIndex = 0;
while (currentIndex < path.length - 1) {
const key = path[currentIndex];
if (!object || !object[key]) {
logger.error('Incorrect path specified. No ' + key + ' in ', object);
return false;
}
object = object[key];
currentIndex++;
}
// Ensure the newValue is properly typed to avoid breaking anything in
// the game engine.
const currentValue = object[path[currentIndex]];
if (typeof currentValue === 'number') {
newValue = parseFloat(newValue);
} else {
if (typeof currentValue === 'string') {
newValue = '' + newValue;
}
}
logger.log('Updating', path, 'to', newValue);
object[path[currentIndex]] = newValue;
return true;
}
/**
* Call a method, specified by a path starting from the {@link RuntimeGame} instance.
* @param path - The path to the method, starting from {@link RuntimeGame}.
* @param args - The arguments to pass the method.
* @return Was the operation successful?
*/
call(path: string[], args: any[]): boolean {
if (!path || !path.length) {
logger.warn('No path specified, call operation from debugger aborted');
return false;
}
let object = this._runtimegame;
let currentIndex = 0;
while (currentIndex < path.length - 1) {
const key = path[currentIndex];
if (!object || !object[key]) {
logger.error('Incorrect path specified. No ' + key + ' in ', object);
return false;
}
object = object[key];
currentIndex++;
}
if (!object[path[currentIndex]]) {
logger.error('Unable to call', path);
return false;
}
logger.log('Calling', path, 'with', args);
object[path[currentIndex]].apply(object, args);
return true;
}
sendRuntimeGameStatus(): void {
const currentScene = this._runtimegame.getSceneStack().getCurrentScene();
this._sendMessage(
circularSafeStringify({
command: 'status',
payload: {
isPaused: this._runtimegame.isPaused(),
isInGameEdition: this._runtimegame.isInGameEdition(),
sceneName: currentScene ? currentScene.getName() : null,
},
})
);
}
/**
* Dump all the relevant data from the {@link RuntimeGame} instance and send it to the server.
*/
sendRuntimeGameDump(): void {
const that = this;
const message = { command: 'dump', payload: this._runtimegame };
const serializationStartTime = Date.now();
// Stringify the message, excluding some known data that are big and/or not
// useful for the debugger.
const excludedValues = [that._runtimegame.getGameData()];
const excludedKeys = [
// Exclude reference to the debugger
'_debuggerClient',
// Exclude some RuntimeScene fields:
'_allInstancesList',
// Exclude circular references to parent runtimeGame or runtimeScene:
'_runtimeGame',
'_runtimeScene',
// Exclude some runtimeObject duplicated data:
'_behaviorsTable',
// Exclude some objects data:
'_animations',
'_animationFrame',
// Exclude linked objects to avoid too much repetitions:
'linkedObjectsManager',
// Could be improved by using private fields and excluding these (_)
// Exclude some behaviors data:
'_platformRBush',
// PlatformBehavior
'HSHG',
// Pathfinding
'_obstaclesHSHG',
// Pathfinding
'owner',
// Avoid circular reference from behavior to parent runtimeObject
// Exclude rendering related objects:
'_renderer',
'_gameRenderer',
'_imageManager',
'_rendererEffects',
// Exclude PIXI textures:
'baseTexture',
'_baseTexture',
'_invalidTexture',
];
const stringifiedMessage = circularSafeStringify(
message,
function (key, value) {
if (
excludedValues.indexOf(value) !== -1 ||
excludedKeys.indexOf(key) !== -1
) {
return '[Removed from the debugger]';
}
return value;
},
/* Limit maximum depth to prevent any crashes */
18
);
const serializationDuration = Date.now() - serializationStartTime;
logger.log(
'RuntimeGame serialization took ' + serializationDuration + 'ms'
);
if (serializationDuration > 500) {
logger.warn(
'Serialization took a long time: please check if there is a need to remove some objects from serialization'
);
}
this._sendMessage(stringifiedMessage);
}
/**
* Send logs from the hot reloader to the server.
* @param logs The hot reloader logs.
*/
sendHotReloaderLogs(logs: HotReloaderLog[]): void {
this._sendMessage(
circularSafeStringify({
command: 'hotReloader.logs',
payload: logs,
})
);
}
/**
* Callback called when profiling is starting.
*/
sendProfilerStarted(): void {
this._sendMessage(
circularSafeStringify({
command: 'profiler.started',
payload: null,
})
);
}
/**
* Callback called when profiling is ending.
*/
sendProfilerStopped(): void {
this._sendMessage(
circularSafeStringify({
command: 'profiler.stopped',
payload: null,
})
);
}
sendInstancesUpdated(runtimeObjects: gdjs.RuntimeObject[]): void {
this._sendMessage(
circularSafeStringify({
command: 'instances.updated',
payload: 'TODO',
})
);
}
/**
* Send profiling results.
* @param framesAverageMeasures The measures made for each frames.
* @param stats Other measures done during the profiler run.
*/
sendProfilerOutput(
framesAverageMeasures: FrameMeasure,
stats: ProfilerStats
): void {
this._sendMessage(
circularSafeStringify({
command: 'profiler.output',
payload: {
framesAverageMeasures: framesAverageMeasures,
stats: stats,
},
})
);
}
}
}