Skip to content

feat: Support user-defined description for backup#8354

Merged
f2c-ci-robot[bot] merged 1 commit intodev-v2from
pr@dev-v2@feat_backup_description
Apr 9, 2025
Merged

feat: Support user-defined description for backup#8354
f2c-ci-robot[bot] merged 1 commit intodev-v2from
pr@dev-v2@feat_backup_description

Conversation

@ssongliu
Copy link
Copy Markdown
Member

@ssongliu ssongliu commented Apr 9, 2025

Refs #4735

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot Bot commented Apr 9, 2025

Adding the "do-not-merge/release-note-label-needed" label because no release-note block was detected, please follow our release note process to remove it.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes/test-infra repository.

}
open.value = true;
};

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.

There are several minor suggestions to improve the code:

  1. Replace size="60%" with :width="'60%'" for more consistent template syntax.
  2. Use named props where possible (v-model:selects) instead of shorthand bindings like @input.
  3. Add an event listener for form submission outside the element's own slot content.

Here is the revised version:

<template>
    <!-- Rest of the component -->

    <DrawerPro
        :title="$t('commons.button.backup')"
        :resource="detailName ? name + ' [' + detailName + ']' : name"
        @close="handleClose"
        :width="'60%'" // Consistent width binding
    >
        <!-- Content -->
    </DrawerPro>

    <!-- Other parts remain unchanged -->

</template>

Additional Improvements Not Mentioned

  1. Consistently use ref(): Ensure all reactive properties are consistently created using ref(), not just when needed for input bindings or computed values.
  2. Improve function names: For better readability and maintainability, consider naming functions such as goFile and onChange with clear prefix indicating their purpose (e.g., openBackupFileDialog, updateRecordDescriptionValue).
  3. Refactor complex logic: If there's specific block of logic that becomes too lengthy, consider extracting it into a separate method or utility function.
  4. Add type checking: In typescript projects, explicitly define types for variables, components, and APIs used.

These improvements enhance code readability, maintainability, performance (where applicable), and adhering to community guidelines for Vue 3.x applications.

return folders[i].CreateAt.After(folders[j].CreateAt)
})
return folders[0].Name, nil
}
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.

The provided code has several issues that need to be addressed:

  1. Naming Conventions: The function loadRestorePath should follow conventional Go naming conventions, starting with lowercase letters (e.g., LoadRestorePath). This is more idiomatic Go coding practice.

  2. Logical Flow: There seems to be an error where you try to get information about non-existent files using file.Info(). You might want to check if the file exists before attempting to read its metadata to avoid errors.

  3. Sorting Logic: The sorting logic in sort.Slice uses a less-than comparison (folders[i].CreateAt.After(folders[j].CreateAt)), which sorts in ascending order based on creation time. If descending order is required, you can switch the comparison operator to folders[i].CreateAt.Before(folders[j].CreateAt).

  4. Return Type of Scan File: It's unclear what type is expected from the return value of scanFile. Assuming it returns no meaningful data or just void, ensure any callers understand the function’s behavior.

  5. Documentation and Comments: Add comments to explain each part of the loadRestorePath function to make it easier to understand for others reading the code.

Here's the revised version of the loadRestorePath function:

// LoadRestorePath loads the restore path by sorting directories by their creation time.
func LoadRestorePath(upgradeDir string) (string, error) {
	if _, err := os.Stat(upgradeDir); err != nil && !os.IsNotExist(err) {
		return "", fmt.Errorf("failed to stat upgrade directory: %w", err)
	}

	files, err := os.ReadDir(upgradeDir)
	if err != nil {
		return "", fmt.Errorf("could not list items in upgrade directory: %w", err)
	}
	type itemState struct {
		Name      string
		CreatedAt time.Time
	}
	var folders []itemState
	for _, file := range files {
		if file.IsDir() {
			info, ok := file.Info()
			if !ok {
				log.Printf("Failed to get info for file %s: %v", file.Name(), os.ErrInvalid)
				continue // Skip invalid entries
			}
			folders = append(folders, itemState{Name: file.Name(), CreatedAt: info.ModTime()})
		}
	}
	if len(folders) == 0 {
		return "", fmt.Errorf("upgrade directory is empty or does not exist")
	}
	sort.Slice(folders, func(i, j int) bool {
		return folders[i].CreatedAt.After(folders[j].CreatedAt) // Sort in descending order
	})
	return folders[0].Name, nil
}

Note added checks within ReadDir() to handle errors gracefully and logs the issue if encountered, along with proper docstrings and comments explaining key sections.


// @Tags Backup Account
// @Summary Delete backup record
// @Accept json
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.

The provided Go code snippet appears to be part of an API implementation using the Gin web framework on top of Golang. It includes two functions: DownloadRecord and UpdateRecordDescription. Let's analyze both for potential issues and improvements:

DownloadRecord Function

Main Points:

  • Purpose: Retrieves a file based on the requested path from the client request.
  • Parameters:
    • c *gin.Context: Represents the current context in an HTTP request.
    • filePath string: The location of the file that needs to be served.

Issues:

  1. No Error Handling: Without error handling, if something goes wrong (e.g., path/filepath.WalkFile returns an error), the function does not respond to the client appropriately. Consider adding logging or returning errors in JSON format.

  2. Response Type: While it handles successful downloads gracefully with metadata, it doesn't explicitly state its response type (application/octet-stream, etc.). This might be useful for clients expecting specific MIME types.

  3. Error Response Format: No clear indication of whether responses are successes or failures. A custom error message could help with debugging and understanding client responses.

  4. Logging: If logs are necessary, consider incorporating them to track download operations and handle exceptions more effectively.

if err := os.WalkFile(filePath, visitFunc); err != nil {
    helper.Logger.Error(err)
    helper.BadRequestWithMsg("Internal server error", c)
    return
}

helper.SetHeader(c, http.StatusOK, contentType)
fileReader, _ := os.Open(filePath)
_, err = io.CopyWriter(fileReader)
if err != nil {
    // Handle copy error separately
    helper.LogErrorAndRespond(http.StatusInternalServerError, "Failed to send file data")
}

UpdateRecordDescription Function

Main Points:

  • Purpose: Updates the description associated with a backup record using input parameters via a Post request.
  • Parameters:
    • req dto.UpdateDescription: A struct containing the new description to update.

Issues:

  1. Missing Validation Check: Although checkBindAndValidate is called within CheckBindAndValidate, there isn't explicit validation or error checking here after updating the service logic.

  2. Return Status Code For Errors: In case of business logic issues such as invalid updates, no status codes are returned properly. Returning a non-successful status (like http.StatusBadRequest) would indicate failure, but without proper documentation, clients may not understand what went wrong.

err := backupRecordService.UpdateDescription(req)
if err == nil {
helper.SuccessWithOutData(c)
} else {
helper.InternalServer(c, err)
log.Fatalf("[ERROR] Internal Server Error while updating backup record description %s\n", err)
}


#### Recommendations:
- **Add Custom Error Responses**: Ensure consistent use of `BadRequestWithMessage` and similar methods to clearly communicate errors to clients.
- **Implement Proper Validation After Service Calls**: Include checks to ensure the updated description is valid before proceeding with saving changes. Return appropriate messages based on specific validation failures like empty fields or unsupported formats.

### Additional Suggestions:
- **Middleware Usage**: Organize shared functionalities into middleware functions to keep handlers clean. Middleware can also enhance security features easily such as authentication and rate limiting.

- **Rate Limiting & Authentication**: Implement rate limiting strategies to prevent abuse of endpoints, especially sensitive ones like deleting back up records.

These revisions should improve the robustness and maintainability of each endpoint, making their interactions easier for both developers and end-users.

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented Apr 9, 2025

Copy link
Copy Markdown
Member

@wanghe-fit2cloud wanghe-fit2cloud left a comment

Choose a reason for hiding this comment

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

/lgtm

@wanghe-fit2cloud
Copy link
Copy Markdown
Member

/approve

@f2c-ci-robot
Copy link
Copy Markdown

f2c-ci-robot Bot commented Apr 9, 2025

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: wanghe-fit2cloud

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@f2c-ci-robot f2c-ci-robot Bot added the approved label Apr 9, 2025
@f2c-ci-robot f2c-ci-robot Bot merged commit 0934534 into dev-v2 Apr 9, 2025
6 checks passed
@f2c-ci-robot f2c-ci-robot Bot deleted the pr@dev-v2@feat_backup_description branch April 9, 2025 02:15
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.

3 participants