Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,60 @@ describe("datadog", () => {
process.env = oldEnv;
});

describe("tracer metrics", () => {
it.each([false, true])("flushes after each invocation (handler throws: %p)", async (shouldThrow) => {
const tracer = require("dd-trace");
const flush = jest.spyOn(tracer.dogstatsd, "flush").mockImplementation(() => {});
const handlerError = new Error("handler failed");
const metricHandler = jest.fn(async () => {
expect(flush).toHaveBeenCalledTimes(metricHandler.mock.calls.length - 1);
tracer.dogstatsd.distribution("custom.metric", 1);
if (shouldThrow) throw handlerError;
return "result";
});
const wrapped = datadog(metricHandler, { logForwarding: true, enhancedMetrics: false });

try {
for (let invocation = 1; invocation <= 2; invocation++) {
if (shouldThrow) {
await expect(wrapped({}, mockContext, () => {})).rejects.toBe(handlerError);
} else {
await expect(wrapped({}, mockContext, () => {})).resolves.toBe("result");
}
expect(flush).toHaveBeenCalledTimes(invocation);
}
} finally {
flush.mockRestore();
}
});

it.each([false, true])("ignores flush errors (handler throws: %p)", async (shouldThrow) => {
const tracer = require("dd-trace");
const flush = jest.spyOn(tracer.dogstatsd, "flush").mockImplementation(() => {
throw new Error("flush failed");
});
const handlerError = new Error("handler failed");
const wrapped = datadog(
async () => {
if (shouldThrow) throw handlerError;
return "result";
},
{ logForwarding: true, enhancedMetrics: false },
);

try {
if (shouldThrow) {
await expect(wrapped({}, mockContext, () => {})).rejects.toBe(handlerError);
} else {
await expect(wrapped({}, mockContext, () => {})).resolves.toBe("result");
}
expect(flush).toHaveBeenCalledTimes(1);
} finally {
flush.mockRestore();
}
});
});

