Skip to content

Refactor ProfileService, MetadataProfileRespurce, MetricProfileResource: Replace String Literals with Constants - #24

Open
gulati-aakriti wants to merge 5 commits into
kruize:mvp_demofrom
gulati-aakriti:bug_fix
Open

Refactor ProfileService, MetadataProfileRespurce, MetricProfileResource: Replace String Literals with Constants#24
gulati-aakriti wants to merge 5 commits into
kruize:mvp_demofrom
gulati-aakriti:bug_fix

Conversation

@gulati-aakriti

@gulati-aakriti gulati-aakriti commented Jun 2, 2026

Copy link
Copy Markdown

Description

Earlier ProfileService was using hard coded messages and now it has been changed to usage from Constants file.

Changes

  • Refactor ProfileService to use shared message constants instead of inline strings for logging, exceptions, and user-facing messages.
  • Introduce new message and error constants in OptimizerConstants for profile installation, loading, and configuration index handling.
  • Add ProfileResponseConstants to centralize parsing of profile-related error messages returned by the Kruize API.

Fixes # (issue)
https://github.com/kruize/kruize-optimizer/issues/9

Type of change

  • Bug fix
  • New feature
  • Docs update
  • Breaking change (What changes might users need to make in their application due to this PR?)
  • Requires DB changes

How has this been tested?

Please describe the tests that were run to verify your changes and steps to reproduce. Please specify any test configuration required.

  • Tested on kind cluster
  • Functional testsuite

Test Configuration

  • Kubernetes clusters tested on: Kind

Checklist 🎯

  • Followed coding guidelines
  • Comments added
  • Dependent changes merged
  • Documentation updated
  • Tests added or updated

Summary by Sourcery

Refactor profile handling to use centralized constants for messages and API error parsing.

Bug Fixes:

  • Handle Kruize API "no profiles/layers found" responses using shared constants to avoid brittle string matching and improve error handling.

Enhancements:

  • Centralize ProfileService log and error messages in OptimizerConstants to ensure consistent, maintainable messaging.
  • Introduce ProfileResponseConstants to capture Kruize API profile-related error strings for reuse across the codebase.

@sourcery-ai

sourcery-ai Bot commented Jun 2, 2026

Copy link
Copy Markdown

Reviewer's Guide

Refactors ProfileService to centralize all profile-related log messages, error strings, and API response parsing into shared constants classes, improving consistency and maintainability of profile installation and retrieval behavior.

File-Level Changes

Change Details Files
Refactor ProfileService to use centralized message constants for logging, exceptions, and user-visible strings.
  • Replace inline log messages in metadata, metric, and layer profile fetch methods with MessageConstants equivalents
  • Use ProfileResponseConstants when inspecting Kruize API 400-response bodies for 'no profiles/layers found' conditions
  • Update profile installation flow to build user-facing result strings and logs using formatted MessageConstants templates instead of string concatenation
  • Change exceptions in profile install, load, and routing logic to use formatted MessageConstants messages and shared unknown profile type text
  • Standardize configsReferenceIndex.json-related logging with new message and warning constants
src/main/java/com/kruize/optimizer/service/ProfileService.java
Extend OptimizerConstants.MessageConstants with new profile-related info, warning, and error templates used by ProfileService.
  • Add formatted success and result strings for profile installation reporting
  • Introduce error templates for failed profile installation, configs index read failures, and unknown profile types
  • Add info messages for fetching profiles/layers and loading profiles from local resources, plus a warning for missing configs index file
  • Add warning message for failed response body reads and adjust PROFILE_NOT_FOUND to accept a path parameter
src/main/java/com/kruize/optimizer/utils/OptimizerConstants.java
Introduce ProfileResponseConstants to capture specific Kruize API error substrings used when parsing profile-related responses.
  • Create utility class for Kruize profile response error strings with a private constructor and explicit constants for 'no metadata/metric profiles' and 'no layers' errors
  • Update ProfileService to reference these new constants when analyzing response bodies on 400 errors
src/main/java/com/kruize/optimizer/utils/ProfileResponseConstants.java

Possibly linked issues

  • #(not provided): PR fully implements refactoring ProfileService literals to OptimizerConstants constants, matching the issue’s requested changes.

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

@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 - I've found 1 issue, and left some high level feedback:

  • The PROFILE_NOT_FOUND constant was changed to include a %s placeholder; double-check all existing usages outside this diff to ensure they are now using String.format and won’t log a literal %s or throw a formatting error.
  • Consider removing the // Made with Bob comment from ProfileResponseConstants to keep source comments focused on implementation details and avoid non-technical annotations in production code.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `PROFILE_NOT_FOUND` constant was changed to include a `%s` placeholder; double-check all existing usages outside this diff to ensure they are now using `String.format` and won’t log a literal `%s` or throw a formatting error.
- Consider removing the `// Made with Bob` comment from `ProfileResponseConstants` to keep source comments focused on implementation details and avoid non-technical annotations in production code.

## Individual Comments

### Comment 1
<location path="src/main/java/com/kruize/optimizer/service/ProfileService.java" line_range="254" />
<code_context>
                     kruizeClient.createLayer(profileDefinition);
                     break;
                 default:
-                    throw new IllegalArgumentException("Unknown profile type: " + profileType);
+                    throw new IllegalArgumentException(String.format(MessageConstants.ERROR_UNKNOWN_PROFILE_TYPE, profileType));
</code_context>
<issue_to_address>
**suggestion:** Repeated `Unknown profile type` switch defaults suggest the type should be modeled more strongly.

Multiple `switch` statements on `profileType` all fall back to `ERROR_UNKNOWN_PROFILE_TYPE`, which implies a closed set of values (metadata/metric/layer). Consider modelling `profileType` as an enum (or reusing `ProfileType` consistently) instead of strings so the compiler enforces valid values and you can eliminate these repeated runtime checks.

Suggested implementation:

```java
    private Object loadProfileFromLocal(ProfileType profileType, String profileName, String profileVersion) {

```

To fully apply the suggestion across the codebase, the following additional changes are likely needed in this file and related classes:

1. Ensure `ProfileType` is available in this file:
   - If not already imported, add `import com.kruize.optimizer.model.ProfileType;` (or the correct package for the existing `ProfileType` enum) near the top of `ProfileService.java`.

2. Update all methods and fields that currently use `String profileType` to use `ProfileType` instead:
   - Method parameters, local variables, and fields of type `String` that represent profile types should be changed to `ProfileType`.
   - For example, any `switch (profileType)` that currently switches on a `String` should now switch on `ProfileType`.

3. Update call sites of `loadProfileFromLocal`:
   - Wherever `loadProfileFromLocal` is called with a `String profileType`, convert the string to the enum, e.g.:
     - `loadProfileFromLocal(ProfileType.valueOf(profileTypeString.toUpperCase(Locale.ROOT)), profileName, profileVersion);`
     - Or better, through a safer factory like `ProfileType.fromValue(profileTypeString)` if such a helper exists.

4. Update `getResourcePath` (and similar helpers) to accept `ProfileType`:
   - If `getResourcePath` currently has a signature like `getResourcePath(String profileType, ...)`, update it to `getResourcePath(ProfileType profileType, ...)`.
   - Inside that method, use `profileType.name()` or `profileType.getValue()` (depending on how the enum is defined) to build paths or messages.

5. Align other `switch` statements and defaults:
   - For all other `switch` statements on `profileType` in this file (and possibly others), ensure they switch on `ProfileType` instead of `String`.
   - Once `ProfileType` is an enum, consider either:
     - Removing the `default` branch and letting the compiler catch unhandled enum constants, or
     - Keeping the `default` but changing it to throw an `IllegalStateException` to represent an unexpected/unhandled enum value rather than an "unknown" string value.

These changes will ensure `profileType` is modeled as a closed, compiler-enforced set of values and reduce the need for repeated runtime "unknown profile type" checks.
</issue_to_address>

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.

Comment thread src/main/java/com/kruize/optimizer/service/ProfileService.java
@gulati-aakriti
gulati-aakriti requested a review from shekhar316 June 2, 2026 06:46
@gulati-aakriti gulati-aakriti self-assigned this Jun 2, 2026
@gulati-aakriti gulati-aakriti added the bug Something isn't working label Jun 2, 2026
Comment thread src/main/java/com/kruize/optimizer/service/ProfileService.java Outdated
Comment thread src/main/java/com/kruize/optimizer/service/ProfileService.java Outdated
Comment thread src/main/java/com/kruize/optimizer/service/ProfileService.java Outdated
Comment thread src/main/java/com/kruize/optimizer/service/ProfileService.java
Comment thread src/main/java/com/kruize/optimizer/service/ProfileService.java Outdated
@gulati-aakriti gulati-aakriti changed the title Bug fix Refactor ProfileService, MetadataProfileRespurce, MetricProfileResource: Replace String Literals with Constants Jun 3, 2026

@shekhar316 shekhar316 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@bharathappali bharathappali left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@rbadagandi1 rbadagandi1 added this to the Kruize 0.11.0 Release milestone Jun 3, 2026
@rbadagandi1 rbadagandi1 moved this to Verify in Monitoring Jun 3, 2026
@rbadagandi1 rbadagandi1 moved this from Verify to Ready for merge in Monitoring Jun 3, 2026
@shekhar316

Copy link
Copy Markdown
Contributor

@dinogun can we please review and merge this? Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working Optimizer

Projects

Status: Ready for merge

Development

Successfully merging this pull request may close these issues.

5 participants