ServerlessLife / lambda-live-debugger

Remote debugging AWS Lambda functions
https://www.lldebugger.com/
Mozilla Public License 2.0
16 stars 0 forks source link

Can not find handler if stack is in sub-sub-folder (CDK ES Module) #55

Open kristiandreher opened 14 hours ago

kristiandreher commented 14 hours ago

With a folder structure like then one below lld is not able to find the handler from the stack.

[CDK] [Worker] Error Error: Cannot find entry file at /<project-root>/x/handler.ts
    at findEntry (file:/<project-root>/.lldebugger/compiledCdk.mjs:322538:17)
    at new NodejsFunction (file:/<project-root>/.lldebugger/compiledCdk.mjs:322505:40)
    at new EsmTestAppStack (file:/<project-root>/.lldebugger/compiledCdk.mjs:428909:18)
    at file:/<project-root>/.lldebugger/compiledCdk.mjs:428934:1
    at ModuleJob.run (node:internal/modules/esm/module_job:222:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:316:24)
    at async MessagePort.<anonymous> (file:/<project-root>/node_modules/lambda-live-debugger/dist/frameworks/cdkFrameworkWorker.mjs:25:5)

console.log of dirname gives `dirname /x/`, so I suspect that resolving __dirname does work properly. (There is no folder named x in the project.)

lib/stack/esm-test-app-stack.ts

import { Duration, Stack, type StackProps } from "aws-cdk-lib";
import { Construct } from "constructs";
import * as url from "url";
import { resolve } from "path";
import { NodejsFunction, OutputFormat } from "aws-cdk-lib/aws-lambda-nodejs";
import { Runtime } from "aws-cdk-lib/aws-lambda";

const __dirname = url.fileURLToPath(new URL(".", import.meta.url));

export class EsmTestAppStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    new NodejsFunction(this, "Lambda", {
      timeout: Duration.seconds(20),
      memorySize: 1024,
      runtime: Runtime.NODEJS_20_X,
      entry: resolve(__dirname, "./handler.ts"),
      environment: {
        NODE_OPTIONS: "--enable-source-maps",
        LOG_LEVEL: "DEBUG",
      },
      bundling: {
        minify: true,
        sourceMap: true,
        externalModules: [],
        platform: "node",
        // ESM important properties:
        mainFields: ["module", "main"],
        format: OutputFormat.ESM,
        banner:
          "const require = (await import('node:module')).createRequire(import.meta.url);",
      },
    });
  }
}
markostru commented 14 hours ago

Thank you for reporting the issue.

It would really help me if you enabled verbose logging and sent me the whole log. If it is possible of course. Or a sample project.

But either way I will try to reproduce the problem.

kristiandreher commented 14 hours ago

Verbose log below. Folder name replaced by "project-root".

>yarn lld -v                                        
yarn run v1.22.22
warning package.json: No license field
$ /<project-root>/node_modules/.bin/lld -v
Welcome to Lambda Live Debugger 🐞 version 1.0.5.
To keep the project moving forward, please fill out the feedback form at https://forms.gle/v6ekZtuB45Rv3EyW9. Your input is greatly appreciated!
Parameters: 
 - context=undefined
 - interval=3000
 - verbose=true
 - debuggerId=80edea8f7b5fa224fdc38915ba29a40c
 - start=true
