Skip to content

Conversation

@lakshayman
Copy link
Collaborator

@lakshayman lakshayman commented Nov 10, 2025

Date: 10/11/2025

Developer Name: @lakshayman


Issue Ticket Number

#247

Description

Improved code quality

Documentation Updated?

  • Yes
  • No

Under Feature Flag

  • Yes
  • No

Database Changes

  • Yes
  • No

Breaking Changes

  • Yes
  • No

Development Tested?

  • Yes
  • No

Screenshots

Screenshot 1 SCREENSHOT TO SUPPORT NEW LOGGING image

Test Coverage

Screenshot 1 image

Additional Notes

@lakshayman lakshayman requested a review from vinit717 November 10, 2025 06:59
@lakshayman lakshayman self-assigned this Nov 10, 2025
@coderabbitai
Copy link

coderabbitai bot commented Nov 10, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Summary by CodeRabbit

  • New Features

    • Added structured logging system with multiple log levels.
    • Introduced worker pool for improved concurrent operation handling.
    • Added centralized HTTP utilities with timeout support.
    • Enhanced error handling with explicit error types and standardized responses.
  • Refactor

    • Restructured Lambda function initialization and dependency injection across all service handlers.
    • Improved internal error handling and validation in data retrieval operations.

Walkthrough

This PR refactors four Lambda handlers (call-profile, call-profiles, health-check, verify) to use centralized dependency injection through a new utils.Deps struct and InitializeLambdaWithFirestore initialization function. It simultaneously introduces new utility modules for structured logging, error handling, HTTP operations with timeouts, concurrency management (WorkerPool), and a standardized User data structure for Firestore interactions.

Changes

Cohort / File(s) Summary
Call-Profile Service Refactoring
call-profile/main.go, call-profile/main_test.go
Converted handler from deps-bound method to standalone function accepting *utils.Deps. Updated Firestore data retrieval using dsnap.DataTo into User struct. Replaced direct HTTP health checks with utils.GetWithContext. Changed main initialization to use utils.InitializeLambdaWithFirestore. Updated test helpers to construct and pass utils.Deps with exported fields.
Call-Profiles Service Refactoring
call-profiles/main.go, call-profiles/main_test.go
Migrated handler signature to accept *utils.Deps instead of local deps type. Replaced sync.WaitGroup concurrency with utils.WorkerPool for profile processing. Introduced structured logging via utils.GetLogger(). Updated Firestore initialization to centralized utils.InitializeLambdaWithFirestore. Adapted test dependencies to public utils.Deps structure.
Health-Check Service Refactoring
health-check/main.go, health-check/main_test.go
Replaced method-based handler with standalone function accepting *utils.Deps. Changed concurrency from WaitGroup to WorkerPool. Updated HTTP health checks to use utils.GetWithContext. Converted Firestore data extraction to use User struct with doc.DataTo. Modified initialization to utils.InitializeLambdaWithFirestore. Updated test to use public utils.Deps structure.
Verify Service Refactoring
verify/main.go, verify/main_test.go, verify/helpers_test.go
Added context parameter to verify function signature. Converted handler from deps method to standalone function accepting *utils.Deps. Replaced direct HTTP calls with utils.PostWithContext. Updated main to use centralized Firestore initialization. Modified test helpers to pass context and use public utils.Deps.
Layer Utils — Core Infrastructure
layer/utils/handler.go
New file introducing Deps struct (Client, Ctx), HandlerFunc type signature, and InitializeLambdaWithFirestore function for unified Lambda initialization with Firestore client and dependency injection.
Layer Utils — Logging
layer/utils/logger.go
New structured logging module with Logger type, log levels (Debug, Info, Warn, Error), and global logging functions. Provides JSON-based logging with service context and field merging.
Layer Utils — Error Handling
layer/utils/errors.go
New error utilities introducing predefined errors (ErrInvalidUserID, ErrProfileURLNotFound, etc.), ProfileError struct with wrapping, HandleLambdaError for error-to-response mapping, and HandleProfileSkippedError for skip responses.
Layer Utils — HTTP Operations
layer/utils/http.go
New HTTP utilities providing CreateHTTPClient, context-aware GetWithContext, PostWithContext, and DoRequestWithContext with unified timeout handling via DefaultHTTPTimeout.
Layer Utils — Concurrency
layer/utils/concurrency.go
New concurrency module introducing WorkerPool with fixed-size worker pool pattern, Submit and Wait semantics, panic recovery, and SafeGoroutine helper for tracked goroutine execution.
Layer Utils — Auth & Firestore
layer/utils/auth.go, layer/utils/firestore.go
Updated auth.go to use centralized LogError instead of direct logging. Enhanced firestore.go with improved error propagation in GetUserData (User struct parsing), Getdata (timeout-aware HTTP, error wrapping), and getLastDiff (error returns instead of fatal exits).
Layer Utils — Data Models
layer/utils/constants.go
New User struct with Firestore tags for ProfileURL, ProfileStatus, Chaincode, DiscordID, and UpdatedAt fields for unified user data representation.

