Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Detect and warn if duplicate lambda libraries are detected #585

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
62 changes: 62 additions & 0 deletions src/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { TraceSource } from "./trace/trace-context-service";
import { inflateSync } from "zlib";
import { MetricsListener } from "./metrics/listener";
import { SpanOptions, TracerWrapper } from "./trace/tracer-wrapper";
import fs from "fs";

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

Expand Down Expand Up @@ -623,3 +624,64 @@ describe("emitTelemetryOnErrorOutsideHandler", () => {
expect(mockedStartSpan).toBeCalledTimes(0);
});
});

describe("detectDuplicateInstallations", () => {
jest.mock("fs");

let fsAccessMock: jest.SpyInstance;
let logWarningMock: jest.SpyInstance;

beforeEach(() => {
jest.resetAllMocks();
fsAccessMock = jest.spyOn(fs, "access");
logWarningMock = jest.spyOn(require("./utils"), "logWarning").mockImplementation(() => {});
});

it("should log warning when duplicate installations are detected", async () => {
// Mock fs.access to simulate both paths exist
fsAccessMock.mockImplementation((path: string, callback: any) => {
callback(null); // No error = path exists
});

await datadog(async () => {}, { forceWrap: true })();
expect(logWarningMock).toHaveBeenCalledWith(expect.stringContaining("Detected duplicate installations"));
});

it("should not log warning when only layer installation exists", async () => {
// Simulate layerPath exists, localPath does not exist
fsAccessMock.mockImplementation((path: string, callback: any) => {
if (path.includes("/opt/nodejs")) {
callback(null); // Exists
} else {
callback(new Error("ENOENT")); // Does not exist
}
});

await datadog(async () => {}, { forceWrap: true })();
expect(logWarningMock).not.toHaveBeenCalled();
});

it("should not log warning when only local installation exists", async () => {
// Simulate localPath exists, layerPath does not exist
fsAccessMock.mockImplementation((path: string, callback: any) => {
if (path.includes("/opt/nodejs")) {
callback(new Error("ENOENT")); // Does not exist
} else {
callback(null); // Exists
}
});

await datadog(async () => {}, { forceWrap: true })();
expect(logWarningMock).not.toHaveBeenCalled();
});

it("should not log warning when neither installation exists", async () => {
// Simulate neither path exists
fsAccessMock.mockImplementation((path: string, callback: any) => {
callback(new Error("ENOENT")); // Does not exist
});

await datadog(async () => {}, { forceWrap: true })();
expect(logWarningMock).not.toHaveBeenCalled();
});
});
32 changes: 32 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,14 @@ import {
setSandboxInit,
setLogger,
setLogLevel,
logWarning,
} from "./utils";
import { getEnhancedMetricTags } from "./metrics/enhanced-metrics";
import { DatadogTraceHeaders } from "./trace/context/extractor";
import { SpanWrapper } from "./trace/span-wrapper";
import { SpanOptions, TracerWrapper } from "./trace/tracer-wrapper";
import path from "path";
import fs from "fs";

// Backwards-compatible export, TODO deprecate in next major
export { DatadogTraceHeaders as TraceHeaders } from "./trace/context/extractor";
Expand Down Expand Up @@ -127,6 +130,15 @@ export function datadog<TEvent, TResult>(

const traceListener = new TraceListener(finalConfig);

// Check for duplicate installations of the Lambda library
detectDuplicateInstallations().then((duplicateFound) => {
if (duplicateFound) {
logWarning(
`Detected duplicate installations of datadog-lambda-js. This can cause: (1) increased cold start times, (2) broken metrics, and (3) other unexpected behavior. Please use either the Lambda layer version or the package in node_modules, but not both. See: https://docs.datadoghq.com/serverless/aws_lambda/installation/nodejs/?tab=custom`,
);
}
});

// Only wrap the handler once unless forced
const _ddWrappedKey = "_ddWrapped";
if ((handler as any)[_ddWrappedKey] !== undefined && !finalConfig.forceWrap) {
Expand Down Expand Up @@ -465,3 +477,23 @@ export async function emitTelemetryOnErrorOutsideHandler(
await metricsListener.onCompleteInvocation();
}
}

async function detectDuplicateInstallations() {
try {
const layerPath = "/opt/nodejs/node_modules/datadog-lambda-js";
const localPath = path.join(process.cwd(), "node_modules/datadog-lambda-js");

const checkPathExistsAsync = (libraryPath: string): Promise<boolean> =>
new Promise((resolve) => fs.access(libraryPath, (err) => resolve(!err)));

const [layerExists, localExists] = await Promise.all([
checkPathExistsAsync(layerPath),
checkPathExistsAsync(localPath),
]);

return layerExists && localExists;
} catch (err) {
logDebug("Failed to check for duplicate installations.");
return false;
}
}
Loading