Skip to content

Conversation

fogelito
Copy link
Contributor

What does this PR do?

(Provide a description of what this PR does and why it's needed.)

Test Plan

(Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work. Screenshots may also be helpful.)

Related PRs and Issues

  • (Related PR or issue)

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?

Copy link
Contributor

coderabbitai bot commented Aug 31, 2025

📝 Walkthrough

Walkthrough

Reworked audit batch processing to handle each project individually: the foreach now wraps per-project processing in its own try/catch/finally, derives a per-project Document from $projectLogs['project'], obtains a project-specific DB via the provided callable, constructs an Audit with that DB and calls logBatch for the project's logs. Added per-project logging and per-project error messages, and ensured cleanup with unset($this->logs[$sequence]) in finally. Removed the outer/batch-level catch. Method signature changed to public function action(Message $message, callable $getProjectDB, Document $project): Commit|NoCommit.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • christyjacob4

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 PHPStan (2.1.17)

Note: Using configuration file /phpstan.neon.
Invalid entry in excludePaths:
Path "/app/sdks" is neither a directory, nor a file path, nor a fnmatch pattern.

If the excluded path can sometimes exist, append (?)
to its config entry to mark it as optional. Example:

parameters:
excludePaths:
analyseAndScan:
- app/sdks (?)

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch check-audits

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
🪧 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>, please review it.
    • 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.
  • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

github-actions bot commented Aug 31, 2025

Security Scan Results for PR

Docker Image Scan Results

Package Version Vulnerability Severity
golang.org/x/crypto v0.31.0 CVE-2025-22869 HIGH
golang.org/x/oauth2 v0.24.0 CVE-2025-22868 HIGH
stdlib 1.22.10 CVE-2025-47907 HIGH

Source Code Scan Results

🎉 No vulnerabilities found!

Copy link
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: 4

🧹 Nitpick comments (2)
src/Appwrite/Platform/Workers/Audits.php (2)

43-44: Remove constructor noise (wrong severity).

This logs on every worker start at error level. Drop it or guard behind a debug flag.

Apply this diff:

-        Console::error('__construct Audits');

76-78: Avoid error-level for routine context; gate or downgrade.

These are dev traces. Either remove or show only outside production.

Apply this diff:

-        Console::error('project '.$project->getSequence());
-        Console::error('lastTriggeredTime '.$this->lastTriggeredTime);
+        if (System::getEnv('_APP_ENV', 'production') !== 'production') {
+            Console::log('project ' . $project->getSequence());
+            Console::log('lastTriggeredTime ' . $this->lastTriggeredTime);
+        }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c7bbb6a and c96b630.

📒 Files selected for processing (1)
  • src/Appwrite/Platform/Workers/Audits.php (4 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/Appwrite/Platform/Workers/Audits.php (1)
app/realtime.php (1)
  • getProjectDB (76-122)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: Setup & Build Appwrite Image
  • GitHub Check: scan
🔇 Additional comments (1)
src/Appwrite/Platform/Workers/Audits.php (1)

152-154: Good: snapshot then clear buffer.

This prevents in-loop mutation and simplifies processing semantics.

Copy link

github-actions bot commented Aug 31, 2025

✨ Benchmark results

  • Requests per second: 1,188
  • Requests with 200 status code: 213,929
  • P99 latency: 0.162649866

⚡ Benchmark Comparison

Metric This PR Latest version
RPS 1,188 970
200 213,929 174,602
P99 0.162649866 0.199244098

Comment on lines 134 to 147
$logs = $this->logs;
$this->logs = [];

foreach ($logs as $projectLogs) {
try {
$projectDocument = $projectLogs['project'];
Console::log('Processing Project "' . $projectDocument->getSequence() . '" batch with ' . count($projectLogs['logs']) . ' events');
$dbForProject = $getProjectDB($projectDocument);
$audit = new Audit($dbForProject);

$audit->logBatch($projectLogs['logs']);
Console::success('Audit logs processed successfully');

unset($this->logs[$sequence]);
} catch (Throwable $e) {
Console::error('Error processing audit logs for Project "' . $projectDocument->getSequence() . '": ' . $e->getMessage());
}
Copy link
Member

Choose a reason for hiding this comment

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

Instead of resetting all, let's unset at the end of the loop as before, but also unset in the catch

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done!

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

♻️ Duplicate comments (1)
src/Appwrite/Platform/Workers/Audits.php (1)

134-153: Stop dropping logs on errors; unset only on success and return NoCommit if any project fails.

The finally block unconditionally unsets buffered logs and the method always returns Commit. On any per-project exception, this will drop that project's logs and ack the message — a data-loss scenario. Handle failures per-project, keep failed batches in memory, and return NoCommit if any failure occurred.

Apply this diff:

-        foreach ($this->logs as $sequence => $projectLogs) {
-            try {
-                Console::log('Processing Project "' . $sequence . '" batch with ' . count($projectLogs['logs']) . ' events');
-
-                $projectDocument = $projectLogs['project'];
-                $dbForProject = $getProjectDB($projectDocument);
-                $audit = new Audit($dbForProject);
-                $audit->logBatch($projectLogs['logs']);
-
-                Console::success('Audit logs processed successfully');
-            } catch (Throwable $e) {
-                Console::error('Error processing audit logs for Project "' . $sequence . '": ' . $e->getMessage());
-            } finally {
-                unset($this->logs[$sequence]);
-            }
-        }
+        $failed = [];
+        foreach ($this->logs as $sequence => $projectLogs) {
+            try {
+                Console::log('Processing Project "' . $sequence . '" batch with ' . count($projectLogs['logs']) . ' events');
+                /** @var Document $projectDocument */
+                $projectDocument = $projectLogs['project'];
+                $dbForProject = $getProjectDB($projectDocument);
+                $audit = new Audit($dbForProject);
+                $audit->logBatch($projectLogs['logs']);
+                Console::success('Audit logs processed successfully');
+                // Remove only successfully processed batches
+                unset($this->logs[$sequence]);
+            } catch (Throwable $e) {
+                Console::error('Error processing audit logs for Project "' . $sequence . '": ' . $e->getMessage());
+                // Keep failed batches in buffer for retry
+                $failed[$sequence] = true;
+            }
+        }
+        if (!empty($failed)) {
+            return new NoCommit();
+        }
🧹 Nitpick comments (1)
src/Appwrite/Platform/Workers/Audits.php (1)

136-146: Confirm idempotency to avoid duplicates on retry.

With at-least-once delivery (NoCommit), successful batches are removed but the current message will be redelivered. Ensure Audit::logBatch is idempotent or events have a dedupe key to prevent duplicate inserts on retries.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 0af3734 and 711d31b.

📒 Files selected for processing (1)
  • src/Appwrite/Platform/Workers/Audits.php (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/Appwrite/Platform/Workers/Audits.php (1)
app/realtime.php (1)
  • getProjectDB (76-122)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: E2E Service Test (Site Screenshots)
  • GitHub Check: Unit Test
  • GitHub Check: E2E General Test
  • GitHub Check: Linter
  • GitHub Check: scan
  • GitHub Check: CodeQL

@abnegate abnegate merged commit a63e486 into 1.8.x Sep 2, 2025
41 checks passed
@abnegate abnegate deleted the check-audits branch September 2, 2025 11:08
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.

2 participants