NPM module folder: /<project-root>/node_modules/lambda-live-debugger/dist
Project folder: /<project-root>
Starting the debugger (ID 80edea8f7b5fa224fdc38915ba29a40c)...
Getting resources with 'cdk' framework
[CDK] Entry file: /<project-root>/bin/esm-test-app.ts
[CDK] Using ESM format
[CDK] Context: {
  "@aws-cdk/aws-lambda:recognizeLayerVersion": true,
  "@aws-cdk/core:checkSecretUsage": true,
  "@aws-cdk/core:target-partitions": [
    "aws",
    "aws-cn"
  ],
  "@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
  "@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
  "@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
  "@aws-cdk/aws-iam:minimizePolicies": true,
  "@aws-cdk/core:validateSnapshotRemovalPolicy": true,
  "@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
  "@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
  "@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
  "@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
  "@aws-cdk/core:enablePartitionLiterals": true,
  "@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
  "@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
  "@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
  "@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
  "@aws-cdk/aws-route53-patters:useCertificate": true,
  "@aws-cdk/customresources:installLatestAwsSdkDefault": false,
  "@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
  "@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
  "@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
  "@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
  "@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
  "@aws-cdk/aws-redshift:columnId": true,
  "@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
  "@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
  "@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
  "@aws-cdk/aws-kms:aliasNameRef": true,
  "@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
  "@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
  "@aws-cdk/aws-efs:denyAnonymousAccess": true,
  "@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true,
  "@aws-cdk/aws-lambda-nodejs:useLatestRuntimeVersion": true,
  "@aws-cdk/aws-efs:mountTargetOrderInsensitiveLogicalId": true,
  "@aws-cdk/aws-rds:auroraClusterChangeScopeOfInstanceParameterGroupWithEachParameters": true,
  "@aws-cdk/aws-appsync:useArnForSourceApiAssociationIdentifier": true,
  "@aws-cdk/aws-rds:preventRenderingDeprecatedCredentials": true,
  "@aws-cdk/aws-codepipeline-actions:useNewDefaultBranchForCodeCommitSource": true,
  "@aws-cdk/aws-cloudwatch-actions:changeLambdaPermissionLogicalIdForLambdaAction": true,
  "@aws-cdk/aws-codepipeline:crossAccountKeysDefaultValueToFalse": true,
  "@aws-cdk/aws-codepipeline:defaultPipelineTypeToV2": true,
  "@aws-cdk/aws-kms:reduceCrossAccountRegionPolicyScope": true,
  "@aws-cdk/aws-eks:nodegroupNameAttribute": true,
  "@aws-cdk/aws-ec2:ebsDefaultGp3Volume": true,
  "@aws-cdk/aws-ecs:removeDefaultDeploymentAlarm": true,
  "@aws-cdk/custom-resources:logApiResponseDataPropertyTrueDefault": false,
  "aws:cdk:bundling-stacks": []
}
[CDK] aws-cdk-lib path: /<project-root>/node_modules/aws-cdk-lib
[CDK] [Worker] Started
[Worker undefined] Received message {
  compileOutput: '/<project-root>/.lldebugger/compiledCdk.mjs'
}
[CDK] [Worker] aws-cdk-lib PATH /<project-root>/node_modules/aws-cdk-lib
[CDK] [Worker] Error Error: Cannot find entry file at /<project-root>/x/handler.ts
    at findEntry (file:///<project-root>/.lldebugger/compiledCdk.mjs:322538:17)
    at new NodejsFunction (file:///<project-root>/.lldebugger/compiledCdk.mjs:322505:40)
    at new EsmTestAppStack (file:///<project-root>/.lldebugger/compiledCdk.mjs:428907:5)
    at file:///<project-root>/.lldebugger/compiledCdk.mjs:428932:1
    at ModuleJob.run (node:internal/modules/esm/module_job:222:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:316:24)
    at async MessagePort.<anonymous> (file:///<project-root>/node_modules/lambda-live-debugger/dist/frameworks/cdkFrameworkWorker.mjs:25:5)
Error: Error running CDK code in worker: Cannot find entry file at /<project-root>/x/handler.ts
    at Worker.<anonymous> (file:///<project-root>/node_modules/lambda-live-debugger/dist/frameworks/cdkFramework.mjs:328:24)
    at Worker.emit (node:events:519:28)
    at [kOnErrorMessage] (node:internal/worker:326:10)
    at [kOnMessage] (node:internal/worker:337:37)
    at MessagePort.<anonymous> (node:internal/worker:232:57)
    at [nodejs.internal.kHybridDispatch] (node:internal/event_target:820:20)
    at MessagePort.<anonymous> (node:internal/per_context/messageport:23:28) {
  [cause]: Error: Cannot find entry file at /<project-root>/x/handler.ts
      at findEntry (file:///<project-root>/.lldebugger/compiledCdk.mjs:322538:17)
      at new NodejsFunction (file:///<project-root>/.lldebugger/compiledCdk.mjs:322505:40)
      at new EsmTestAppStack (file:///<project-root>/.lldebugger/compiledCdk.mjs:428907:5)
      at file:///<project-root>/.lldebugger/compiledCdk.mjs:428932:1
      at ModuleJob.run (node:internal/modules/esm/module_job:222:25)
      at async ModuleLoader.import (node:internal/modules/esm/loader:316:24)
      at async MessagePort.<anonymous> (file:///<project-root>/node_modules/lambda-live-debugger/dist/frameworks/cdkFrameworkWorker.mjs:25:5)
}
Done in 2.78s.
ServerlessLife commented 13 hours ago

Perfect.

I will dig into it over the weekend.

kristiandreher commented 13 hours ago

Great! Thanks a lot!

I think that you should be able to reproduce the problem by just moving test/cdk-esm/lib/cdk-esm-stack.ts to a sub-folder of lib.

ServerlessLife commented 9 hours ago

I managed to reproduce the problem.

The issue is only in the case of using __dirname

entry: resolve(__dirname, "./handler.ts"),

But not if I use absolute path: :heavy_check_mark:

 entry: "lib/stack/handler.ts" 

I will keep thinking about how to resolve that.