Skip to content

Conversation

zubairirfan96
Copy link
Collaborator

@zubairirfan96 zubairirfan96 commented Aug 29, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of first-time AWS Lambda deployments by adding a brief post-creation wait, reducing intermittent trust-policy-related failures. No impact to subsequent updates or existing deployments.
  • Chores

    • Updated core package to version 1.5.52.
    • Updated SDK package to version 1.0.47.
    • No API, configuration, or dependency changes; behavior remains unchanged aside from the reliability improvement.

…agation-issue

added 500 ms delay after lambda created for  aws lambda trust policy propagation
Copy link

coderabbitai bot commented Aug 29, 2025

Walkthrough

Version increments in core and SDK package.json files. Lambda creation helper adjusted: removed capturing/logging of CreateFunctionCommand response, added a 500ms wait after creation before verifying deployment status; update path unchanged.

Changes

Cohort / File(s) Summary
Version bumps
packages/*/package.json
Increased versions: packages/core 1.5.51 → 1.5.52; packages/sdk 1.0.46 → 1.0.47. No other fields changed.
Lambda create flow
packages/core/src/helpers/AWSLambdaCode.helper.ts
In create path, stop using/logging function creation response; simply await client.send. Insert a ~500ms delay post-creation (first-time creation) before calling verifyFunctionDeploymentStatus. Update path and error handling unchanged.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant AWSLambdaCodeHelper
    participant AWSLambda

    Caller->>AWSLambdaCodeHelper: createOrUpdateLambda()
    alt First-time create
        AWSLambdaCodeHelper->>AWSLambda: CreateFunctionCommand
        AWSLambda-->>AWSLambdaCodeHelper: ack
        Note over AWSLambdaCodeHelper: Wait ~500ms (trust policy propagation)
        AWSLambdaCodeHelper->>AWSLambda: verifyFunctionDeploymentStatus()
        AWSLambda-->>AWSLambdaCodeHelper: status
    else Update existing
        AWSLambdaCodeHelper->>AWSLambda: UpdateFunctionCode/Config
        AWSLambda-->>AWSLambdaCodeHelper: status
    end
    AWSLambdaCodeHelper-->>Caller: result
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I nudge the version by a hare’s small hop,
A whisk of code, a thump—then pause atop.
Half-second hush for policies to land,
Lambda wakes, approves the plan at hand.
Two carrots tall, the SDK in tow—
Ship it swift; onward we go! 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dev

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/core/src/helpers/AWSLambdaCode.helper.ts (3)

246-262: Harden deployment waiter: check State + LastUpdateStatus, add timeout/backoff, handle failures.

Current implementation can loop forever and ignores State / failure reasons.

Apply this diff:

-export async function verifyFunctionDeploymentStatus(functionName, client): Promise<boolean> {
-    return new Promise((resolve, reject) => {
-        try {
-            let interval = setInterval(async () => {
-                const getFunctionCommand = new GetFunctionCommand({ FunctionName: functionName });
-                const lambdaResponse = await client.send(getFunctionCommand);
-
-                if (lambdaResponse.Configuration.LastUpdateStatus === 'Successful') {
-                    clearInterval(interval);
-                    return resolve(true);
-                }
-            }, 5000);
-        } catch (error) {
-            return false;
-        }
-    });
-}
+export async function verifyFunctionDeploymentStatus(
+    functionName: string,
+    client: LambdaClient,
+    opts: { timeoutMs?: number; pollMs?: number } = {},
+): Promise<boolean> {
+    const timeoutAt = Date.now() + (opts.timeoutMs ?? 120_000);
+    const pollMs = opts.pollMs ?? 2_000;
+    while (Date.now() < timeoutAt) {
+        const lambdaResponse = await client.send(new GetFunctionCommand({ FunctionName: functionName }));
+        const cfg = lambdaResponse.Configuration!;
+        if (cfg.State === 'Active' && cfg.LastUpdateStatus === 'Successful') {
+            return true;
+        }
+        if (cfg.LastUpdateStatus === 'Failed' || cfg.State === 'Failed') {
+            const reason = cfg.LastUpdateStatusReason || cfg.StateReason || 'unknown';
+            throw new Error(`Lambda ${functionName} deployment failed: ${reason}`);
+        }
+        await new Promise((r) => setTimeout(r, pollMs));
+    }
+    throw new Error(`Timed out waiting for Lambda ${functionName} to become Active & Successful`);
+}

229-244: Role waiter can hang forever; add timeout/backoff and handle transient IAM errors.

setInterval with async body risks overlaps and never resolves on errors.

Apply this diff:

-export async function waitForRoleDeploymentStatus(roleName, client): Promise<boolean> {
-    return new Promise((resolve, reject) => {
-        try {
-            let interval = setInterval(async () => {
-                const getRoleCommand = new GetRoleCommand({ RoleName: roleName });
-                const roleResponse = await client.send(getRoleCommand);
-                if (roleResponse.Role.AssumeRolePolicyDocument) {
-                    clearInterval(interval);
-                    return resolve(true);
-                }
-            }, 7000);
-        } catch (error) {
-            return false;
-        }
-    });
-}
+export async function waitForRoleDeploymentStatus(
+    roleName: string,
+    client: IAMClient,
+    opts: { timeoutMs?: number; pollMs?: number } = {},
+): Promise<boolean> {
+    const timeoutAt = Date.now() + (opts.timeoutMs ?? 90_000);
+    const pollMs = opts.pollMs ?? 3_000;
+    while (Date.now() < timeoutAt) {
+        try {
+            const roleResponse = await client.send(new GetRoleCommand({ RoleName: roleName }));
+            if (roleResponse.Role?.AssumeRolePolicyDocument) return true;
+        } catch (err: any) {
+            if (!['NoSuchEntityException', 'ThrottlingException'].includes(err?.name)) {
+                throw err;
+            }
+        }
+        await new Promise((r) => setTimeout(r, pollMs));
+    }
+    throw new Error(`Timed out waiting for IAM role ${roleName} assume-role policy to propagate`);
+}

195-195: Upgrade Lambda runtime to Node.js 20.x.

Node 18.x is EOL; prefer Runtime.nodejs20x for security/support.

Apply this diff:

-                Runtime: Runtime.nodejs18x,
+                Runtime: Runtime.nodejs20x,
🧹 Nitpick comments (1)
packages/core/src/helpers/AWSLambdaCode.helper.ts (1)

206-206: OK to drop capturing the CreateFunction response; optional ARN log.

If ARN telemetry is useful, consider logging FunctionArn from the response; otherwise this is fine.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge Base: Disabled due to data retention organization setting

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e56cb0c and a1c321c.

📒 Files selected for processing (3)
  • packages/core/package.json (1 hunks)
  • packages/core/src/helpers/AWSLambdaCode.helper.ts (1 hunks)
  • packages/sdk/package.json (1 hunks)
🔇 Additional comments (2)
packages/sdk/package.json (1)

3-3: Version bump looks good.

No functional impact; safe metadata change.

packages/core/package.json (1)

3-3: Version bump looks good.

No functional impact; safe metadata change.

Comment on lines +209 to +211
// wait 500 ms to let the function trust policy be applied
// it will only occur when the function is created for the first time
await new Promise((resolve) => setTimeout(resolve, 500));
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace fixed 500ms sleep with a robust waiter; 500ms is too short and flaky.

Trust-policy/IAM propagation often takes seconds. Fold readiness into the deployment waiter and remove the hard-coded delay.

Apply this diff to remove the brittle sleep:

-            // wait 500 ms to let the function trust policy be applied
-            // it will only occur when the function is created for the first time
-            await new Promise((resolve) => setTimeout(resolve, 500));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// wait 500 ms to let the function trust policy be applied
// it will only occur when the function is created for the first time
await new Promise((resolve) => setTimeout(resolve, 500));
🤖 Prompt for AI Agents
In packages/core/src/helpers/AWSLambdaCode.helper.ts around lines 209 to 211,
replace the brittle fixed 500ms sleep with a robust waiter: remove the new
Promise setTimeout and instead integrate an AWS-ready waiter that polls for the
function's readiness or the IAM/trust-policy propagation (for example using AWS
SDK's waiter for functionActive or a custom loop with exponential backoff retry
checking GetFunctionConfiguration/GetPolicy until the expected role/trust-policy
is effective), fold this check into the existing deployment waiter flow, set a
sensible timeout (several seconds to minutes) and surface a clear error if the
waiter times out.

@alaa-eddine-k alaa-eddine-k merged commit 82f30b3 into main Aug 29, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants