Skip to content

Conversation

@GHkrishna
Copy link
Contributor

@GHkrishna GHkrishna commented Nov 10, 2025

, including passed from headers of http request

Summary by CodeRabbit

  • Refactor

    • Apply a global message interceptor in the agent service and remove its registration from the API gateway.
    • Migrate internal messaging to a unified NATS client wrapper for consistent calls.
    • Move to dependency-injected logging across verification services and controllers.
  • Enhancements

    • Improved correlation ID detection and generation across multiple header formats with added debug logging.
    • Standardized logging and error reporting for clearer diagnostics.

…of http request

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>
@coderabbitai
Copy link

coderabbitai bot commented Nov 10, 2025

Walkthrough

This PR moves NATS interception from global interceptor usage to a NATSClient wrapper, adds DI-based Logger usage, enhances context ID resolution across headers with logging, and updates module providers/imports (including MICRO_SERVICE_NAME, Prisma, and Config changes).

Changes

Cohort / File(s) Summary
NATS interceptor wiring
apps/agent-service/src/agent-service.module.ts, apps/api-gateway/src/main.ts
Added global APP_INTERCEPTOR binding for NatsInterceptor in agent-service; removed NatsInterceptor import and app.useGlobalInterceptors(...) call from api-gateway bootstrap.
NATSClient integration
apps/oid4vc-verification/src/oid4vc-verification.service.ts
Replaced local pattern-based _natsCall usage with NATSClient.sendNatsMessage(...); injected NATSClient into constructor; removed internal natsCall helper and adjusted imports.
Logger DI changes
apps/oid4vc-verification/src/oid4vc-verification.controller.ts, apps/api-gateway/src/oid4vc-verification/oid4vc-verification.service.ts, apps/api-gateway/src/oid4vc-verification/oid4vc-verification.controller.ts
Switched to DI-provided Logger in controller; removed BaseService inheritance and added Logger property in api-gateway service; minor logger instantiation reorder in controller (no behavioral change).
Module provider & config updates
apps/oid4vc-verification/src/oid4vc-verification.module.ts, apps/oid4vc-verification/src/main.ts
Added MICRO_SERVICE_NAME provider, imported PrismaServiceModule, added ConfigModule.forRoot(); removed (commented) global HttpExceptionFilter registration in main.
Context middleware/interceptor enhancements
libs/context/src/contextInterceptorModule.ts, libs/context/src/contextModule.ts
Enhanced context ID resolution to read multiple header variants, generate UUID fallback, wrap generation in try/catch with logging, and add debug logs for chosen/generated IDs.
Logging interceptor cleanup
libs/logger/src/logging.interceptor.ts
Renamed injected logger field _loggerlogger; changed header handling to use headers.get('contextId'), added debug logs for header retrieval and generated context IDs, standardized error logging.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant APIGW as API Gateway
    participant OIDSvc as OID4VC Service
    participant NATS

    Note over Client,APIGW: Old (interceptor-based)
    Client->>APIGW: HTTP request
    APIGW->>APIGW: NatsInterceptor (global) intercepts
    APIGW->>NATS: publish message (interceptor)
    NATS->>OIDSvc: deliver

    Note over Client,OIDSvc: New (service-level NATSClient)
    Client->>APIGW: HTTP request
    APIGW->>OIDSvc: controller -> service
    OIDSvc->>NATS: NATSClient.sendNatsMessage()
    NATS->>OIDSvc: response
    OIDSvc->>Client: HTTP response
