Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: backup file has no content #312

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

Khachi-at
Copy link

@Khachi-at Khachi-at commented Jul 3, 2024

It is found that the backup file has no content in use. The specific reason is that the file writing process stops (such as closing the process).
Based on the above reasons, the backup file writing logic is optimized, and the configuration file content is first written to a new file, and then the new file is used to overwrite the old file.

Summary by CodeRabbit

  • New Features

    • Fix the issue of backup file has no content.
  • Tests

    • Added tests for the new backup writing functionality to ensure reliable performance and error handling.

Copy link

coderabbitai bot commented Jul 3, 2024

Walkthrough

The updates introduce a WriteWithBackup method to enhance the ConfigFile functionalities, enabling configuration write operations with backup support. Corresponding tests have been added to ensure robustness. The changes affect methods and comments across several files in the config and file handling modules, ensuring uniformity and improved functionality.

Changes

File Path Change Summary
env/config/.../json_config.go Renamed comments, updated Load and Write methods, added WriteWithBackup.
env/config/.../json_config_test.go Added tests TestJSONConfigFile_WriteWithBackup and TestJSONConfigFile_WriteWithBackup_error.
env/file/.../json.go, .../raw.go Updated imports, comments, and replaced Write with WriteWithBackup in the WriteConfigFile method.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ConfigFile
    participant FileSystem

    User->>ConfigFile: WriteWithBackup(data)
    ConfigFile->>FileSystem: Backup existing file
    FileSystem-->ConfigFile: Backup success/failure
    ConfigFile->>FileSystem: Write new data to file
    FileSystem-->ConfigFile: Write success/failure
    ConfigFile-->>User: Operation success/failure
Loading

Poem

In the code, new winds do blow,
With backups in hand, our data flows,
Configs are safe, oh what a feat,
Tests are run, no risks to meet.
Embrace the change, with joy so sweet,
In lines of logic, the worlds do greet. 🌐✨

Tip

AI model upgrade

gpt-4o model for reviews and chat is now live

OpenAI claims that this model is better at understanding and generating code than the previous models. Please join our Discord Community to provide any feedback or to report any issues.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

mergify bot commented Jul 3, 2024

感谢您提出Pull Request,我会尽快Review。我会在1-2日内进行查看或者回复,如果遇到节假日可能会处理较慢,敬请谅解。

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9660dd0 and a185bcc.

Files selected for processing (4)
  • env/config/json/json_config.go (3 hunks)
  • env/config/json/json_config_test.go (1 hunks)
  • env/file/json/json.go (3 hunks)
  • env/file/json/raw.go (4 hunks)
Additional context used
Gitleaks
env/config/json/json_config_test.go

175-175: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


185-185: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

Additional comments not posted (8)
env/file/json/raw.go (1)

Line range hint 63-74: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to WriteConfigFile are updated accordingly.

Verification successful

Function calls to WriteConfigFile are correctly updated.

  • The WriteConfigFile function in storage/repository.go uses the updated handler implementation.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `WriteConfigFile` match the new implementation.

# Test: Search for the function usage. Expect: Only occurances of the new implementation.
rg --type go $'WriteConfigFile'

Length of output: 1756



Script:

#!/bin/bash
# Extract and review the context of each `WriteConfigFile` call in the main codebase, excluding test files.

# List all files with `WriteConfigFile` occurrences, excluding test files
rg --type go --files-with-matches 'WriteConfigFile' | grep -v '_test.go' | xargs -I {} sh -c 'echo "File: {}"; rg --context 5 "WriteConfigFile" {}'

Length of output: 1853



Script:

#!/bin/bash
# Verify the implementation of `extension.GetFileHandler()` to ensure it returns an instance of the updated handler.

# Search for the implementation of `GetFileHandler` in the `extension` package
rg --type go 'func GetFileHandler' extension/

Length of output: 106



Script:

#!/bin/bash
# Extract and review the implementation of `GetFileHandler` in `extension/file.go`.

# Display the implementation of `GetFileHandler`
rg --context 10 'func GetFileHandler' extension/file.go

Length of output: 331



Script:

#!/bin/bash
# Search for calls to `SetFileHandler` and review the context to confirm the correct handler is being used.

# Search for calls to `SetFileHandler`
rg --context 5 'SetFileHandler' --type go

Length of output: 8046

env/config/json/json_config.go (3)

Line range hint 50-63: LGTM!

The Write function correctly handles errors and logs them.


66-74: LGTM!

The WriteWithBackup function correctly implements the backup mechanism.


Line range hint 34-49: LGTM!

The Load function correctly handles errors and logs them.

env/file/json/json.go (2)

Line range hint 99-115: LGTM!

The LoadConfigFile function correctly handles errors and logs them.


78-79: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to WriteConfigFile are updated accordingly.

Verification successful

LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to WriteConfigFile are updated accordingly.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `WriteConfigFile` match the new implementation.

# Test: Search for the function usage. Expect: Only occurances of the new implementation.
rg --type go $'WriteConfigFile'

Length of output: 1756



Script:

#!/bin/bash
# Description: Verify the implementation of WriteConfigFile in the listed files.

# Check implementation in start_test.go
rg -A 5 -B 5 'func (fileHandler \*testFileHandler) WriteConfigFile' start_test.go

# Check implementation in storage/repository.go
rg -A 5 -B 5 'WriteConfigFile' storage/repository.go

# Check implementation in env/file/file_handler.go
rg -A 5 -B 5 'WriteConfigFile' env/file/file_handler.go

# Check implementation in env/file/json/json.go
rg -A 5 -B 5 'func (fileHandler \*FileHandler) WriteConfigFile' env/file/json/json.go

# Check implementation in env/file/json/raw.go
rg -A 5 -B 5 'func (fileHandler \*rawFileHandler) WriteConfigFile' env/file/json/raw.go

# Check implementation in env/file/json/raw_test.go
rg -A 5 -B 5 'WriteConfigFile' env/file/json/raw_test.go

# Check implementation in env/file/json/json_test.go
rg -A 5 -B 5 'WriteConfigFile' env/file/json/json_test.go

# Check implementation in extension/file_test.go
rg -A 5 -B 5 'func (r \*TestFileHandler) WriteConfigFile' extension/file_test.go

Length of output: 3594



Script:

#!/bin/bash
# Description: Verify the implementation of WriteConfigFile in the specific file env/file/json/json.go.

# Check implementation in env/file/json/json.go
rg -A 10 -B 10 'func (fileHandler \*FileHandler) WriteConfigFile' env/file/json/json.go

# Check other instances to ensure they align with the new logic.
rg -A 10 -B 10 'WriteConfigFile' env/file/json/raw.go env/file/json/raw_test.go env/file/json/json_test.go storage/repository.go

Length of output: 8728



Script:

#!/bin/bash
# Description: Verify the implementation of WriteConfigFile in the specific file env/file/json/json.go.

# Check implementation in env/file/json/json.go
rg -A 10 -B 10 'WriteWithBackup' env/file/json/json.go

Length of output: 766

env/config/json/json_config_test.go (2)

173-181: LGTM!

The TestJSONConfigFile_WriteWithBackup function correctly tests the WriteWithBackup method.

Tools
Gitleaks

175-175: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


183-194: LGTM!

The TestJSONConfigFile_WriteWithBackup_error function correctly tests the WriteWithBackup method for error scenarios.

Tools
Gitleaks

185-185: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

@nobodyiam
Copy link
Member

Could you please help to describe the steps to duplicate the original bug?

@coveralls
Copy link

coveralls commented Jul 7, 2024

Pull Request Test Coverage Report for Build 9774866320

Details

  • 9 of 9 (100.0%) changed or added relevant lines in 3 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage increased (+0.1%) to 75.709%

Totals Coverage Status
Change from base Build 8956224862: 0.1%
Covered Lines: 1334
Relevant Lines: 1762

💛 - Coveralls

@Khachi-at
Copy link
Author

Khachi-at commented Jul 9, 2024

Could you please help to describe the steps to duplicate the original bug?

  • The test code is like this. You can duplicate the bug by running it.
package apollofx

import (
	"encoding/json"
	"testing"

	"github.com/apolloconfig/agollo/v4"
	"github.com/apolloconfig/agollo/v4/env/config"
	ajson "github.com/apolloconfig/agollo/v4/env/config/json"
	"github.com/stretchr/testify/require"
)

func TestXxx(t *testing.T) {
	loader := &ajson.ConfigFile{}
	// Create app config.
	appCfg := &config.AppConfig{}
	_, err := loader.Load("config.json", func(bytes []byte) (interface{}, error) {
		return appCfg, json.Unmarshal(bytes, appCfg)
	})
	require.NoError(t, err)

	// Start apollo client.
	client, err := agollo.StartWithConfig(func() (*config.AppConfig, error) {
		return appCfg, nil
	})
	require.NoError(t, err)
	_, err = client.GetConfigCache("namespace").Get("content")
	require.NoError(t, err)
}

config.json

{
  "appId": "testapp",
  "cluster": "default",
  "ip": "http://127.0.0.1:32026",
  "namespaceName": "namespace",
  "isBackupConfig": true,
  "secret": "secret",
  "backupConfigPath": "./"
}

@nobodyiam
Copy link
Member

Could you please help to describe the steps to duplicate the original bug?

  • The test code is like this. You can duplicate the bug by running it.
package apollofx

import (
	"encoding/json"
	"testing"

	"github.com/apolloconfig/agollo/v4"
	"github.com/apolloconfig/agollo/v4/env/config"
	ajson "github.com/apolloconfig/agollo/v4/env/config/json"
	"github.com/stretchr/testify/require"
)

func TestXxx(t *testing.T) {
	loader := &ajson.ConfigFile{}
	// Create app config.
	appCfg := &config.AppConfig{}
	_, err := loader.Load("config.json", func(bytes []byte) (interface{}, error) {
		return appCfg, json.Unmarshal(bytes, appCfg)
	})
	require.NoError(t, err)

	// Start apollo client.
	client, err := agollo.StartWithConfig(func() (*config.AppConfig, error) {
		return appCfg, nil
	})
	require.NoError(t, err)
	_, err = client.GetConfigCache("namespace").Get("content")
	require.NoError(t, err)
}

config.json

{
  "appId": "testapp",
  "cluster": "default",
  "ip": "http://127.0.0.1:32026",
  "namespaceName": "namespace",
  "isBackupConfig": true,
  "secret": "secret",
  "backupConfigPath": "./"
}

I followed the steps and found no errors. Did I miss something?

image

@Khachi-at
Copy link
Author

Could you please help to describe the steps to duplicate the original bug?

  • The test code is like this. You can duplicate the bug by running it.
package apollofx

import (
	"encoding/json"
	"testing"

	"github.com/apolloconfig/agollo/v4"
	"github.com/apolloconfig/agollo/v4/env/config"
	ajson "github.com/apolloconfig/agollo/v4/env/config/json"
	"github.com/stretchr/testify/require"
)

func TestXxx(t *testing.T) {
	loader := &ajson.ConfigFile{}
	// Create app config.
	appCfg := &config.AppConfig{}
	_, err := loader.Load("config.json", func(bytes []byte) (interface{}, error) {
		return appCfg, json.Unmarshal(bytes, appCfg)
	})
	require.NoError(t, err)

	// Start apollo client.
	client, err := agollo.StartWithConfig(func() (*config.AppConfig, error) {
		return appCfg, nil
	})
	require.NoError(t, err)
	_, err = client.GetConfigCache("namespace").Get("content")
	require.NoError(t, err)
}

config.json

{
  "appId": "testapp",
  "cluster": "default",
  "ip": "http://127.0.0.1:32026",
  "namespaceName": "namespace",
  "isBackupConfig": true,
  "secret": "secret",
  "backupConfigPath": "./"
}

I followed the steps and found no errors. Did I miss something?

image

Adjusting the code like this can increase the probability of duplicating the bug. You need to pay attention to the contents of the backup file. Because a new backup file is created each time, if the program is stopped after the new backup file is created and before the content is written to the backup file, the backup file will have no content.

package apollofx

import (
	"encoding/json"
	"testing"

	"github.com/apolloconfig/agollo/v4"
	"github.com/apolloconfig/agollo/v4/env/config"
	ajson "github.com/apolloconfig/agollo/v4/env/config/json"
	"github.com/stretchr/testify/require"
)

func TestXxx(t *testing.T) {
	loader := &ajson.ConfigFile{}
	// Create app config.
	appCfg := &config.AppConfig{}
	_, err := loader.Load("config.json", func(bytes []byte) (interface{}, error) {
		return appCfg, json.Unmarshal(bytes, appCfg)
	})
	require.NoError(t, err)

	// Start apollo client.
	agollo.StartWithConfig(func() (*config.AppConfig, error) {
		return appCfg, nil
	})
}

Copy link

stale bot commented Oct 6, 2024

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the stale label Oct 6, 2024
@zouyx zouyx changed the base branch from master to develop October 22, 2024 23:51
@stale stale bot removed the stale label Oct 22, 2024
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.

3 participants