Sequence Diagram(s)

sequenceDiagram
    participant Main as main()
    participant Utils as utils.InitializeLambdaWithFirestore
    participant Lambda as lambda.Start
    participant Handler as handler()
    participant Deps as *utils.Deps

    Note over Main,Handler: New Architecture

    Main->>Utils: InitializeLambdaWithFirestore("service-name", handlerFunc)
    Utils->>Utils: Create background context
    Utils->>Utils: Initialize Firestore client
    Utils->>Deps: Construct Deps{Client, Ctx}
    Utils->>Lambda: Create wrapper & lambda.Start(wrapped)
    
    Lambda->>Handler: Invoke with wrapped request
    Handler->>Deps: Access d.Client & d.Ctx
    Handler->>Handler: Process request
    Handler-->>Lambda: Return response, error
    Lambda-->>Main: Complete
Loading
sequenceDiagram
    participant Handler as handler()
    participant WorkerPool as WorkerPool
    participant Worker as worker goroutine
    participant Job as callProfile/healthCheck

    Note over Handler,Job: Concurrency Pattern Change (e.g., call-profiles)

    Handler->>WorkerPool: NewWorkerPool(numWorkers, queueSize)
    loop For each Firestore doc
        Handler->>WorkerPool: Submit(job)
        WorkerPool->>WorkerPool: Enqueue job to channel
    end
    
    Worker->>Worker: Recover from panic
    Worker->>Job: Execute job
    Job-->>Worker: Complete/error
    Worker->>Worker: Continue polling

    Handler->>WorkerPool: Wait()
    WorkerPool->>WorkerPool: Close job channel (sync.Once)
    WorkerPool->>Worker: Workers drain & exit
    Worker-->>WorkerPool: Done
    WorkerPool-->>Handler: All jobs complete
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Multiple heterogeneous refactorings: Four separate Lambda handlers refactored with interconnected dependencies and patterns (handler signature, initialization, concurrency model changes).
  • New utility modules with logic: Logging system with JSON encoding, worker pool with panic recovery, error mapping, HTTP timeout handling, and Firestore data parsing—each requiring separate validation.
  • Concurrency model change: Migration from explicit sync.WaitGroup to WorkerPool abstraction across multiple services; requires verification of job submission, wait semantics, and panic recovery behavior.
  • Error propagation changes: Firestore operations shifted from log.Fatalf to explicit error returns; impacts control flow in handlers (e.g., call-profiles iteration failure path).
  • Data structure integration: New utils.User struct with Firestore tags propagated across multiple handlers; requires verification of field mapping and validation logic.

Areas requiring extra attention:

  • WorkerPool implementation (layer/utils/concurrency.go): Verify sync.Once usage for safe shutdown, panic recovery in workers, and that Wait() properly drains the job channel.
  • Firestore data extraction (layer/utils/firestore.go, handler files): Ensure doc.DataTo(&user) correctly deserializes and that field existence/type checks are comprehensive (especially profileURL, chaincode validation).
  • HTTP timeout handling: Confirm utils.GetWithContext and utils.PostWithContext enforce timeouts correctly and don't leak goroutines on timeout.
  • Error mapping (layer/utils/errors.go): Validate that HandleLambdaError produces correct HTTP status codes for all error types across different services.
  • Centralized logging: Verify that log levels and structured fields are correctly applied throughout handlers and utility functions.

