From 1c5abac229621a986d03543502ff350f6bb62e8f Mon Sep 17 00:00:00 2001 From: simon-id Date: Fri, 27 Dec 2024 13:39:52 +0100 Subject: [PATCH] add express-session instrumentation --- .../src/express-session.js | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 packages/datadog-instrumentations/src/express-session.js diff --git a/packages/datadog-instrumentations/src/express-session.js b/packages/datadog-instrumentations/src/express-session.js new file mode 100644 index 0000000000..12e41ae784 --- /dev/null +++ b/packages/datadog-instrumentations/src/express-session.js @@ -0,0 +1,52 @@ +'use strict' + +const { addHook } = require('./helpers/instrument') +const shimmer = require('../../datadog-shimmer') +const { channel } = require('./helpers/instrument') + +const sessionMiddlewareFinishCh = channel('datadog:express-session:middleware:finish') + +function wrapSessionMiddleware (sessionMiddleware) { + return function wrappedSessionMiddleware (req, res, next) { + shimmer.wrap(arguments, 2, function wrapNext (next) { + return function wrappedNext () { + if (sessionMiddlewareFinishCh.hasSubscribers) { + const abortController = new AbortController() + + sessionMiddlewareFinishCh.publish({ req, res, sessionId: req.sessionID, abortController }) + + if (abortController.signal.aborted) return + } + + return next.apply(this, arguments) + } + }) + + return sessionMiddleware.apply(this, arguments) + } +} + +function wrapSession (session) { + return function wrappedSession () { + const sessionMiddleware = session.apply(this, arguments) + + return shimmer.wrapFunction(sessionMiddleware, wrapSessionMiddleware) + } +} + +addHook({ + name: 'express-session', + versions: ['>=0.3.0'] // TODO +}, session => { + return shimmer.wrapFunction(session, wrapSession) +}) + + + return shimmer.wrapFunction(session, function wrapSession { + const queryMiddleware = query.apply(this, arguments) + + return shimmer.wrapFunction(queryMiddleware, queryMiddleware => function (req, res, next) { + arguments[2] = publishQueryParsedAndNext(req, res, next) + return queryMiddleware.apply(this, arguments) + }) + }) \ No newline at end of file