I am using Elastic APM. I find that mongoose integration is not working when used with GraphQL/Apollo Server somehow. I wrote an apollo-server plugin like this to start/stop transactions:
import apm from 'elastic-apm-node/start';
import _ from 'lodash';
import { gql } from 'apollo-server-express';
const apmPlugin = {
requestDidStart: (requestContext) => {
const query = gql`${requestContext.request.query}`;
const type = _.get(query, 'definitions[0].operation', '');
const funcName = _.get(query, 'definitions[0].name.value', '');
const txnName = type && funcName ? `${type} ${funcName}` : '/gql';
const txn = apm.startTransaction(txnName, 'graphql');
return {
didEncounterErrors: (err) => {
if (txn) {
txn.result = err.errors.length === 1 ? err.errors[0].name : 'error';
}
},
willSendResponse: (res) => {
if (Array.isArray(res.response.errors).length === 0) {
txn.result = 'success';
}
if (typeof txn?.end === 'function') txn.end();
},
};
},
};
It works, but I am missing spans from mongoose, when I enable trace, this is what I see:
start trace {
trans: 'ddc03cb86cf71448',
parent: undefined,
trace: '7127e63abe8e6d5086d36c13deee8183',
name: 'unnamed',
type: 'graphql',
subtype: null,
action: null
}
start span {
span: '94fc2307e19dd187',
parent: 'ddc03cb86cf71448',
trace: '7127e63abe8e6d5086d36c13deee8183',
name: 'GraphQL: Unknown Query',
type: 'db',
subtype: 'graphql',
action: 'execute'
}
intercepted call to graphql.execute { id: 'ddc03cb86cf71448' }
Mongoose: yyy.findOne({ domainSlug: 'xxx' }, { projection: {} })
no active transaction found - cannot build new span
Mongoose: yyy.findOne({ email: 'xxx', company: ObjectId("5f1ab19010469e8eb952e754") }}, { projection: {} })
no active transaction found - cannot build new span
Mongoose: roles.find({ _id: { '$in': [ ObjectId("5f1ab19010469e8eb952e786") ] } }, { skip: undefined, limit: undefined, perDocumentLimit: undefined, projection: {}})
no active transaction found - cannot build new span
ended span {
span: '94fc2307e19dd187',
parent: 'ddc03cb86cf71448',
trace: '7127e63abe8e6d5086d36c13deee8183',
name: 'GraphQL: xxx',
type: 'db',
subtype: 'graphql',
action: 'execute'
}
encoding span {
span: '94fc2307e19dd187',
parent: 'ddc03cb86cf71448',
trace: '7127e63abe8e6d5086d36c13deee8183',
name: 'GraphQL: xxx',
type: 'db'
}
sending span {
span: '94fc2307e19dd187',
parent: 'ddc03cb86cf71448',
trace: '7127e63abe8e6d5086d36c13deee8183',
name: 'GraphQL: xxx',
type: 'db'
}
sending transaction {
trans: 'ddc03cb86cf71448',
trace: '7127e63abe8e6d5086d36c13deee8183'
}
ended transaction {
trans: 'ddc03cb86cf71448',
parent: undefined,
trace: '7127e63abe8e6d5086d36c13deee8183',
type: 'graphql',
result: 'success',
name: 'mutation doLogin'
}
Notice the spans created fine before and after those mongoose calls, but the mongoose calls seem to be unable to find the active transaction somehow.
no active transaction found - cannot build new span