Loading
sequenceDiagram
    participant Request
    participant Middleware as Context Middleware
    participant Headers as HTTP Headers
    participant Store as Context Storage

    Request->>Middleware: incoming request
    Middleware->>Headers: check headers (contextid / context-id / contextId / x-correlation-id)
    alt header present
        Headers-->>Middleware: header value
        Middleware->>Store: setContextId(header value)
        Middleware->>Middleware: logger.debug("using header")
    else header absent
        Middleware->>Middleware: generate UUID
        Middleware->>Store: setContextId(new UUID)
        Middleware->>Middleware: logger.debug("generated id")
    end
    Middleware-->>Request: continue
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review NATS pattern -> sendNatsMessage() mapping for correctness and error handling in apps/oid4vc-verification/src/oid4vc-verification.service.ts.
  • Verify Logger DI consistency and constructor signatures across controllers/services.
  • Confirm header resolution priority and logging in libs/context/* and libs/logger/*.
  • Check module import ordering for PrismaServiceModule and ConfigModule.forRoot() to avoid init issues.

Possibly related PRs

Suggested reviewers

  • RinkalBhojani
  • tipusinghaw
  • shitrerohit

Poem

🐰 A hop, a refactor, a tidy new trail,

Logger now listens and headers set sail,
NATS messages routed from service, not sky,
Context IDs found or born with a sigh,
The warren logs softly as changes prevail.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: trace contextId across services' clearly and specifically describes the main objective of the PR: implementing context ID tracing across multiple services.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/contextId-in-logs

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4b26742 and f69bd0a.

📒 Files selected for processing (1)
  • libs/context/src/contextInterceptorModule.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/context/src/contextInterceptorModule.ts

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.

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>
Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>
@GHkrishna
Copy link
Contributor Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Nov 10, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Nitpick comments (1)
apps/api-gateway/src/oid4vc-verification/oid4vc-verification.controller.ts (1)

57-59: Inconsistency: Logger is not dependency-injected.

The AI summary indicates that the Logger should be dependency-injected via the constructor, but the code still shows direct instantiation with private readonly logger = new Logger('Oid4vcVerificationController'). The constructor only injects Oid4vcVerificationService.

For consistency with the broader DI pattern changes in this PR, consider injecting Logger via the constructor:

-  private readonly logger = new Logger('Oid4vcVerificationController');
-
-  constructor(private readonly oid4vcVerificationService: Oid4vcVerificationService) {}
+  constructor(
+    private readonly oid4vcVerificationService: Oid4vcVerificationService,
+    private readonly logger: Logger
+  ) {}

Ensure that Logger is provided in the module's providers array.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e90c021 and 60f0d4a.

📒 Files selected for processing (13)
  • apps/agent-service/src/agent-service.module.ts (3 hunks)
  • apps/api-gateway/src/app.module.ts (2 hunks)
  • apps/api-gateway/src/main.ts (0 hunks)
  • apps/api-gateway/src/oid4vc-verification/oid4vc-verification.controller.ts (1 hunks)
  • apps/api-gateway/src/oid4vc-verification/oid4vc-verification.service.ts (1 hunks)
  • apps/oid4vc-verification/src/main.ts (1 hunks)
  • apps/oid4vc-verification/src/oid4vc-verification.controller.ts (1 hunks)
  • apps/oid4vc-verification/src/oid4vc-verification.module.ts (2 hunks)
  • apps/oid4vc-verification/src/oid4vc-verification.service.ts (7 hunks)
  • libs/common/src/nats.interceptor.ts (1 hunks)
  • libs/context/src/contextInterceptorModule.ts (2 hunks)
  • libs/context/src/contextModule.ts (2 hunks)
  • libs/logger/src/logging.interceptor.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/api-gateway/src/main.ts
🧰 Additional context used
🪛 ESLint
libs/context/src/contextInterceptorModule.ts

[error] 10-10: Expected no linebreak before this expression.

(implicit-arrow-linebreak)

🔇 Additional comments (9)
apps/api-gateway/src/oid4vc-verification/oid4vc-verification.service.ts (1)

2-2: Refactoring from BaseService to direct Logger is correct and contextId propagation is verified.

The removal of BaseService is safe—it only provides a protected logger initialized with a name. The direct Logger instantiation with new Logger('Oid4vcVerificationService') is working correctly.

contextId propagation is handled automatically by NATSClient.sendNatsMessage(), which retrieves the contextId from ContextStorageService and sets it in message headers. No explicit contextId extraction is needed in this service.

Optional improvement: Consider dependency injection for the Logger (rather than new Logger(...)) for better testability, though the current approach is functional.

apps/oid4vc-verification/src/oid4vc-verification.service.ts (1)

35-41: LGTM: Constructor injection properly updated.

The NATSClient is correctly injected via constructor DI. Ensure that NATSClient is provided in the module's providers array (verified in oid4vc-verification.module.ts).

apps/agent-service/src/agent-service.module.ts (2)

26-28: LGTM: Module imports enhanced for logging and context tracking.

The addition of LoggerModule, PlatformConfig, and ContextInterceptorModule aligns with the PR's objective to trace contextId across services.


52-56: LGTM: Global interceptor registration follows NestJS best practices.

The NatsInterceptor is properly registered as a global interceptor using the APP_INTERCEPTOR token. This ensures consistent NATS message interception across the agent service. The NATSClient provider enables dependency injection for NATS messaging operations.

apps/api-gateway/src/app.module.ts (2)

36-37: LGTM: Imports added for global interceptor pattern.

The APP_INTERCEPTOR and NatsInterceptor imports enable consistent NATS message interception across the API gateway service.


82-85: LGTM: Global interceptor registration is consistent.

The NatsInterceptor is registered as a global interceptor using the APP_INTERCEPTOR token, matching the pattern used in other modules (e.g., agent-service.module.ts and oid4vc-verification.module.ts). This ensures uniform context tracking and correlation ID handling across services.

apps/oid4vc-verification/src/oid4vc-verification.controller.ts (1)

11-14: LGTM: Logger properly injected via constructor DI.

The Logger is now dependency-injected via the constructor, replacing the previous in-class instantiation. This aligns with NestJS best practices and the broader DI pattern changes in this PR. Ensure that Logger is provided in the module's providers array (verified in oid4vc-verification.module.ts at line 45).

apps/oid4vc-verification/src/oid4vc-verification.module.ts (2)

21-25: LGTM: Module imports properly configured.

The addition of ConfigModule.forRoot(), ContextInterceptorModule, PlatformConfig, LoggerModule, and CacheModule.register() provides the necessary infrastructure for context tracking, logging, and configuration management across the verification service.


41-55: LGTM: Providers comprehensively configured for DI.

All necessary providers are properly configured:

  • Logger enables dependency-injected logging (used in controller at line 13)
  • NATSClient enables the NATS client wrapper pattern (used in service at line 37)
  • MICRO_SERVICE_NAME provides service identification for logging/tracing
  • APP_INTERCEPTOR with NatsInterceptor ensures consistent NATS message interception

This configuration fully supports the contextId tracing feature across services.

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>
@GHkrishna
Copy link
Contributor Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Nov 11, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

♻️ Duplicate comments (1)
libs/context/src/contextModule.ts (1)

16-18: Remove the redundant contextId header check and fix TypeScript typing.

Line 18 checks req.headers['contextId'] (with capital I), but as noted in the previous review, Express normalizes all header keys to lowercase. This check will never match and serves no purpose. Additionally, the Request type from the global namespace lacks proper typing for the headers property—you should use Express's Request type from @nestjs/common or express.

Apply this diff:

-        idGenerator: (req: Request) => {
+        idGenerator: (req: { headers: Record<string, string | string[] | undefined> }) => {
           // TODO: Check if we want the x-correlation-id or the correlationId
-          const contextIdHeader = req.headers['contextid'] ?? req.headers['context-id'] ?? req.headers['contextId'];
+          const contextIdHeader = req.headers['contextid'] ?? req.headers['context-id'];
           const correlationIdHeader = req.headers['x-correlation-id'];
🧹 Nitpick comments (3)
libs/context/src/contextModule.ts (1)

25-30: Replace console.log with structured logging.

Using console.log bypasses the application's logging infrastructure, making it harder to control log levels, formatting, and output destinations in different environments.

Consider using NestJS Logger instead:

+        idGenerator: (req: { headers: Record<string, string | string[] | undefined> }) => {
+          const logger = new Logger('ContextModule');
           // TODO: Check if we want the x-correlation-id or the correlationId
           const contextIdHeader = req.headers['contextid'] ?? req.headers['context-id'];
           const correlationIdHeader = req.headers['x-correlation-id'];
           let resolvedContextId =
             (Array.isArray(contextIdHeader) ? contextIdHeader[0] : contextIdHeader) ??
             (Array.isArray(correlationIdHeader) ? correlationIdHeader[0] : correlationIdHeader);

           if (resolvedContextId) {
-            // eslint-disable-next-line no-console
-            console.log('ContextId received in request headers::::', resolvedContextId);
+            logger.debug(`ContextId received in request headers: ${resolvedContextId}`);
           } else {
             resolvedContextId = v4();
-            // eslint-disable-next-line no-console
-            console.log('ContextId not received in request headers, generated a new one::::', resolvedContextId);
+            logger.debug(`ContextId not received in request headers, generated a new one: ${resolvedContextId}`);
           }
           return resolvedContextId;
         }
libs/context/src/contextInterceptorModule.ts (2)

23-23: Avoid creating a Logger instance on every request.

Instantiating a new Logger for every RPC call adds unnecessary overhead. Consider declaring it once at module scope or injecting it if possible.

Apply this diff:

+const logger = new Logger('ContextInterceptorModule');
+
 @Global()
 @Module({
   imports: [
     ClsModule.forRoot({
       global: true,
       interceptor: {
         mount: true,

         generateId: true,
         idGenerator: (context: ExecutionContext) => {
           try {
-            const logger = new Logger('ContextInterceptorModule');
             const rpcContext = context.switchToRpc().getContext();

37-40: Replace console.log with structured error logging.

Using console.log for error handling bypasses the application's logging infrastructure and makes it difficult to capture, filter, or alert on these errors in production.

Apply this diff:

           } catch (error) {
-            // eslint-disable-next-line no-console
-            console.log('[idGenerator] Error in idGenerator: ', error);
+            logger.error('[idGenerator] Error in idGenerator: ', error);
+            return uuid(); // Fallback to new UUID on error
           }

Note: You should also return a fallback UUID when an error occurs to prevent returning undefined.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 60f0d4a and 4b26742.

📒 Files selected for processing (3)
  • apps/oid4vc-verification/src/oid4vc-verification.module.ts (2 hunks)
  • libs/context/src/contextInterceptorModule.ts (2 hunks)
  • libs/context/src/contextModule.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/oid4vc-verification/src/oid4vc-verification.module.ts
🧰 Additional context used
🪛 ESLint
libs/context/src/contextInterceptorModule.ts

[error] 10-10: Expected no linebreak before this expression.

(implicit-arrow-linebreak)

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>
@sonarqubecloud
Copy link

@GHkrishna
Copy link
Contributor Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Nov 12, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Contributor

@tipusinghaw tipusinghaw left a comment

Choose a reason for hiding this comment

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

LGTM

@GHkrishna GHkrishna merged commit c382111 into feat/oidc-main-sync Nov 12, 2025
5 checks passed
@GHkrishna GHkrishna deleted the fix/contextId-in-logs branch November 12, 2025 07:52
RinkalBhojani pushed a commit that referenced this pull request Nov 17, 2025
* feat: trace contextId across services, including passed from headers of http request

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>

* fix: import issues caused by merge

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>

* fix: contextId refactoring and coderabbit resolve

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>

* fix: make contextInterceptorModule resilient

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>

---------

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>
tipusinghaw pushed a commit that referenced this pull request Nov 28, 2025
* feat: trace contextId across services, including passed from headers of http request

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>

* fix: import issues caused by merge

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>

* fix: contextId refactoring and coderabbit resolve

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>

* fix: make contextInterceptorModule resilient

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>

---------

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>
RinkalBhojani pushed a commit that referenced this pull request Dec 16, 2025
* feat: trace contextId across services, including passed from headers of http request

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>

* fix: import issues caused by merge

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>

* fix: contextId refactoring and coderabbit resolve

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>

* fix: make contextInterceptorModule resilient

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>

---------

Signed-off-by: Krishna Waske <krishna.waske@ayanworks.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working enhancement Improving existing code or adding enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CLS context ID not consistently applied to logs inside NATS microservices (context not propagated through NATS request pipeline)

3 participants