@graphql-mesh/plugin-prometheus
Version:
73 lines (69 loc) • 2.72 kB
JavaScript
const prometheus = require('@envelop/prometheus');
const utils = require('@graphql-mesh/utils');
const promClient = require('prom-client');
async function useMeshPrometheus(pluginOptions) {
const registry = pluginOptions.registry
? await utils.loadFromModuleExportExpression(pluginOptions.registry, {
cwd: pluginOptions.baseDir,
importFn: pluginOptions.importFn,
defaultExportName: 'default',
})
: promClient.register;
const fetchHistogram = new promClient.Histogram({
name: 'graphql_mesh_fetch_duration',
help: 'Time spent on outgoing HTTP calls',
labelNames: ['url', 'method', 'requestHeaders', 'statusCode', 'statusText', 'responseHeaders'],
registers: [registry],
});
const delegateHistogram = new promClient.Histogram({
name: 'graphql_mesh_delegate_duration',
help: 'Time spent on delegate execution',
labelNames: ['sourceName', 'typeName', 'fieldName', 'args', 'key'],
registers: [registry],
});
return {
onPluginInit({ addPlugin }) {
addPlugin(prometheus.usePrometheus({
...pluginOptions,
registry,
}));
},
onDelegate({ sourceName, typeName, fieldName, args, key }) {
if (pluginOptions.delegation !== false) {
const start = Date.now();
return () => {
const end = Date.now();
const duration = end - start;
delegateHistogram.observe({
sourceName,
typeName,
fieldName,
args: JSON.stringify(args),
key: JSON.stringify(key),
}, duration);
};
}
return undefined;
},
onFetch({ url, options }) {
if (pluginOptions.fetch !== false) {
const start = Date.now();
return ({ response }) => {
const end = Date.now();
const duration = end - start;
fetchHistogram.observe({
url,
method: options.method,
requestHeaders: JSON.stringify(options.headers),
statusCode: response.status,
statusText: response.statusText,
responseHeaders: JSON.stringify(utils.getHeadersObj(response.headers)),
}, duration);
};
}
return undefined;
},
};
}
module.exports = useMeshPrometheus;
;