Skip to content

fix(ZMSKVR): reenable dldb backups#2183

Open
Fabinatix97 wants to merge 9 commits into
nextfrom
bugfix-zmskvr-reenable-dldb-backups
Open

fix(ZMSKVR): reenable dldb backups#2183
Fabinatix97 wants to merge 9 commits into
nextfrom
bugfix-zmskvr-reenable-dldb-backups

Conversation

@Fabinatix97
Copy link
Copy Markdown
Member

@Fabinatix97 Fabinatix97 commented Apr 10, 2026

Pull Request Checklist (Feature Branch to next):

  • Ich habe die neuesten Änderungen aus dem next Branch in meinen Feature-Branch gemergt.
  • Relevante Tests wurden mit zmsautomation ausgeführt.
  • Das Code-Review wurde abgeschlossen.
  • Fachliche Tests wurden durchgeführt und sind abgeschlossen.

Summary by CodeRabbit

  • Bug Fixes

    • Backups are now only created when existing files truly differ, avoiding unnecessary backups.
    • Ensures destination directory exists before writing outputs.
  • Refactor

    • Safer deploy flow: downloads and generated outputs are written to temporary files, then moved into place atomically.
    • Temporary files are cleaned up after deployment.
    • Improved error reporting and handling for file write and copy failures.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 10, 2026

📝 Walkthrough

Walkthrough

Downloader now writes each output to per-file temp files, helpers prepare backups (no return value) and always move temp files into the destination and unlink temps; helper signatures adjusted and a new copy/unlink helper was added.

Changes

Cohort / File(s) Summary
Helper Class
zmsdldb/bin/dldb-helpers.php
Normalized require_once spacing and re-indented blocks. Changed checkAndCreateBackup($newFiles) to : void (no return) and added copyDownloadedTempFilesToDestinationAndUnlink(array $filenameToTempPath): void to copy temp files to destinations, log copy failures, and unlink temps. Minor formatting tweaks.
Downloader (generic)
zmsdldb/bin/dldbget
Normalized require_once spacing; removed unused $backupPath; download writes to per-file temp files via tempnam(); $downloadedFiles maps filenames → temp paths; checkAndCreateBackup(...) is called and wrapped in try/finally so copyDownloadedTempFilesToDestinationAndUnlink(...) always runs; added temp file creation/write error handling and cleanup.
Downloader (Munich variant)
zmsdldb/bin/dldbget-munich
Ensures destination dir via inline is_dir/mkdir check; JSON outputs written to temp files via new helper (writeJsonTempFile) and tracked as filename → tempPath; backup check and final copy/unlink use the same try/finally pattern; minor require_once whitespace and CLI option formatting changes.

Sequence Diagram(s)

sequenceDiagram
  participant Downloader as Downloader
  participant Helpers as DldbHelpers
  participant FS as Filesystem

  Downloader->>FS: write downloaded content to temp file (tempnam)
  Downloader->>Helpers: call checkAndCreateBackup(map filename=>tempPath)
  Helpers->>FS: stat/examine existing destination files (md5/metadata)
  alt backups required
    Helpers->>FS: create backup files/directories
  end
  Helpers->>FS: copyDownloadedTempFilesToDestinationAndUnlink(map tempPath=>dest)
  FS-->>Helpers: report write success/failure
  Helpers->>FS: unlink temp files
  FS-->>Downloader: final status/errors
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I nibbled bytes in cozy digs, 🐇
Temp files snug in burrowed rigs,
Backups checked, then home they hop—
I copy, unlink, and never stop.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix(ZMSKVR): reenable dldb backups' directly addresses the main objective of the pull request, which is to re-enable DLDB backups across three related scripts by refactoring the backup pipeline to use temporary files and ensure proper cleanup.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bugfix-zmskvr-reenable-dldb-backups

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.

Copy link
Copy Markdown
Contributor

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
zmsdldb/bin/dldb-helpers.php (1)

123-132: ⚠️ Potential issue | 🟠 Major

This shared helper now disables backups for dldbget-munich.

