Skip to content

fix(events): parse newline-delimited JSON from Docker event stream#270

Merged
Fahl-Design merged 2 commits into
mainfrom
fix/event-stream-newline-json
Jul 13, 2026
Merged

fix(events): parse newline-delimited JSON from Docker event stream#270
Fahl-Design merged 2 commits into
mainfrom
fix/event-stream-newline-json

Conversation

@Fahl-Design

@Fahl-Design Fahl-Design commented Jul 13, 2026

Copy link
Copy Markdown
Member

Problem

DockerApiClientWrapper::listenForEvents() never invoked its callback — container events were silently dropped.

Root cause: Docker's /events endpoint returns newline-delimited JSON (Content-Type: application/json), not Server-Sent Events. The old loop only processed ServerSentEvent chunks, which a plain Symfony HttpClient never emits (only EventSourceHttpClient does). It also fired a duplicate /events request on every while() iteration.

Empirically confirmed against a live daemon: chunks arrive as FirstChunk + DataChunk, never ServerSentEvent, so the "instanceof ServerSentEvent" branch was dead code.

Fix

  • Buffer raw data chunks, split on newline, decode each complete JSON line, dispatch events where Type equals "container".
  • Denormalize the already-decoded array instead of parsing the JSON a second time via deserialize().
  • Handles payloads split across chunk boundaries via the buffer.
  • Removes the duplicate /events request in the loop condition.
  • Injects an optional event-stream HttpClient (defaults to the socket-bound client in production) so the method is unit testable.

Tests

New unit tests for listenForEvents() using MockHttpClient:

  • dispatches only container events (non-container events ignored)
  • reassembles a JSON object split across two transport chunks
  • skips invalid JSON lines

Verification

  • composer qa (cs:fix + test + stan) green on PHP 8.5.8; CI green on PHP 8.3 / 8.4 / 8.5.
  • End-to-end against a live Docker daemon (via docker-hostfile-sync): start / stop / die / restart events reach the callback and update the hosts file.

Notes

  • Drive-by: cs:fix added a missing closure return type in EventsListenCommand.php.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Fahl-Design, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 37 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8906a762-a68a-43a8-b7fc-f2419448c75d

📥 Commits

Reviewing files that changed from the base of the PR and between fc3d7be and cf60c67.

📒 Files selected for processing (3)
  • src/Client/DockerApiClientWrapper.php
  • src/Command/EventsListenCommand.php
  • tests/Unit/Client/DockerApiClientWrapperTest.php
📝 Walkthrough

Walkthrough

The Docker event listener now processes newline-delimited JSON stream payloads, filters container events, and invokes a callback with deserialized events. The event command callback explicitly declares a void return type.

Changes

Docker event stream handling

Layer / File(s) Summary
Stream parsing and callback contract
src/Client/DockerApiClientWrapper.php, src/Command/EventsListenCommand.php
Stream chunks are buffered and parsed as newline-delimited JSON, container events are deserialized and dispatched, and the listener callback declares void.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Poem

I twitch my nose at each JSON line,
Container events now neatly align.
Chunks join, then flow,
To callbacks they go—
A tidy Docker stream, oh so fine!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title accurately summarizes the main change: parsing Docker event stream JSON instead of SSE.
Description check ✅ Passed The description is directly related to the Docker event-stream parsing fix and its tests.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/event-stream-newline-json

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/Client/DockerApiClientWrapper.php (1)

74-78: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Redundant double JSON decode.

$line is parsed twice: once via json_decode for the Type filter check, and again inside $serializer->deserialize(). Consider denormalizing the already-decoded $eventObject array instead of re-parsing the raw string.

♻️ Avoid re-parsing the same JSON string
                 $eventObject = json_decode(json: $line, associative: true, depth: 512, flags: JSON_THROW_ON_ERROR);
                 if (is_array($eventObject) && ($eventObject['Type'] ?? false) === 'container') {
-                    $event = $serializer->deserialize(data: $line, type: ContainerEvent::class, format: 'json');
+                    $event = $serializer->denormalize(data: $eventObject, type: ContainerEvent::class);

                     $eventCallback($event);
                 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/Client/DockerApiClientWrapper.php` around lines 74 - 78, Update the event
handling around $eventObject and $serializer->deserialize() to denormalize the
already-decoded array instead of passing $line for a second JSON parse. Preserve
the existing container Type filter and eventCallback invocation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/Client/DockerApiClientWrapper.php`:
- Around line 54-80: Import the remaining global functions used in the streaming
loop of the Docker API client wrapper: add function imports for strpos, substr,
trim, and json_validate alongside the existing imports, without changing the
logic around stream processing or event deserialization.

---

Nitpick comments:
In `@src/Client/DockerApiClientWrapper.php`:
- Around line 74-78: Update the event handling around $eventObject and
$serializer->deserialize() to denormalize the already-decoded array instead of
passing $line for a second JSON parse. Preserve the existing container Type
filter and eventCallback invocation.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ace2dbb6-8563-4c6e-b4da-8845c0693c22

📥 Commits

Reviewing files that changed from the base of the PR and between 98301bc and fc3d7be.

📒 Files selected for processing (2)
  • src/Client/DockerApiClientWrapper.php
  • src/Command/EventsListenCommand.php

Comment thread src/Client/DockerApiClientWrapper.php
@Fahl-Design Fahl-Design force-pushed the fix/event-stream-newline-json branch 2 times, most recently from 992309f to 2100c93 Compare July 13, 2026 20:20
Docker's /events endpoint returns newline-delimited JSON with
Content-Type: application/json, not Server-Sent Events. The old loop
only handled ServerSentEvent chunks, which a plain HttpClient never
emits, so listenForEvents() never invoked the callback and container
events were silently dropped.

- Buffer raw data chunks and split on newlines, decoding each complete
  JSON line and denormalizing the decoded array (no second JSON parse).
- Drop the duplicate /events request issued on every loop iteration.
- Inject an optional event-stream HttpClient so the method is unit
  testable via MockHttpClient; production still builds the socket-bound
  client by default.
- Add unit tests for dispatch filtering, chunk buffering and invalid
  JSON handling.

Drive-by: cs:fix adds a missing closure return type in EventsListenCommand.
@Fahl-Design Fahl-Design force-pushed the fix/event-stream-newline-json branch from c2011f9 to cf60c67 Compare July 13, 2026 20:25
@Fahl-Design Fahl-Design merged commit ecd385e into main Jul 13, 2026
6 of 7 checks passed
@Fahl-Design Fahl-Design deleted the fix/event-stream-newline-json branch July 13, 2026 20:28
webproject-bot Bot pushed a commit that referenced this pull request Jul 13, 2026
## [1.4.4](1.4.3...1.4.4) (2026-07-13)

### Bug Fixes

* **events:** parse newline-delimited JSON from Docker event stream ([#270](#270)) ([ecd385e](ecd385e))
@webproject-bot

Copy link
Copy Markdown

🎉 This PR is included in version 1.4.4 🎉

The release is available on GitHub release

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant