Skip to content

chore: use any over interface{} - #79

Merged
indrasaputra merged 1 commit into
mainfrom
use-any
Nov 8, 2025
Merged

chore: use any over interface{}#79
indrasaputra merged 1 commit into
mainfrom
use-any

Conversation

@indrasaputra

@indrasaputra indrasaputra commented Nov 8, 2025

Copy link
Copy Markdown
Owner

User description

Summary

use any over interface{}

Description

use any over interface{}


PR Type

Enhancement


Description

  • Replace interface{} with any keyword throughout codebase

  • Update function signatures in database, gRPC, and auth packages

  • Modernize Go code to use Go 1.18+ syntax conventions


Diagram Walkthrough

flowchart LR
  A["interface{} usage"] -- "replaced with" --> B["any keyword"]
  B -- "applied to" --> C["Database functions"]
  B -- "applied to" --> D["gRPC handlers"]
  B -- "applied to" --> E["Auth & test utilities"]
Loading

File Walkthrough

Relevant files
Enhancement
db.go
Update database function signatures to use any                     

pkg/sdk/database/postgres/db.go

  • Replace interface{} with any in Exec() method signature
  • Replace interface{} with any in Query() method signature
  • Replace interface{} with any in QueryRow() method signature
+3/-3     
server.go
Update gRPC recovery handler to use any                                   

pkg/sdk/grpc/server/server.go

  • Replace interface{} with any in recoveryHandler() parameter type
+1/-1     
login_test.go
Update test helper JSON comparison variables                         

service/auth/features/login_test.go

  • Replace interface{} with any for expected variable declaration
  • Replace interface{} with any for actual variable declaration
+2/-2     
auth.go
Update JWT token parser callback signature                             

service/auth/pkg/sdk/auth/auth.go

  • Replace interface{} with any in JWT token parsing callback function
    return type
+1/-1     
user_test.go
Update test helper JSON comparison variables                         

service/user/features/user_test.go

  • Replace interface{} with any for expected variable declaration
  • Replace interface{} with any for actual variable declaration
+2/-2     

Summary by CodeRabbit

  • Refactor
    • Updated internal type annotations to use Go's modern standard library conventions. No functional changes or user-facing impact.

@sourcery-ai

sourcery-ai Bot commented Nov 8, 2025

Copy link
Copy Markdown
Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Replace all occurrences of interface{} with the Go 1.18 alias any to modernize the codebase, updating function signatures, variable declarations, and callback return types across database, tests, gRPC server, and JWT parsing logic.

Class diagram for updated function signatures using 'any' instead of 'interface{}'

classDiagram
class TxDB {
  +Exec(ctx context.Context, sql string, args ...any) pgconn.CommandTag
  +Query(ctx context.Context, sql string, args ...any) pgx.Rows
  +QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}

class recoveryHandler {
  +recoveryHandler(p any) error
}

class ParseToken {
  +ParseToken(tokenString string, secret []byte) (*entity.Claims, error)
}

class jwtParseWithClaimsCallback {
  +func(token *jwt.Token) (any, error)
}
Loading

File-Level Changes

Change Details Files
Update database transaction methods to use any for variadic args
  • Changed Exec signature to use args ...any
  • Changed Query signature to use args ...any
  • Changed QueryRow signature to use args ...any
pkg/sdk/database/postgres/db.go
Use any instead of interface{} in JSON deepCompare tests
  • Replaced var expected interface{} with var expected any
  • Replaced var actual interface{} with var actual any
service/auth/features/login_test.go
service/user/features/user_test.go
Change recovery handler parameter type to any
  • Updated recoveryHandler parameter from p interface{} to p any
pkg/sdk/grpc/server/server.go
Adjust JWT parsing callback to return any
  • Modified jwt.ParseWithClaims callback to return (any, error) instead of (interface{}, error)
service/auth/pkg/sdk/auth/auth.go

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai

coderabbitai Bot commented Nov 8, 2025

Copy link
Copy Markdown

Walkthrough

Replaced interface{} with the any type alias across method signatures and variable declarations in database, gRPC server, and authentication service modules. All changes are type substitutions with no behavioral, control flow, or error handling modifications.

Changes

