Skip to content

Commit 47c5508

Browse files
amymin00astuyve
andauthored
Lazy load metrics listener (#320)
* add lazy loading of MetricsListener * remove console log * add test and extensionEnabled method * add back fileExists method Co-authored-by: AJ Stuyvenberg <[email protected]>
1 parent 9e1957e commit 47c5508

File tree

4 files changed

+64
-14
lines changed

4 files changed

+64
-14
lines changed

src/index.spec.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
} from "./index";
1212
import { incrementErrorsMetric, incrementInvocationsMetric } from "./metrics/enhanced-metrics";
1313
import { LogLevel, setLogLevel } from "./utils";
14+
import mock from "mock-fs";
1415

1516
jest.mock("./metrics/enhanced-metrics");
1617

@@ -319,6 +320,27 @@ describe("datadog", () => {
319320
expect(mockedIncrementErrors).toBeCalledTimes(0);
320321
});
321322

323+
it("doesn't increment enhanced metrics when using extension", async () => {
324+
process.env.DD_ENHANCED_METRICS = "false";
325+
mock({
326+
"/opt/extensions/datadog-agent": Buffer.from([0]),
327+
});
328+
329+
const handlerError: Handler = (event, context, callback) => {
330+
throw Error("Some error");
331+
};
332+
333+
const wrappedHandler = datadog(handlerError, { forceWrap: true });
334+
335+
const result = wrappedHandler({}, mockContext, () => {});
336+
await expect(result).rejects.toEqual(Error("Some error"));
337+
338+
expect(mockedIncrementInvocations).toBeCalledTimes(0);
339+
expect(mockedIncrementErrors).toBeCalledTimes(0);
340+
341+
mock.restore();
342+
});
343+
322344
it("use custom logger to log debug messages", async () => {
323345
const logger = {
324346
debug: jest.fn(),

src/index.ts

Lines changed: 34 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
import { Context, Handler } from "aws-lambda";
2-
import {
3-
incrementErrorsMetric,
4-
incrementInvocationsMetric,
5-
KMSService,
6-
MetricsConfig,
7-
MetricsListener,
8-
} from "./metrics";
2+
import { MetricsConfig } from "./metrics";
3+
import type { MetricsListener as MetricsListenerType } from "./metrics";
4+
95
import { TraceConfig, TraceHeaders, TraceListener } from "./trace";
106
import {
117
logDebug,
@@ -17,6 +13,8 @@ import {
1713
setLogger,
1814
setLogLevel,
1915
} from "./utils";
16+
import { getExtensionPath } from "./utils/extension-path";
17+
import { existsSync } from "fs";
2018

2119
export { TraceHeaders } from "./trace";
2220

@@ -77,8 +75,9 @@ export const defaultConfig: Config = {
7775
siteURL: "",
7876
} as const;
7977

80-
let currentMetricsListener: MetricsListener | undefined;
78+
let currentMetricsListener: MetricsListenerType | undefined;
8179
let currentTraceListener: TraceListener | undefined;
80+
let isExtension: boolean;
8281

8382
/**
8483
* Wraps your AWS lambda handler functions to add tracing/metrics support
@@ -97,7 +96,20 @@ export function datadog<TEvent, TResult>(
9796
config?: Partial<Config>,
9897
): Handler<TEvent, TResult> {
9998
const finalConfig = getConfig(config);
100-
const metricsListener = new MetricsListener(new KMSService(), finalConfig);
99+
let metricsListener: MetricsListenerType;
100+
let incrementErrorsMetric: any;
101+
let incrementInvocationsMetric: any;
102+
if (!isExtensionEnabled()) {
103+
const {
104+
MetricsListener,
105+
KMSService,
106+
incrementErrorsMetric: errorFunc,
107+
incrementInvocationsMetric: invoFunc,
108+
} = require("./metrics");
109+
incrementErrorsMetric = errorFunc;
110+
incrementInvocationsMetric = invoFunc;
111+
metricsListener = new MetricsListener(new KMSService(), finalConfig);
112+
}
101113

102114
const traceListener = new TraceListener(finalConfig);
103115

@@ -122,7 +134,7 @@ export function datadog<TEvent, TResult>(
122134
try {
123135
await traceListener.onStartInvocation(event, context);
124136
await metricsListener.onStartInvocation(event);
125-
if (finalConfig.enhancedMetrics) {
137+
if (finalConfig.enhancedMetrics && !isExtensionEnabled()) {
126138
incrementInvocationsMetric(metricsListener, context);
127139
}
128140
} catch (err) {
@@ -145,7 +157,7 @@ export function datadog<TEvent, TResult>(
145157
localResult,
146158
finalConfig.captureLambdaPayload,
147159
);
148-
if (responseIs5xxError) {
160+
if (responseIs5xxError && !isExtensionEnabled()) {
149161
incrementErrorsMetric(metricsListener, context);
150162
}
151163
}
@@ -156,7 +168,7 @@ export function datadog<TEvent, TResult>(
156168
error = err;
157169
}
158170
try {
159-
if (didThrow && finalConfig.enhancedMetrics) {
171+
if (didThrow && finalConfig.enhancedMetrics && !isExtensionEnabled()) {
160172
incrementErrorsMetric(metricsListener, context);
161173
}
162174
await metricsListener.onCompleteInvocation();
@@ -299,3 +311,13 @@ function getRuntimeTag(): string {
299311
const version = process.version;
300312
return `dd_lambda_layer:datadog-node${version}`;
301313
}
314+
315+
function isExtensionEnabled(): boolean {
316+
if (isExtension !== undefined) {
317+
return isExtension;
318+
}
319+
320+
const extensionPath = getExtensionPath();
321+
isExtension = existsSync(extensionPath);
322+
return isExtension;
323+
}

src/metrics/extension.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
import { URL } from "url";
22
import { get, post, logDebug, logError } from "../utils";
3+
import { getExtensionPath } from "../utils/extension-path";
34
import fs from "fs";
45

56
export const AGENT_URL = "http://127.0.0.1:8124";
67
const HELLO_PATH = "/lambda/hello";
78
const FLUSH_PATH = "/lambda/flush";
8-
const EXTENSION_PATH = "/opt/extensions/datadog-agent";
99
const AGENT_TIMEOUT_MS = 100;
1010

1111
export async function isAgentRunning() {
12-
const extensionExists = await fileExists(EXTENSION_PATH);
12+
const extensionPath = getExtensionPath();
13+
const extensionExists = await fileExists(extensionPath);
1314
if (!extensionExists) {
1415
logDebug(`Agent isn't present in sandbox`);
1516
return false;

src/utils/extension-path.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
const EXTENSION_PATH = "/opt/extensions/datadog-agent";
2+
3+
export function getExtensionPath() {
4+
return EXTENSION_PATH;
5+
}

0 commit comments

Comments
 (0)