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 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
76 changes: 76 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,78 @@ describe("emitTelemetryOnErrorOutsideHandler", () => {
expect(mockedStartSpan).toBeCalledTimes(0);
});
});

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

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

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

it("should log warning when duplicate installations are detected", async () => {
// Mock fs.promises.access to simulate both paths exist
fsAccessMock.mockResolvedValue(undefined); // undefined (no error) = path exists

await datadog(
async () => {
/* empty */
},
{ 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) => {
if (path.includes("/opt/nodejs")) {
return Promise.resolve(); // Exists
}
return Promise.reject(new Error("ENOENT")); // Does not exist
});

await datadog(
async () => {
/* empty */
},
{ 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) => {
if (path.includes("/opt/nodejs")) {
return Promise.reject(new Error("ENOENT")); // Does not exist
}
return Promise.resolve(); // Exists
});

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

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

await datadog(
async () => {
/* empty */
},
{ forceWrap: true },
)();
expect(logWarningMock).not.toHaveBeenCalled();
});
});
42 changes: 42 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 @@ -104,6 +107,9 @@ export const _metricsQueue: MetricsQueue = new MetricsQueue();
let currentMetricsListener: MetricsListener | undefined;
let currentTraceListener: TraceListener | undefined;

const LAMBDA_LAYER_PATH = "/opt/nodejs/node_modules/datadog-lambda-js";
const LAMBDA_LIBRARY_PATH = path.join(process.cwd(), "node_modules/datadog-lambda-js");

if (getEnvValue(coldStartTracingEnvVar, "true").toLowerCase() === "true") {
subscribeToDC();
}
Expand Down Expand Up @@ -131,6 +137,19 @@ export function datadog<TEvent, TResult>(

const traceListener = new TraceListener(finalConfig);

// Check for duplicate installations of the Lambda library
detectDuplicateInstallations()
.then((duplicateFound) => {
Comment on lines +141 to +142
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I put this under the datadog() wrapper, but I'm not sure if this is the best place to make this call. If there's somewhere that's better, I'm open to suggestions!

if (duplicateFound) {
Copy link
Contributor Author

@nhulston nhulston Jan 31, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, this code might be relevant, so wanted to share for reviewers:

export class TracerWrapper {
private tracer: any;
constructor() {
try {
// Try and use the same version of the tracing library the user has installed.
// This handles edge cases where two versions of dd-trace are installed, one in the layer
// and one in the user's code.
const path = require.resolve("dd-trace", { paths: ["/var/task/node_modules", ...module.paths] });
this.tracer = require(path);
return;
} catch (err) {
if (err instanceof Object || err instanceof Error) {
logDebug("Couldn't require dd-trace from main", err);
}
}
}

Note that this code only loads in one version of dd-trace, not to be confused with the datadog-lambda-js; this PR detects duplicate installations of datadog-lambda-js

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wonder if there's a way for us to use similar logic like this one 🤔

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`,
);
}
})
.catch(() => {
logDebug("Failed to check for duplicate installations.");
});

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

async function detectDuplicateInstallations() {
try {
const checkPathExistsAsync = async (libraryPath: string): Promise<boolean> => {
try {
await fs.promises.access(libraryPath);
return true;
} catch {
return false;
}
};

const [layerExists, localExists] = await Promise.all([
checkPathExistsAsync(LAMBDA_LAYER_PATH),
checkPathExistsAsync(LAMBDA_LIBRARY_PATH),
]);

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