Skip to content

Improve realtime error logging with project, user, and auth context#11421

Merged
abnegate merged 2 commits into1.8.xfrom
realtime-log-improve
Feb 27, 2026
Merged

Improve realtime error logging with project, user, and auth context#11421
abnegate merged 2 commits into1.8.xfrom
realtime-log-improve

Conversation

@premtsd-code
Copy link

Summary

  • Convert logError from closure to named function with function_exists guard, enabling cloud to override with region-specific tags
  • Add projectId, userId as tags and detailedTrace, roles as extras to realtime error logs sent to Sentry
  • Pass $project, $user, and $authorization context at onOpen and onMessage call sites

Test plan

  • Deploy to staging and trigger a realtime connection error
  • Verify Sentry receives projectId, userId tags and roles, detailedTrace extras
  • Verify cloud override adds projectRegion and region tags
  • Verify errors without context (e.g. pubSubConnection, updateWorkerDocument) still log correctly with n/a defaults

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 26, 2026

📝 Walkthrough

Walkthrough

Adds a public function logError(Throwable $error, string $action, array $tags = [], ?Document $project = null, ?Document $user = null, ?Authorization $authorization = null) in app/realtime.php and replaces prior inline $logError closure calls with direct logError(...) calls across server startup, pub/sub, onOpen, and onMessage paths. logError logs via the configured realtimeLogger, enriches metadata (projectId, userId, tags, file, line, trace, detailedTrace, roles), sets environment from _APP_ENV, is non-blocking, includes a function_exists guard for overrides, and handlers add defensive initialization for $project, $logUser, and $authorization while preserving existing error handling/response behavior.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 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
Title check ✅ Passed The title clearly and specifically summarizes the main change: converting logError to a named function with enhanced context (project, user, and auth) for improved error logging in the realtime module.
Description check ✅ Passed The description is directly related to the changeset, providing a clear summary of the three main changes (function conversion, tag/extras additions, context passing) and a concrete test plan for validation.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch realtime-log-improve

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.

@github-actions
Copy link

github-actions bot commented Feb 26, 2026

Security Scan Results for PR

Docker Image Scan Results

Package Version Vulnerability Severity
libecpg 18.1-r0 CVE-2026-2004 HIGH
libecpg 18.1-r0 CVE-2026-2005 HIGH
libecpg 18.1-r0 CVE-2026-2006 HIGH
libecpg 18.1-r0 CVE-2026-2007 HIGH
libecpg-dev 18.1-r0 CVE-2026-2004 HIGH
libecpg-dev 18.1-r0 CVE-2026-2005 HIGH
libecpg-dev 18.1-r0 CVE-2026-2006 HIGH
libecpg-dev 18.1-r0 CVE-2026-2007 HIGH
libheif 1.20.2-r1 CVE-2025-68431 HIGH
libpng 1.6.54-r0 CVE-2026-25646 HIGH
libpng-dev 1.6.54-r0 CVE-2026-25646 HIGH
libpq 18.1-r0 CVE-2026-2004 HIGH
libpq 18.1-r0 CVE-2026-2005 HIGH
libpq 18.1-r0 CVE-2026-2006 HIGH
libpq 18.1-r0 CVE-2026-2007 HIGH
libpq-dev 18.1-r0 CVE-2026-2004 HIGH
libpq-dev 18.1-r0 CVE-2026-2005 HIGH
libpq-dev 18.1-r0 CVE-2026-2006 HIGH
libpq-dev 18.1-r0 CVE-2026-2007 HIGH
postgresql18-dev 18.1-r0 CVE-2026-2004 HIGH
postgresql18-dev 18.1-r0 CVE-2026-2005 HIGH
postgresql18-dev 18.1-r0 CVE-2026-2006 HIGH
postgresql18-dev 18.1-r0 CVE-2026-2007 HIGH

Source Code Scan Results

🎉 No vulnerabilities found!

@premtsd-code premtsd-code changed the base branch from main to 1.8.x February 26, 2026 14:52
@github-actions
Copy link

github-actions bot commented Feb 26, 2026

🔄 PHP-Retry Summary

Flaky tests detected across commits:

Commit 117fab7 - 3 flaky tests
Test Retries Total Time Details
UsageTest::testDatabaseStatsCollectionsAPI 1 10.24s Logs
LegacyCustomServerTest::testListAttributes 1 240.48s Logs
TablesDBCustomServerTest::testCreatedBetween 1 240.69s Logs
Commit 81e828a - 2 flaky tests
Test Retries Total Time Details
UsageTest::testDatabaseStatsCollectionsAPI 1 10.09s Logs
SitesCustomServerTest::testAdapterDetectionAstroSSR 1 121.15s Logs

@github-actions
Copy link

github-actions bot commented Feb 26, 2026

✨ Benchmark results

  • Requests per second: 1,751
  • Requests with 200 status code: 315,203
  • P99 latency: 0.095193304

⚡ Benchmark Comparison

Metric This PR Latest version
RPS 1,751 1,125
200 315,203 202,462
P99 0.095193304 0.204793445

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.

🧹 Nitpick comments (4)
app/realtime.php (4)

705-705: Consider a more descriptive action string.

The action 'realtime' is generic. For better log filtering and clarity, consider using 'realtimeOpen' or 'onOpen' to distinguish connection establishment errors from message handling errors.

♻️ Suggested change
-        logError($th, 'realtime', [], $project, $logUser, $authorization);
+        logError($th, 'realtimeOpen', [], $project, $logUser, $authorization);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/realtime.php` at line 705, The log call uses a generic action string
'realtime' which makes it hard to distinguish connection-open errors from other
realtime events; update the action argument in the logError invocation (the call
to logError) to a more specific value like 'realtimeOpen' or 'onOpen' to
indicate this is the connection establishment path so logs can be filtered and
understood more easily.

274-276: Consider using null coalescing for tag values.

The expression $value ?: 'n/a' treats all falsy values (including "0", "", false) as missing. If a tag value of "0" or empty string could be meaningful, consider using $value ?? 'n/a' instead.

♻️ Suggested change
         foreach ($tags as $key => $value) {
-            $log->addTag($key, $value ?: 'n/a');
+            $log->addTag($key, $value ?? 'n/a');
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/realtime.php` around lines 274 - 276, The loop that adds tags uses the
PHP elvis operator (`$value ?: 'n/a'`) which treats all falsy values (like "0"
or "") as missing; update the tag handling in the foreach over `$tags` so the
default is applied only when the key is null using the null coalescing operator
(`$value ?? 'n/a'`) before calling `$log->addTag($key, $value ?? 'n/a')`,
leaving `$log->addTag` and the surrounding loop intact.

740-743: User context is not captured for onMessage error logging.

The error logging at line 869 passes null for the user parameter. However, for authentication-type messages (line 806), the $user is retrieved from the database. Consider capturing this user and passing it to logError for richer error context on authentication failures.

♻️ Suggested change to capture user context
 $server->onMessage(function (int $connection, string $message) use ($server, $register, $realtime, $containerId) {
     $project = null;
     $authorization = null;
+    $logUser = null;

     try {
         // ... existing code ...

         /** `@var` User $user */
         $user = $database->getDocument('users', $store->getProperty('id', ''));
+        $logUser = $user;

         // ... existing code ...
     } catch (Throwable $th) {
-        logError($th, 'realtimeMessage', [], $project, null, $authorization);
+        logError($th, 'realtimeMessage', [], $project, $logUser, $authorization);

Also applies to: 869-869

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/realtime.php` around lines 740 - 743, The onMessage closure currently
initializes $user as null only locally when handling authentication, but passes
null into logError for exceptions; declare and capture a $user variable in the
outer scope of the onMessage handler (e.g., initialize $user = null alongside
$project and $authorization at the top of the closure), assign the retrieved
user object to that $user when you fetch from the DB in the authentication
branch, and then pass that $user into logError instead of null so error logs
include the authenticated user context (update the closure variables and the
logError call accordingly).

281-281: Be aware: detailedTrace may contain sensitive function arguments.

$error->getTrace() includes function arguments which could contain sensitive data (tokens, passwords, PII) that will be sent to the logging service. This is standard practice for internal error monitoring, but ensure your logging service has appropriate access controls and retention policies.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/realtime.php` at line 281, The current call
$log->addExtra('detailedTrace', $error->getTrace()) may leak sensitive function
arguments; replace it with a sanitized trace that strips or omits the "args"
entries before sending to $log->addExtra. Locate the use of $error and
getTrace() and transform the trace (e.g., iterate over $error->getTrace() and
remove the 'args' key or replace values with redacted placeholders) and then
pass that sanitized array to $log->addExtra('detailedTrace', ...).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@app/realtime.php`:
- Line 705: The log call uses a generic action string 'realtime' which makes it
hard to distinguish connection-open errors from other realtime events; update
the action argument in the logError invocation (the call to logError) to a more
specific value like 'realtimeOpen' or 'onOpen' to indicate this is the
connection establishment path so logs can be filtered and understood more
easily.
- Around line 274-276: The loop that adds tags uses the PHP elvis operator
(`$value ?: 'n/a'`) which treats all falsy values (like "0" or "") as missing;
update the tag handling in the foreach over `$tags` so the default is applied
only when the key is null using the null coalescing operator (`$value ?? 'n/a'`)
before calling `$log->addTag($key, $value ?? 'n/a')`, leaving `$log->addTag` and
the surrounding loop intact.
- Around line 740-743: The onMessage closure currently initializes $user as null
only locally when handling authentication, but passes null into logError for
exceptions; declare and capture a $user variable in the outer scope of the
onMessage handler (e.g., initialize $user = null alongside $project and
$authorization at the top of the closure), assign the retrieved user object to
that $user when you fetch from the DB in the authentication branch, and then
pass that $user into logError instead of null so error logs include the
authenticated user context (update the closure variables and the logError call
accordingly).
- Line 281: The current call $log->addExtra('detailedTrace', $error->getTrace())
may leak sensitive function arguments; replace it with a sanitized trace that
strips or omits the "args" entries before sending to $log->addExtra. Locate the
use of $error and getTrace() and transform the trace (e.g., iterate over
$error->getTrace() and remove the 'args' key or replace values with redacted
placeholders) and then pass that sanitized array to
$log->addExtra('detailedTrace', ...).

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8368a28 and 117fab7.

📒 Files selected for processing (1)
  • app/realtime.php

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

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

Inline comments:
In `@app/realtime.php`:
- Around line 740-743: The onMessage closure is dropping authenticated user
context—ensure the resolved $user (from the authentication flow inside the
onMessage closure) is passed through to the realtime logging/emit call so userId
is not set to 'n/a'; locate the onMessage(...) closure and the logging/emission
call that currently omits $user (referenced by variables $server, $register,
$realtime, $containerId and local $project/$authorization) and update that call
to include the $user (or derived userId) in the payload/context used for logging
and realtime events so the richer user context is preserved.
- Around line 281-283: The code is currently passing $error->getTrace() directly
into $log->addExtra('detailedTrace', ...), which may contain sensitive argument
data; instead, build a sanitized trace array by mapping $error->getTrace() to
include only safe fields (e.g. 'file','line','class','function') and omit 'args'
(and any large or sensitive values), then pass that sanitizedTrace to
$log->addExtra('detailedTrace', $sanitizedTrace); update the call site using the
same symbols ($error->getTrace(), $log->addExtra('detailedTrace', ...)) so
authorization roles logging ($authorization?->getRoles()) remains unchanged.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e4821b3 and 81e828a.

📒 Files selected for processing (1)
  • app/realtime.php

@abnegate abnegate merged commit 98aab7b into 1.8.x Feb 27, 2026
91 checks passed
@abnegate abnegate deleted the realtime-log-improve branch February 27, 2026 05:55
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