Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 34 additions & 12 deletions internal/file/file_operator.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ func (fo *FileOperator) ReadChunk(

func (fo *FileOperator) WriteManifestFile(
ctx context.Context, updatedFiles map[string]*model.ManifestFile, manifestDir, manifestPath string,
) (writeError error) {
) error {
slog.DebugContext(ctx, "Writing manifest file", "updated_files", updatedFiles)
manifestJSON, err := json.MarshalIndent(updatedFiles, "", " ")
if err != nil {
Expand All @@ -164,28 +164,50 @@ func (fo *FileOperator) WriteManifestFile(

fo.manifestLock.Lock()
defer fo.manifestLock.Unlock()

// 0755 allows read/execute for all, write for owner
if err = os.MkdirAll(manifestDir, dirPerm); err != nil {
return fmt.Errorf("unable to create directory %s: %w", manifestDir, err)
}

// 0600 ensures only root can read/write
newFile, err := os.OpenFile(manifestPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, filePerm)
// Write to a temporary file first to ensure atomicity
tempManifestFilePath := manifestPath + ".tmp"
tempFile, err := os.OpenFile(tempManifestFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, filePerm)
if err != nil {
return fmt.Errorf("failed to read manifest file: %w", err)
return fmt.Errorf("failed to open temporary manifest file: %w", err)
}
defer func() {
if closeErr := newFile.Close(); closeErr != nil {
writeError = closeErr
}
}()

_, err = newFile.Write(manifestJSON)
if _, err = tempFile.Write(manifestJSON); err != nil {
closeFile(ctx, tempFile)

return fmt.Errorf("failed to write to temporary manifest file: %w", err)
}

closeFile(ctx, tempFile)

// Verify the contents of the temporary file is JSON
file, err := os.ReadFile(tempManifestFilePath)
if err != nil {
return fmt.Errorf("failed to write manifest file: %w", err)
return fmt.Errorf("failed to read temporary manifest file: %w", err)
}

return writeError
var manifestFiles map[string]*model.ManifestFile

err = json.Unmarshal(file, &manifestFiles)
if err != nil {
if len(file) == 0 {
return fmt.Errorf("temporary manifest file is empty: %w", err)
}

return fmt.Errorf("failed to parse temporary manifest file: %w", err)
}

// Rename the temporary file to the actual manifest file path
if renameError := os.Rename(tempManifestFilePath, manifestPath); renameError != nil {
return fmt.Errorf("failed to rename temporary manifest file: %w", renameError)
}

return nil
}

func (fo *FileOperator) MoveFile(ctx context.Context, sourcePath, destPath string) error {
Expand Down
Loading