Possibly related PRs

  • fix: added emulator tests for all the modules #243: Directly related refactor modifying handler signatures and dependency wiring across the same service main files (call-profile, call-profiles, health-check, verify), suggesting coordinated architectural migration.

Suggested reviewers

  • vinit717
  • vinit-flx

Poem

🐰 A refactor's tale, told by a hare...

Dependencies bundled with care,
Workers pooled without a WaitGroup snare,
Logging flows like JSON through the air,
Lambda boots with helpers beyond compare,
One function to rule them all, if you dare! 🚀

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.27% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor: all lambdas' is clearly related to the changeset, which comprehensively refactors all Lambda functions across multiple files to use a unified dependency injection pattern with utils.Deps and centralized initialization.
Description check ✅ Passed The description indicates the PR closes issue #247 and states 'Improved code quality,' which is related to the refactoring work evident in the changeset, though it lacks specific detail about the scope and nature of the refactoring.

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@korbit-ai
Copy link

korbit-ai bot commented Nov 10, 2025

I was unable to write a description for this pull request. This could be because I only found files I can't scan.

Copy link

@korbit-ai korbit-ai bot left a comment

Choose a reason for hiding this comment

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

Review by Korbit AI

Korbit automatically attempts to detect when you fix issues in new commits.
Category Issue Status
Readability Unclear struct name abbreviation ▹ view
Performance HTTP client created per request ▹ view
Performance Context parameter ignored in HTTP request ▹ view
Readability Misleading Function Name ▹ view
Readability Duplicate HTTP Request Setup Logic ▹ view
Files scanned
File Path Reviewed
layer/utils/handler.go
layer/utils/auth.go
layer/utils/http.go
layer/utils/concurrency.go
layer/utils/errors.go
layer/utils/constants.go
call-profiles/main.go
health-check/main.go
verify/main.go
layer/utils/logger.go
call-profile/main.go
layer/utils/firestore.go

Explore our documentation to understand the languages and file types we support and the files we ignore.

Check out our docs on how you can make Korbit work best for you and your team.

Loving Korbit!? Share us on LinkedIn Reddit and X

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: 12

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 68a6049 and 2759f19.

📒 Files selected for processing (17)
  • call-profile/main.go (4 hunks)
  • call-profile/main_test.go (5 hunks)
  • call-profiles/main.go (4 hunks)
  • call-profiles/main_test.go (1 hunks)
  • health-check/main.go (2 hunks)
  • health-check/main_test.go (2 hunks)
  • layer/utils/auth.go (1 hunks)
  • layer/utils/concurrency.go (1 hunks)
  • layer/utils/constants.go (1 hunks)
  • layer/utils/errors.go (1 hunks)
  • layer/utils/firestore.go (5 hunks)
  • layer/utils/handler.go (1 hunks)
  • layer/utils/http.go (1 hunks)
  • layer/utils/logger.go (1 hunks)
  • verify/helpers_test.go (1 hunks)
  • verify/main.go (4 hunks)
  • verify/main_test.go (10 hunks)
🧰 Additional context used
🧬 Code graph analysis (12)
layer/utils/firestore.go (6)
layer/utils/constants.go (4)
  • Res (18-31)
  • Constants (63-83)
  • User (55-61)
  • Log (11-16)
layer/utils/validation.go (1)
  • DiffToRes (32-47)
layer/utils/logger.go (1)
  • LogWarnWithError (133-135)
layer/utils/http.go (2)
  • CreateHTTPClient (12-19)
  • DoRequestWithContext (21-23)
layer/utils/logging.go (1)
  • LogProfileSkipped (29-44)
layer/utils/errors.go (1)
  • NewProfileError (36-42)
health-check/main_test.go (1)
layer/utils/handler.go (1)
  • Deps (12-15)
health-check/main.go (5)
layer/utils/logger.go (1)
  • GetLogger (117-119)
layer/utils/http.go (1)
  • GetWithContext (43-58)
layer/utils/handler.go (2)
  • Deps (12-15)
  • InitializeLambdaWithFirestore (19-41)
layer/utils/concurrency.go (1)
  • NewWorkerPool (30-50)
layer/utils/constants.go (1)
  • User (55-61)
call-profile/main.go (7)
layer/utils/handler.go (2)
  • Deps (12-15)
  • InitializeLambdaWithFirestore (19-41)
layer/utils/constants.go (2)
  • User (55-61)
  • Diff (33-49)
layer/utils/logging.go (2)
  • LogProfileSkipped (29-44)
  • LogHealth (46-61)
layer/utils/firestore.go (2)
  • SetProfileStatusBlocked (76-127)
  • Getdata (132-241)
layer/utils/http.go (1)
  • GetWithContext (43-58)
layer/utils/validation.go (1)
  • DiffToRes (32-47)
layer/utils/errors.go (2)
  • ProfileError (19-23)
  • HandleProfileSkippedError (65-70)
layer/utils/handler.go (2)
layer/utils/logger.go (1)
  • GetLogger (117-119)
layer/utils/firestore.go (1)
  • InitializeFirestoreClient (24-37)
layer/utils/auth.go (1)
layer/utils/logger.go (1)
  • LogError (137-139)
layer/utils/concurrency.go (1)
layer/utils/logger.go (1)
  • GetLogger (117-119)
call-profiles/main_test.go (1)
layer/utils/handler.go (1)
  • Deps (12-15)
verify/main.go (4)
layer/utils/http.go (1)
  • PostWithContext (25-41)
layer/utils/handler.go (2)
  • Deps (12-15)
  • InitializeLambdaWithFirestore (19-41)
layer/utils/firestore.go (3)
  • GetUserIdFromBody (262-270)
  • GetUserData (276-329)
  • SetProfileStatus (334-354)
layer/utils/logging.go (1)
  • LogVerification (63-88)
verify/main_test.go (1)
layer/utils/handler.go (1)
  • Deps (12-15)
call-profile/main_test.go (1)
layer/utils/handler.go (1)
  • Deps (12-15)
call-profiles/main.go (3)
layer/utils/logger.go (1)
  • GetLogger (117-119)
layer/utils/handler.go (2)
  • Deps (12-15)
  • InitializeLambdaWithFirestore (19-41)
layer/utils/concurrency.go (1)
  • NewWorkerPool (30-50)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: run_tests
🔇 Additional comments (4)
layer/utils/auth.go (1)

49-52: LGTM: Proper migration to structured logging.

The change replaces direct logging with centralized structured error logging, providing better observability with structured fields for function name and parameter name.

verify/helpers_test.go (1)

213-213: LGTM: Test updated to use context-first API.

The change correctly passes context.Background() as the first parameter to the verify function, aligning with the refactored context-aware signature.

health-check/main_test.go (1)

400-404: LGTM: Test properly migrated to public Deps API.

The test correctly constructs dependencies using the public utils.Deps type and invokes the handler with the new signature handler(d, request). This aligns with the centralized dependency injection pattern.

call-profiles/main_test.go (1)

305-309: LGTM: Test properly migrated to public Deps API.

The test correctly constructs dependencies using &utils.Deps{ Client: client, Ctx: ctx } and invokes the handler with the updated signature. Consistent with the broader refactoring effort.

Copy link
Contributor

@prakashchoudhary07 prakashchoudhary07 left a comment

Choose a reason for hiding this comment

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

As discussed, the changes will be made in next PR by @lakshayman

@prakashchoudhary07 prakashchoudhary07 merged commit 44fbfc8 into develop Nov 11, 2025
3 checks passed
@prakashchoudhary07 prakashchoudhary07 deleted the refactor-all-lambdas branch November 11, 2025 07:24
@korbit-ai
Copy link

korbit-ai bot commented Nov 11, 2025

I was unable to write a description for this pull request. This could be because I only found files I can't scan.

@vinit717 vinit717 mentioned this pull request Nov 25, 2025
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.

3 participants