kibana/examples/v8_profiler_examples/server/lib/session.ts
Patrick Mueller 1f3426942c
[examples] add routes to access v8 profiling (#155956)
Adds routes to run v8 profiling tools, when running the examples plugins
via `--run-examples`

See the included README.md for more info
2023-06-30 08:42:38 -04:00

79 lines
1.9 KiB
TypeScript

/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { Logger } from '@kbn/core/server';
import { createDeferred } from './deferred';
let inspector: any = null;
try {
inspector = require('inspector');
} catch (err) {
// inspector will be null :-(
}
export async function createSession(logger: Logger): Promise<Session> {
logger.debug('creating session');
if (inspector == null) {
throw new Error('the inspector module is not available for this version of node');
}
let session = null;
try {
session = new inspector.Session();
} catch (err) {
throw new Error(`error creating inspector session: ${err.message}`);
}
try {
session.connect();
} catch (err) {
throw new Error(`error connecting inspector session: ${err.message}`);
}
return new Session(logger, session);
}
export class Session {
readonly logger: Logger;
private session: any;
constructor(logger: Logger, session: any) {
this.logger = logger;
this.session = session;
}
async destroy() {
this.session.disconnect();
this.session = null;
}
on(event: string, handler: any) {
this.session.on(event, handler);
}
async post(method: string, args?: any) {
this.logger.debug(`posting method ${method} ${JSON.stringify(args)}`);
if (this.session == null) {
throw new Error('session disconnected');
}
const deferred = createDeferred();
this.session.post(method, args, (err: any, response: any) => {
if (err) {
this.logger.debug(`error from method ${method}: ${err.message}`);
return deferred.reject(err);
}
deferred.resolve(response);
});
return deferred.promise;
}
}