zmsdldb/bin/dldbget-munich:99-108 still passes final destination paths after writing the files. With the new md5_file($destFile) !== md5_file($filePath) check, both operands point to the same file there, so $backupRequired never becomes true and that script stops creating backups entirely.

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@zmsdldb/bin/dldb-helpers.php`:
- Around line 157-160: The temp file is being deleted unconditionally after a
failed copy, causing loss of the only downloaded payload; modify the logic
around the copy/unlink in the dldb-helpers.php routine so that
`@unlink`($tempFile) is only executed when the copy to $destFile succeeds (i.e.,
move the unlink into the success branch or return/exit on failure), and when
copy fails leave $tempFile in place (and log the error via $this->cli->red as
already done) so retries or inspection can use the downloaded file; refer to the
copy($tempFile, $destFile) call and the subsequent `@unlink`($tempFile) to locate
the change.

In `@zmsdldb/bin/dldbget`:
- Around line 107-116: file_put_contents() can return false so the script
currently adds $tempFile to $downloadedFiles even when the write failed; modify
the block around $newContent / $tempFile to check the return value of
file_put_contents($tempFile, $newContent) and only set
$downloadedFiles[$download['file']] = $tempFile on success, otherwise print an
error (using $cli->red or similar), unlink the failed $tempFile if created, and
continue the loop so downstream backup/copy logic never runs against an
unwritten temp file.
- Around line 119-123: The temp-file cleanup is skipped if
DldbHelpers::checkAndCreateBackup() throws; wrap the backup call in a
try/finally so copyDownloadedTempFilesToDestinationAndUnlink($downloadedFiles)
always runs. Specifically, in the dldbget flow where
$helpers->checkAndCreateBackup($downloadedFiles) is invoked, call that inside a
try block and place
$helpers->copyDownloadedTempFilesToDestinationAndUnlink($downloadedFiles) in the
finally block so temp files are removed even on backup-directory creation
errors.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6e1c2cd5-19b3-4d6f-9cfe-0dbbfb59bf80

📥 Commits

Reviewing files that changed from the base of the PR and between a36fc7f and 4f95e45.

📒 Files selected for processing (2)
  • zmsdldb/bin/dldb-helpers.php
  • zmsdldb/bin/dldbget

Comment thread zmsdldb/bin/dldb-helpers.php
Comment thread zmsdldb/bin/dldbget
Comment thread zmsdldb/bin/dldbget Outdated
Fabinatix97 and others added 2 commits April 13, 2026 17:00
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Copy Markdown
Contributor

@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: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@zmsdldb/bin/dldb-helpers.php`:
- Line 66: The current return (int) $rollbackDaySetting[0] silently coerces
invalid input to 0; update the logic around $rollbackDaySetting so you validate
that $rollbackDaySetting[0] is a numeric digit string (e.g. using ctype_digit or
a regex) before casting, and explicitly fall back (return null or a defined
default) when it fails validation instead of casting; locate the code returning
(int) $rollbackDaySetting[0] and replace it with a guarded check that
logs/handles invalid values and only casts when the value is fully numeric.
- Around line 155-156: In the foreach that builds $destFile from
$filenameToTempPath, normalize the key the same way checkAndCreateBackup() does
by using basename($filename) (and validate it's non-empty) before concatenating
with $this->destinationPath so writes and backups target the same sanitized
filename and prevent directory-traversal (e.g., "../") escaping the destination
directory; update references to $filename when computing $destFile and any
subsequent operations to use the sanitized basename variable.
- Around line 157-161: Replace the accidental shell-execution-style backticks
around the unlink call so PHP calls the function normally: locate the line
containing the backticked `@unlink` with the $tempFile variable (after the copy
failure handling) and change it to call `@unlink`($tempFile) so the temporary file
is removed without using shell execution syntax.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 03eb9d0a-32e3-48a2-985e-050c591068a1

📥 Commits

Reviewing files that changed from the base of the PR and between 4f95e45 and 9e2c639.

📒 Files selected for processing (1)
  • zmsdldb/bin/dldb-helpers.php

Comment thread zmsdldb/bin/dldb-helpers.php
Comment thread zmsdldb/bin/dldb-helpers.php Outdated
Comment thread zmsdldb/bin/dldb-helpers.php Outdated
Copy link
Copy Markdown
Contributor

@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.

🧹 Nitpick comments (1)
zmsdldb/bin/dldbget-munich (1)

73-95: Consider using consistent error output style.

The writeJsonTempFile() helper uses plain echo for errors (lines 78, 84, 89), while the rest of the script uses print($cli->red(...)) for colored error output. This inconsistency reduces visual uniformity in error reporting.

Note: Since $cli is a global variable, it's not directly accessible inside the function without passing it as a parameter or using global $cli. The current approach works but lacks visual consistency.

♻️ Optional: Accept $cli as parameter for consistent error styling
-function writeJsonTempFile($data)
+function writeJsonTempFile($data, $cli = null)
 {
     $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
     if ($json === false) {
-        echo "Error: JSON encoding failed: " . json_last_error_msg() . "\n\n";
+        $msg = "Error: JSON encoding failed: " . json_last_error_msg() . "\n\n";
+        print($cli ? $cli->red($msg) : $msg);
         exit(1);
     }

     $tempFile = tempnam(sys_get_temp_dir(), 'dldbget_');
     if ($tempFile === false) {
-        echo "Error: Failed to create temporary file\n\n";
+        $msg = "Error: Failed to create temporary file\n\n";
+        print($cli ? $cli->red($msg) : $msg);
         exit(1);
     }

     if (file_put_contents($tempFile, $json) === false) {
-        echo "Error: Failed to write temporary file\n\n";
+        $msg = "Error: Failed to write temporary file\n\n";
+        print($cli ? $cli->red($msg) : $msg);
         `@unlink`($tempFile);
         exit(1);
     }

     return $tempFile;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@zmsdldb/bin/dldbget-munich` around lines 73 - 95, The writeJsonTempFile()
helper uses echo for error messages which is inconsistent with the rest of the
script's colored error output; update writeJsonTempFile to accept a $cli
parameter (or declare global $cli) and replace the echo error calls with
print($cli->red(...)) messages, keep the same error texts and retain the
existing temp file cleanup (`@unlink`) and exit(1) behavior, and update all call
sites of writeJsonTempFile to pass the $cli instance.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@zmsdldb/bin/dldbget-munich`:
- Around line 73-95: The writeJsonTempFile() helper uses echo for error messages
which is inconsistent with the rest of the script's colored error output; update
writeJsonTempFile to accept a $cli parameter (or declare global $cli) and
replace the echo error calls with print($cli->red(...)) messages, keep the same
error texts and retain the existing temp file cleanup (`@unlink`) and exit(1)
behavior, and update all call sites of writeJsonTempFile to pass the $cli
instance.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: cdd9cbfd-78da-44d3-9c9b-5a31ae7b899e

📥 Commits

Reviewing files that changed from the base of the PR and between 9e2c639 and 4bbbb4c.

📒 Files selected for processing (3)
  • zmsdldb/bin/dldb-helpers.php
  • zmsdldb/bin/dldbget
  • zmsdldb/bin/dldbget-munich
🚧 Files skipped from review as they are similar to previous changes (1)
  • zmsdldb/bin/dldb-helpers.php

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