Skip to content

backend/enh/added-callBecknAPIWithLogging#1227

Open
H-C-21 wants to merge 1 commit into
mainfrom
backend/enh/added-callBecknAPIWithLogging
Open

backend/enh/added-callBecknAPIWithLogging#1227
H-C-21 wants to merge 1 commit into
mainfrom
backend/enh/added-callBecknAPIWithLogging

Conversation

@H-C-21
Copy link
Copy Markdown
Contributor

@H-C-21 H-C-21 commented Apr 22, 2026

Summary by CodeRabbit

  • New Features
    • Added logging and monitoring capability for API calls with Kafka integration, enabling enhanced visibility and observability of internal API interactions.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 22, 2026

Walkthrough

A new function callBecknAPIWithLogging is introduced that wraps the existing callBecknAPI call with asynchronous logging and Kafka event publishing capabilities. The function captures API results—both successful responses and exceptions—converts them to text, logs them for debugging, and publishes them to Kafka. The module Kernel.Utils.Common is updated to re-export this new function.

Changes

Cohort / File(s) Summary
BecknAPI Logging Integration
lib/mobility-core/src/Kernel/Utils/Error/BaseError/HTTPError/BecknAPIError.hs
Added imports for Kafka producer support and text encoding utilities. Introduced new exported function callBecknAPIWithLogging that wraps callBecknAPI with try-fork-rethrow pattern: executes API call, forks async block to convert result to text, logs via debug, publishes to Kafka via pushInternalApiCallDataToKafkaWithTextEncodedResp, then rethrows any exceptions.
Common Exports
lib/mobility-core/src/Kernel/Utils/Common.hs
Updated import statement to re-export callBecknAPIWithLogging alongside existing callBecknAPI from the BecknAPIError module.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant callBecknAPIWithLogging
    participant callBecknAPI
    participant AsyncLogger as Async Logger
    participant Kafka
    participant TextEncoder as Text Encoder

    Caller->>callBecknAPIWithLogging: callBecknAPIWithLogging(params)
    callBecknAPIWithLogging->>callBecknAPI: try callBecknAPI(params)
    
    alt Success Path
        callBecknAPI-->>callBecknAPIWithLogging: Success (res)
        callBecknAPIWithLogging->>AsyncLogger: fork async block
    else Exception Path
        callBecknAPI-->>callBecknAPIWithLogging: Exception
        callBecknAPIWithLogging->>AsyncLogger: fork async block
    end
    
    AsyncLogger->>TextEncoder: encodeToText(result/exception)
    TextEncoder-->>AsyncLogger: Text representation
    AsyncLogger->>AsyncLogger: debug log
    AsyncLogger->>Kafka: pushInternalApiCallDataToKafka(action, source, entityId, req, resText)
    Kafka-->>AsyncLogger: Published
    
    callBecknAPIWithLogging->>callBecknAPIWithLogging: either throwM return
    alt Exception Case
        callBecknAPIWithLogging-->>Caller: throwM exception
    else Success Case
        callBecknAPIWithLogging-->>Caller: return res
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A little rabbit logs with care,
Every API call through the air!
To Kafka's stream both wins and fails,
Async whispers tell the tales,
No exception left unseen,
In the logging in-between! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: adding a new function callBecknAPIWithLogging to the codebase.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch backend/enh/added-callBecknAPIWithLogging

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.

Copy link
Copy Markdown

@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

🧹 Nitpick comments (1)
lib/mobility-core/src/Kernel/Utils/Error/BaseError/HTTPError/BecknAPIError.hs (1)

81-91: Three adjacent Text / Maybe Text parameters are easy to mix up at call sites.

action :: Text, source :: Text, and entityId :: Maybe Text are positional and semantically similar, so callers can silently swap action and source with no type error. Given this helper is intended for broad use (re-exported via Kernel.Utils.Common), consider introducing a small record (e.g. BecknCallLogCtx { action, source, entityId }) or at minimum naming the parameters in the Haddock, to reduce the risk of misrouted Kafka/log data.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@lib/mobility-core/src/Kernel/Utils/Error/BaseError/HTTPError/BecknAPIError.hs`
around lines 81 - 91, The function callBecknAPIWithLogging currently takes three
adjacent positional Text/Maybe Text parameters (action, source, entityId) that
are easy to mix up; define a small record type (e.g. BecknCallLogCtx with fields
action :: Text, source :: Text, entityId :: Maybe Text), change the
callBecknAPIWithLogging signature to take BecknCallLogCtx instead of those three
parameters, update all call sites to construct the record (using record field
names so arguments are explicit), and adjust any re-exports or Haddock to
document the new record; ensure pattern matches/uses inside
callBecknAPIWithLogging are updated to access ctx.action, ctx.source,
ctx.entityId.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@lib/mobility-core/src/Kernel/Utils/Error/BaseError/HTTPError/BecknAPIError.hs`:
- Around line 91-97: The current callBecknAPIWithLogging collapses success and
exception into a plain Text (resText) which prevents consumers from
distinguishing outcomes and breaks JSON parsers; change it to build a small
structured wrapper (e.g. {status: "success" | "error", payload: <response JSON
or error string>}) and KUT.encodeToText that wrapper before calling
pushInternalApiCallDataToKafkaWithTextEncodedResp and in logDebug, so callers of
pushInternalApiCallDataToKafkaWithTextEncodedResp and readers of
Internal-API-Call-Logs can unambiguously detect success vs failure and safely
parse JSON; use the existing identifiers callBecknAPIWithLogging, result,
pushInternalApiCallDataToKafkaWithTextEncodedResp and KUT.encodeToText to locate
and implement the change.