Cohort / File(s) Summary
Database transaction methods
pkg/sdk/database/postgres/db.go
Updated variadic parameter type from ...interface{} to ...any in three TxDB methods: Exec, Query, and QueryRow.
gRPC server handler
pkg/sdk/grpc/server/server.go
Changed recoveryHandler signature to use any instead of interface{} for the recovered value type.
Authentication service
service/auth/pkg/sdk/auth/auth.go
Updated jwt.ParseWithClaims key function callback return type from (interface{}, error) to (any, error) in ParseToken.
Test utilities
service/auth/features/login_test.go, service/user/features/user_test.go
Replaced local variable types from interface{} to any in deepCompareJSON helper functions.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

  • Homogeneous refactoring pattern applied uniformly across all files
  • Type alias substitution with zero semantic changes
  • No logic, control flow, or error handling modifications
  • Quick verification that all variadic signatures and variable declarations are consistently updated

Poem

🐰✨ A hoppy refactor, so neat and so clean,
From interface{} we've made a switch—now any's seen!
No logic was broken, just aliases aligned,
The code still hops forward with types redefined! 🎉

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'chore: use any over interface{}' clearly and concisely summarizes the main change—replacing interface{} with the any keyword throughout the codebase.
Description check ✅ Passed The pull request description provides a comprehensive overview with clear sections (Summary, Description, Diagram, File Walkthrough) that explain the changes across multiple packages, exceeding the basic template requirements.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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 use-any

📜 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 fa267bc and 0715feb.

📒 Files selected for processing (5)
  • pkg/sdk/database/postgres/db.go (1 hunks)
  • pkg/sdk/grpc/server/server.go (1 hunks)
  • service/auth/features/login_test.go (1 hunks)
  • service/auth/pkg/sdk/auth/auth.go (1 hunks)
  • service/user/features/user_test.go (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
service/auth/pkg/sdk/auth/auth.go (1)
service/auth/entity/auth.go (1)
  • Claims (28-33)
⏰ 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). (14)
  • GitHub Check: Go code quality check / Unit test and coverage
  • GitHub Check: Go code quality check / Semgrep scan
  • GitHub Check: Go code quality check / Lint import block
  • GitHub Check: Go code quality check / Download go module
  • GitHub Check: Go code quality check / go-code-lint
  • GitHub Check: Go code quality check / go-code-lint
  • GitHub Check: Go code quality check / Unit test and coverage
  • GitHub Check: Go code quality check / Unit test and coverage
  • GitHub Check: Go code quality check / go-code-lint
  • GitHub Check: Go code quality check / go-code-lint
  • GitHub Check: Go code quality check / Unit test and coverage
  • GitHub Check: Go code quality check / Unit test and coverage
  • GitHub Check: Go code quality check / go-code-lint
  • GitHub Check: Sourcery review
🔇 Additional comments (5)
service/user/features/user_test.go (1)

204-205: LGTM! Modern Go idiom.

The use of any over interface{} aligns with modern Go conventions (Go 1.18+) and improves readability without any behavioral change.

pkg/sdk/grpc/server/server.go (1)

201-201: LGTM! Consistent type modernization.

The signature update to use any is appropriate and maintains full compatibility while following current Go best practices.

service/auth/features/login_test.go (1)

175-176: LGTM! Consistent modernization across test files.

The type alias change maintains consistency with similar updates in other test files (e.g., service/user/features/user_test.go).

service/auth/pkg/sdk/auth/auth.go (1)

66-66: LGTM! JWT callback signature modernized.

The callback return type update is correct and aligns with modern Go conventions while maintaining full compatibility with the JWT library.

pkg/sdk/database/postgres/db.go (1)

84-96: LGTM! Database method signatures modernized.

All three method signatures (Exec, Query, QueryRow) correctly updated to use any for variadic parameters. This maintains full backward compatibility while aligning with modern Go conventions and pgx library patterns.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (2.5.0)

level=warning msg="[linters_context] running gomodguard failed: unable to read module file go.mod: current working directory must have a go.mod file: if you are not using go modules it is suggested to disable this linter"
level=error msg="[linters_context] typechecking error: pattern ./...: directory prefix . does not contain modules listed in go.work or their selected dependencies"


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.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey there - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@qodo-code-review

qodo-code-review Bot commented Nov 8, 2025

Copy link
Copy Markdown

PR Compliance Guide 🔍