it("patches http request when autoPatch enabled", async () => {
mockTraceHeaders = {
"x-datadog-parent-id": "9101112",
Expand Down
5 changes: 3 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,9 +134,10 @@ export function datadog<TEvent, TResult>(
config?: Partial<Config>,
): Handler<TEvent, TResult> | any {
const finalConfig = getConfig(config);
const metricsListener = new MetricsListener(new KMSService(), finalConfig);
const tracerWrapper = new TracerWrapper();
const metricsListener = new MetricsListener(new KMSService(), finalConfig, tracerWrapper);

const traceListener = new TraceListener(finalConfig);
const traceListener = new TraceListener(finalConfig, tracerWrapper);

// Only wrap the handler once unless forced
const _ddWrappedKey = "_ddWrapped";
Expand Down
51 changes: 51 additions & 0 deletions src/metrics/listener.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ import mock from "mock-fs";

import { LogLevel, setLogLevel } from "../utils";
import { EXTENSION_URL } from "./extension";
import * as extension from "./extension";

import { MetricsListener } from "./listener";
import { LambdaDogStatsD } from "./dogstatsd";
import { Context } from "aws-lambda";
import { TracerWrapper } from "../trace/tracer-wrapper";

jest.mock("./dogstatsd");

Expand Down Expand Up @@ -39,6 +41,55 @@ describe("MetricsListener", () => {
mock.restore();
});

describe("tracer metrics", () => {
const config = {
apiKey: "",
apiKeyKMS: "",
apiKeySecretARN: "",
enhancedMetrics: false,
logForwarding: true,
shouldRetryMetrics: false,
localTesting: true,
siteURL,
};

it.each([false, true])("flushes tracer metrics before the extension (Lambda client throws: %p)", async (throws) => {
const order: string[] = [];
jest.spyOn(extension, "isExtensionRunning").mockResolvedValue(true);
jest.spyOn(TracerWrapper.prototype, "flushMetrics").mockImplementation(() => {
order.push("tracer");
});
jest.spyOn(LambdaDogStatsD.prototype, "flush").mockImplementation(async () => {
order.push("lambda");
if (throws) throw new Error("Lambda metrics flush failed");
});
const extensionFlush = jest.spyOn(extension, "flushExtension").mockImplementation(async () => {
order.push("extension");
return true;
});
const listener = new MetricsListener(new MockKMS("") as any, config);

await listener.onStartInvocation({});
await listener.onCompleteInvocation();

expect(order).toEqual(["tracer", "lambda", "extension"]);
expect(extensionFlush).toHaveBeenCalledWith(true);
});

it("flushes tracer metrics even when the extension is absent", async () => {
jest.spyOn(extension, "isExtensionRunning").mockResolvedValue(false);
const tracerFlush = jest.spyOn(TracerWrapper.prototype, "flushMetrics").mockImplementation(() => {});
const extensionFlush = jest.spyOn(extension, "flushExtension");
const listener = new MetricsListener(new MockKMS("") as any, config);

await listener.onStartInvocation({});
await listener.onCompleteInvocation();

expect(tracerFlush).toHaveBeenCalledTimes(1);
expect(extensionFlush).not.toHaveBeenCalled();
});
});

it("uses unencrypted api key by default", async () => {
nock("https://api.example.com").post("/api/v1/distribution_points?api_key=api-key").reply(200, {});

Expand Down
10 changes: 9 additions & 1 deletion src/metrics/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Context } from "aws-lambda";
import { getEnhancedMetricTags } from "./enhanced-metrics";
import { LambdaDogStatsD } from "./dogstatsd";
import { FIPS_MODE_ENABLED } from "../utils/fips";
import { TracerWrapper } from "../trace/tracer-wrapper";

const METRICS_BATCH_SEND_INTERVAL = 10000; // 10 seconds
const HISTORICAL_METRICS_THRESHOLD_HOURS = 4 * 60 * 60 * 1000; // 4 hours
Expand Down Expand Up @@ -68,7 +69,11 @@ export class MetricsListener {
private isExtensionRunning?: boolean = undefined;
private globalTags?: string[] = [];

constructor(private kmsClient: KMSService, private config: MetricsConfig) {
constructor(
private kmsClient: KMSService,
private config: MetricsConfig,
private tracerWrapper: TracerWrapper = new TracerWrapper(),
) {
this.config = config;
this.statsDClient = new LambdaDogStatsD();
}
Expand Down Expand Up @@ -101,6 +106,9 @@ export class MetricsListener {
}

public async onCompleteInvocation() {
// Flush tracer metrics before the extension and independently of extension detection.
this.tracerWrapper.flushMetrics();

// Flush any metrics
try {
if (this.currentProcessor !== undefined) {
Expand Down
4 changes: 2 additions & 2 deletions src/trace/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,8 @@ export class TraceListener {
return this.contextService.currentTraceHeaders;
}

constructor(private config: TraceConfig) {
this.tracerWrapper = new TracerWrapper();
constructor(private config: TraceConfig, tracerWrapper: TracerWrapper = new TracerWrapper()) {
this.tracerWrapper = tracerWrapper;
this.contextService = new TraceContextService(this.tracerWrapper, this.config);
this.inferrer = new SpanInferrer(this.tracerWrapper);
}
Expand Down
48 changes: 48 additions & 0 deletions src/trace/tracer-wrapper.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { TracerWrapper } from "./tracer-wrapper";
let mockNoTracer = false;
let mockTracerInitialised = false;
let mockSpan: any = null;
let mockDogstatsd: any;
let mockDataStreamsCheckpointer: any = {
setConsumeCheckpoint: jest.fn(),
};
Expand All @@ -28,6 +29,7 @@ jest.mock("dd-trace", () => {
active: () => mockSpan,
}),
dataStreamsCheckpointer: mockDataStreamsCheckpointer,
dogstatsd: mockDogstatsd,
};
}
});
Expand All @@ -53,6 +55,7 @@ describe("TracerWrapper", () => {
mockNoTracer = false;
mockTracerInitialised = true;
mockSpan = null;
mockDogstatsd = { flush: jest.fn() };
mockDataStreamsCheckpointer.setConsumeCheckpoint.mockClear();
});
afterEach(() => {
Expand Down Expand Up @@ -117,6 +120,51 @@ describe("TracerWrapper", () => {
const traceContext = wrapper.traceContext();
expect(traceContext).toBeNull();
});
describe("flushMetrics", () => {
it("flushes the tracer's DogStatsD client with its receiver", () => {
const wrapper = new TracerWrapper();

wrapper.flushMetrics();

expect(mockDogstatsd.flush).toHaveBeenCalledTimes(1);
expect(mockDogstatsd.flush.mock.instances[0]).toBe(mockDogstatsd);
});

it("flushes metrics independently of tracing availability", () => {
mockTracerInitialised = false;
const wrapper = new TracerWrapper();

wrapper.flushMetrics();

expect(mockDogstatsd.flush).toHaveBeenCalledTimes(1);
});

it("does nothing when the tracer is absent", () => {
mockNoTracer = true;
const wrapper = new TracerWrapper();

expect(() => wrapper.flushMetrics()).not.toThrow();
expect(mockDogstatsd.flush).not.toHaveBeenCalled();
});

it.each([undefined, {}, { flush: true }])("supports a tracer without a flush API: %p", (dogstatsd) => {
mockDogstatsd = dogstatsd;
const wrapper = new TracerWrapper();

expect(() => wrapper.flushMetrics()).not.toThrow();
});

it("contains errors from the DogStatsD client", () => {
mockDogstatsd.flush.mockImplementation(() => {
throw new Error("flush failed");
});
const wrapper = new TracerWrapper();

expect(() => wrapper.flushMetrics()).not.toThrow();
expect(mockDogstatsd.flush).toHaveBeenCalledTimes(1);
});
});

it("should not call internal setConsumeCheckpoint when arn is not provided", () => {
process.env["DD_DATA_STREAMS_ENABLED"] = "true";
const wrapper = new TracerWrapper();
Expand Down
13 changes: 13 additions & 0 deletions src/trace/tracer-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,19 @@ export class TracerWrapper {
}
}

public flushMetrics(): void {
try {
const dogstatsd = this.tracer?.dogstatsd;
if (typeof dogstatsd?.flush === "function") {
dogstatsd.flush();
}
} catch (err) {
if (err instanceof Object || err instanceof Error) {
logDebug("Failed to flush dd-trace metrics", err);
}
}
}

public injectSpan(span: SpanContext): any {
const dest = {};
this.tracer.inject(span, "text_map", dest);
Expand Down
Loading