---

Nitpick comments:
In
`@lib/mobility-core/src/Kernel/Utils/Error/BaseError/HTTPError/BecknAPIError.hs`:
- Around line 81-91: The function callBecknAPIWithLogging currently takes three
adjacent positional Text/Maybe Text parameters (action, source, entityId) that
are easy to mix up; define a small record type (e.g. BecknCallLogCtx with fields
action :: Text, source :: Text, entityId :: Maybe Text), change the
callBecknAPIWithLogging signature to take BecknCallLogCtx instead of those three
parameters, update all call sites to construct the record (using record field
names so arguments are explicit), and adjust any re-exports or Haddock to
document the new record; ensure pattern matches/uses inside
callBecknAPIWithLogging are updated to access ctx.action, ctx.source,
ctx.entityId.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c639be19-33f4-43d7-967b-1a497c643963

📥 Commits

Reviewing files that changed from the base of the PR and between f1a5009 and 93afc0c.

📒 Files selected for processing (2)
  • lib/mobility-core/src/Kernel/Utils/Common.hs
  • lib/mobility-core/src/Kernel/Utils/Error/BaseError/HTTPError/BecknAPIError.hs

Comment on lines +91 to +97
callBecknAPIWithLogging mbManagerSelector errorCodeMb action source entityId api baseUrl internalEndPointHashMap req = do
result <- try $ callBecknAPI mbManagerSelector errorCodeMb action api baseUrl internalEndPointHashMap req
fork ("Logging Beckn API call: " <> action) $ do
let resText = either (show :: SomeException -> Text) KUT.encodeToText result
logDebug $ "Beckn API call " <> action <> " result: " <> resText
pushInternalApiCallDataToKafkaWithTextEncodedResp action source entityId (Just req) resText
either throwM return result
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Kafka payload does not distinguish success from failure.

On Line 94, both a successful res (JSON-encoded via KUT.encodeToText) and a SomeException (rendered via show) are collapsed into a single Text that is pushed to Kafka and written to the debug log. Downstream consumers of the Internal-API-Call-Logs topic have no structured way to tell whether a given record represents a 2xx response or an upstream failure, and exception show output is not valid JSON, so any consumer trying to parse the field as JSON will break on the error path.

Consider tagging the outcome explicitly before encoding, e.g.:

🛠️ Suggested change
-  fork ("Logging Beckn API call: " <> action) $ do
-    let resText = either (show :: SomeException -> Text) KUT.encodeToText result
-    logDebug $ "Beckn API call " <> action <> " result: " <> resText
-    pushInternalApiCallDataToKafkaWithTextEncodedResp action source entityId (Just req) resText
+  fork ("Logging Beckn API call: " <> action) $ do
+    let resText = case result of
+          Right res -> KUT.encodeToText (Right res :: Either Text res)
+          Left (e :: SomeException) -> KUT.encodeToText (Left (show e) :: Either Text res)
+    logDebug $ "Beckn API call " <> action <> " result: " <> resText
+    pushInternalApiCallDataToKafkaWithTextEncodedResp action source entityId (Just req) resText
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@lib/mobility-core/src/Kernel/Utils/Error/BaseError/HTTPError/BecknAPIError.hs`
around lines 91 - 97, The current callBecknAPIWithLogging collapses success and
exception into a plain Text (resText) which prevents consumers from
distinguishing outcomes and breaks JSON parsers; change it to build a small
structured wrapper (e.g. {status: "success" | "error", payload: <response JSON
or error string>}) and KUT.encodeToText that wrapper before calling
pushInternalApiCallDataToKafkaWithTextEncodedResp and in logDebug, so callers of
pushInternalApiCallDataToKafkaWithTextEncodedResp and readers of
Internal-API-Call-Logs can unambiguously detect success vs failure and safely
parse JSON; use the existing identifiers callBecknAPIWithLogging, result,
pushInternalApiCallDataToKafkaWithTextEncodedResp and KUT.encodeToText to locate
and implement the change.

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