(Compliance updated until commit 0715feb)

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status: Passed

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
Logging Context: The changes only replace interface{} with any and do not add or remove any audit logging,
so it is unclear from this diff whether critical actions are properly logged.

Referred Code
func defaultStreamServerInterceptors(logger *slog.Logger, cfg *Config) []grpc.StreamServerInterceptor {
	opts := []logging.Option{logging.WithLogOnEvents(logging.StartCall, logging.FinishCall)}

	// Note: Idempotency interceptor is typically only used for unary requests,
	// not streaming requests, as streaming doesn't fit the idempotency pattern well
	return []grpc.StreamServerInterceptor{
		grpcrecovery.StreamServerInterceptor(grpcrecovery.WithRecoveryHandler(recoveryHandler)),
		logging.StreamServerInterceptor(interceptor.SlogLogger(logger), opts...),
		grpc_prometheus.StreamServerInterceptor,
		selector.StreamServerInterceptor(auth.StreamServerInterceptor(interceptor.AuthBasic(cfg.Username, cfg.Password)), selector.MatchFunc(interceptor.ApplyMethod(cfg.AppliedBasicAuthMethods...))),
		selector.StreamServerInterceptor(auth.StreamServerInterceptor(interceptor.AuthBearer(cfg.Secret)), selector.MatchFunc(interceptor.ApplyMethod(cfg.AppliedBearerAuthMethods...))),
	}
}

func recoveryHandler(p any) error {
	return status.Errorf(codes.Unknown, "%v", p)
}
Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status:
Log Sensitivity: No new logging of sensitive data is introduced in this diff, but the change does not
provide evidence that logs are structured and free of sensitive data across affected
paths.

Referred Code
func defaultStreamServerInterceptors(logger *slog.Logger, cfg *Config) []grpc.StreamServerInterceptor {
	opts := []logging.Option{logging.WithLogOnEvents(logging.StartCall, logging.FinishCall)}

	// Note: Idempotency interceptor is typically only used for unary requests,
	// not streaming requests, as streaming doesn't fit the idempotency pattern well
	return []grpc.StreamServerInterceptor{
		grpcrecovery.StreamServerInterceptor(grpcrecovery.WithRecoveryHandler(recoveryHandler)),
		logging.StreamServerInterceptor(interceptor.SlogLogger(logger), opts...),
		grpc_prometheus.StreamServerInterceptor,
		selector.StreamServerInterceptor(auth.StreamServerInterceptor(interceptor.AuthBasic(cfg.Username, cfg.Password)), selector.MatchFunc(interceptor.ApplyMethod(cfg.AppliedBasicAuthMethods...))),
		selector.StreamServerInterceptor(auth.StreamServerInterceptor(interceptor.AuthBearer(cfg.Secret)), selector.MatchFunc(interceptor.ApplyMethod(cfg.AppliedBearerAuthMethods...))),
	}
Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Token Parsing: The change to use any in jwt.ParseWithClaims maintains prior behavior, but the diff does
not show validation/sanitization beyond signing method checks, requiring broader context
to verify secure handling of inputs.

Referred Code
func ParseToken(tokenString string, secret []byte) (*entity.Claims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &entity.Claims{}, func(token *jwt.Token) (any, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, entity.ErrInvalidArgument("unexpected signing method")
		}
		return secret, nil
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

Previous compliance checks

Compliance check up to commit 0715feb
Security Compliance
Panic detail leakage

Description: The recovery handler converts any panic value to an error string without sanitization,
which may leak sensitive panic details to clients in production; consider returning a
generic message and logging details server-side.
server.go [201-203]

Referred Code
func recoveryHandler(p any) error {
	return status.Errorf(codes.Unknown, "%v", p)
}
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
No auditing: New/modified functions execute database and gRPC operations without added audit logging of
critical actions in this diff.

Referred Code
func defaultStreamServerInterceptors(logger *slog.Logger, cfg *Config) []grpc.StreamServerInterceptor {
	opts := []logging.Option{logging.WithLogOnEvents(logging.StartCall, logging.FinishCall)}

	// Note: Idempotency interceptor is typically only used for unary requests,
	// not streaming requests, as streaming doesn't fit the idempotency pattern well
	return []grpc.StreamServerInterceptor{
		grpcrecovery.StreamServerInterceptor(grpcrecovery.WithRecoveryHandler(recoveryHandler)),
		logging.StreamServerInterceptor(interceptor.SlogLogger(logger), opts...),
		grpc_prometheus.StreamServerInterceptor,
		selector.StreamServerInterceptor(auth.StreamServerInterceptor(interceptor.AuthBasic(cfg.Username, cfg.Password)), selector.MatchFunc(interceptor.ApplyMethod(cfg.AppliedBasicAuthMethods...))),
		selector.StreamServerInterceptor(auth.StreamServerInterceptor(interceptor.AuthBearer(cfg.Secret)), selector.MatchFunc(interceptor.ApplyMethod(cfg.AppliedBearerAuthMethods...))),
	}
}

func recoveryHandler(p any) error {
	return status.Errorf(codes.Unknown, "%v", p)
}
Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Generic recovery: The recovery handler returns a generic Unknown status without contextual details which may
limit actionable debugging information.

Referred Code
func recoveryHandler(p any) error {
	return status.Errorf(codes.Unknown, "%v", p)
}

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Simplify claims parsing and error handling

Refactor the ParseToken function to simplify claims parsing by removing a
redundant type assertion and improve error handling by checking for specific
token validation errors.

service/auth/pkg/sdk/auth/auth.go [66-78]

-	token, err := jwt.ParseWithClaims(tokenString, &entity.Claims{}, func(token *jwt.Token) (any, error) {
+	claims := &entity.Claims{}
+	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (any, error) {
 		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
 			return nil, entity.ErrInvalidArgument("unexpected signing method")
 		}
 		return secret, nil
 	})
 	if err != nil {
+		if errors.Is(err, jwt.ErrTokenExpired) {
+			return nil, entity.ErrTokenExpired()
+		}
 		return nil, err
 	}
-	if claims, ok := token.Claims.(*entity.Claims); ok {
-		return claims, nil
+	if !token.Valid {
+		return nil, entity.ErrInvalidToken()
 	}
-	return nil, entity.ErrInternal("unknown claims type")
+	return claims, nil
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies redundant code and improves error handling by checking for specific token errors, making the function more robust and easier to understand.

Medium
Avoid code duplication in tests

Refactor the duplicated deepCompareJSON function from test files into a single,
shared test utility package to improve code reuse and maintainability.

service/auth/features/login_test.go [174-191]

-func deepCompareJSON(want, have []byte) error {
+// In a new shared test utility package, e.g., `internal/testutil/json.go`
+package testutil
+
+import (
+	"encoding/json"
+	"fmt"
+	"reflect"
+)
+
+func DeepCompareJSON(want, have []byte) error {
 	var expected any
 	var actual any
 
-	err := json.Unmarshal(want, &expected)
-	if err != nil {
-		return err
+	if err := json.Unmarshal(want, &expected); err != nil {
+		return fmt.Errorf("failed to unmarshal expected json: %w", err)
 	}
-	err = json.Unmarshal(have, &actual)
-	if err != nil {
-		return err
+	if err := json.Unmarshal(have, &actual); err != nil {
+		return fmt.Errorf("failed to unmarshal actual json: %w", err)
 	}
 
 	if !reflect.DeepEqual(expected, actual) {
 		return fmt.Errorf("expected JSON does not match actual, %v vs. %v", expected, actual)
 	}
 	return nil
 }
 
+// In service/auth/features/login_test.go, replace the original function with a call to the new shared function.
+// e.g., import "github.com/indrasaputra/arjuna/internal/testutil"
+// ...
+// return testutil.DeepCompareJSON(want, have)
+

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 5

__

Why: The suggestion correctly identifies duplicated test code and proposes a valid refactoring to a shared utility, which improves maintainability by adhering to the DRY principle.

Low
  • More

@codecov

codecov Bot commented Nov 8, 2025

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 58.63%. Comparing base (fa267bc) to head (0715feb).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
service/auth/pkg/sdk/auth/auth.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main      #79   +/-   ##
=======================================
  Coverage   58.63%   58.63%           
=======================================
  Files          58       58           
  Lines        1987     1987           
=======================================
  Hits         1165     1165           
  Misses        788      788           
  Partials       34       34           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@indrasaputra
indrasaputra merged commit 779ff31 into main Nov 8, 2025
103 of 104 checks passed
@indrasaputra
indrasaputra deleted the use-any branch November 8, 2025 09:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant