Skip to content

fix: route SSE streaming through WP HTTP API + http_api_curl - #15

Merged
nolderoos merged 7 commits into
mainfrom
fix/curl-to-http-api
May 14, 2026
Merged

nolderoos merged 7 commits into
mainfrom
fix/curl-to-http-api

Conversation

@nolderoos

@nolderoos nolderoos commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #14

What

Refactors OpenTrust_Chat_Provider::stream_post() to drive outbound SSE requests through wp_safe_remote_post(). CURLOPT_WRITEFUNCTION / CURLOPT_HEADERFUNCTION (and the connect-timeout split) are installed via a one-shot, URL-scoped http_api_curl action and removed unconditionally after the request.

Why

wp.org review round 1, issue 4. The only raw curl_init/curl_exec block in the plugin is replaced with the documented WP HTTP API escape hatch. Real-time token streaming, visitor abort, host allowlist, SSL verify, no-redirect, and the describe_streaming_error() rate-limit log path are all preserved. Falls back to a clean error return when curl_init is unavailable so non-cURL transports never silently buffer.

QA gate

Open /trust-center/ask/, ask a multi-token question, confirm tokens stream word-by-word. Click "Stop" mid-stream and confirm the request aborts within ~1 s.

Summary by CodeRabbit

  • Bug Fixes

    • Improved chat streaming reliability with better handling of non-2xx responses, partial stream buffering, and enhanced diagnostic logging.
    • Added runtime checks to surface when PHP cURL or the WordPress cURL transport are required for streaming.
  • Documentation

    • Added translatable messages for cURL requirements and updated translation catalog metadata and source references.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • ✅ Review completed - (🔄 Check again to review again)
📝 Walkthrough

Walkthrough

Refactors OpenTrust_Chat_Provider::stream_post() to use wp_safe_remote_post() with a request-scoped http_api_curl filter that installs cURL header/write callbacks for incremental SSE parsing, early-status capture, error-body accumulation, connection-abort handling, and consistent error reporting. Updates POT with new cURL requirement messages and timestamp.

Changes

SSE Streaming Transport Refactor

Layer / File(s) Summary
Streaming state setup and prerequisites
includes/providers/class-opentrust-chat-provider.php
Checks for PHP cURL extension, encodes the JSON payload, and initializes a shared mutable state object used by the injected cURL callbacks and post-request handling.
Inject http_api_curl header/write callbacks
includes/providers/class-opentrust-chat-provider.php
Registers a request-scoped http_api_curl filter that sets CURLOPT_HEADERFUNCTION to capture early HTTP status/headers and CURLOPT_WRITEFUNCTION to buffer SSE lines on 2xx responses or accumulate error bodies on non-2xx responses; honors connection_aborted() to cancel the transfer.
Request wiring, status derivation, and error handling
includes/providers/class-opentrust-chat-provider.php
Attaches/removes the filter around wp_safe_remote_post(), verifies the cURL transport was used, derives the final HTTP code (favoring early status), flushes a trailing SSE buffer on success, and normalizes WP_Error and non-2xx responses with describe_streaming_error() and logging.

i18n catalog updates

Layer / File(s) Summary
POT header and message additions
languages/opentrust.pot
Updated POT-Creation-Date, added messages AI streaming requires the PHP cURL extension. and AI streaming requires the WordPress cURL transport., and adjusted source reference line numbers for Provider returned HTTP %d.

Sequence Diagram(s)

sequenceDiagram
  participant Method as stream_post()
  participant WP as wp_safe_remote_post()
  participant Filter as http_api_curl Filter
  participant cURL as cURL Handle
  participant SSE as SSE Parser
  participant ErrorBuf as Error Buffer

  Method->>Method: Initialize shared state
  Method->>WP: Register filter and call (Accept: text/event-stream)
  WP->>Filter: Provide cURL handle during setup
  Filter->>cURL: Set CURLOPT_HEADERFUNCTION
  Filter->>cURL: Set CURLOPT_WRITEFUNCTION
  cURL->>Filter: Header callback (captures early HTTP status)
  loop For each response chunk
    cURL->>Filter: Write callback invoked with chunk
    alt early status is 2xx
      Filter->>SSE: Buffer until newline, emit complete SSE lines
      SSE->>Method: Deliver SSE event lines
    else non-2xx
      Filter->>ErrorBuf: Accumulate response body (no SSE parsing)
    end
    alt connection_aborted()
      Filter-->>cURL: Return 0 (abort transfer)
    end
  end
  cURL-->>WP: Transfer complete
  WP-->>Method: Return response
  Method->>Method: Flush trailing SSE buffer (if 2xx) and derive final HTTP code
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 In burrows where the callbacks play,

cURL hands tokens to WP's way.
Lines arrive and errors hide,
The rabbit watches streams collide.
A hop, a log, then tidy stride. 🥕

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title concisely and accurately captures the main objective: routing SSE streaming through the WordPress HTTP API via the http_api_curl hook instead of raw cURL.
Linked Issues check ✅ Passed The PR fully implements issue #14 requirements: routes SSE POST through wp_safe_remote_post(), installs CURLOPT callbacks via scoped http_api_curl hook, preserves real-time streaming and abort behavior, maintains host allowlist and SSL verification, guarantees filter removal, and returns clean error when curl_init unavailable.
Out of Scope Changes check ✅ Passed All changes are directly in-scope: refactored streaming implementation in class-opentrust-chat-provider.php and corresponding translatable string updates in languages/opentrust.pot.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/curl-to-http-api

Comment @coderabbitai help to get the list of available commands and usage tips.

@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

🤖 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 `@includes/providers/class-opentrust-chat-provider.php`:
- Around line 527-535: Initialize a curl_hook_ran flag on the $state object
(e.g., 'curl_hook_ran' => false) when you build $state; inside the http_api_curl
filter callback (the $filter closure that calls curl_init() and sets
CURLOPT_HEADERFUNCTION/WRITEFUNCTION) set $state->curl_hook_ran = true; after
you call remove_action(...) verify $state->curl_hook_ran is true and if not set
an appropriate error on $state (e.g., populate $state->error_body and return a
WP_Error or fail the request) so streaming doesn’t silently fall back when a
non-cURL transport was selected.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 929de1e4-d515-47c6-bcfd-c8cfd46f699c

📥 Commits

Reviewing files that changed from the base of the PR and between 0a38992 and 070609c.

📒 Files selected for processing (1)
  • includes/providers/class-opentrust-chat-provider.php

@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

🤖 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 `@includes/providers/class-opentrust-chat-provider.php`:
- Around line 599-613: The http hook added with add_action('http_api_curl',
$filter, 10, 3) might not be removed if wp_safe_remote_post() throws, so wrap
the wp_safe_remote_post($url, [...]) invocation in a try/finally block: call
add_action(...) before the try, perform the wp_safe_remote_post(...) inside the
try, and always call remove_action('http_api_curl', $filter, 10) inside the
finally so the SSE-specific curl handler ($filter) is unregistered even on
exceptions; reference the existing symbols add_action, wp_safe_remote_post,
$filter, and remove_action when making the change.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: cef3a939-0847-49be-bb87-d8c952577533

📥 Commits

Reviewing files that changed from the base of the PR and between 8917a73 and 5fabfce.

📒 Files selected for processing (2)
  • includes/providers/class-opentrust-chat-provider.php
  • languages/opentrust.pot

@nolderoos

Copy link
Copy Markdown
Collaborator Author

Claude Code review

Verdict: APPROVE

This is a clean, faithful implementation of the round-2 analysis. The single raw-cURL block at includes/providers/class-opentrust-chat-provider.php:511 is replaced with wp_safe_remote_post() driving an http_api_curl-scoped callback. The reviewer's WP.org policy concern is resolved.

Checks performed

  • No raw cURL function calls remain in plugin code. grep -rn "curl_" --include="*.php" includes/ shows: one function_exists('curl_init') feature-detect (line 517), curl_setopt calls only inside the http_api_curl callback (lines 549–595, between the documented phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_setopt annotation), plus benign state-variable names. No curl_init/curl_exec/curl_close/curl_getinfo/curl_errno/curl_error survive.
  • Filter is URL-scoped and tightly bracketed. add_action('http_api_curl', $filter, 10, 3) at line 599 is paired with remove_action(...) in a finally block (line 616). The callback guards on $filter_url !== $state->url (line 544), so concurrent outbound calls in the same PHP request are untouched. Filter detaches even if $on_line throws inside WRITEFUNCTION.
  • SSRF allowlist preserved. host_allowed($url) still gates at line 512 before any HTTP dispatch. wp_safe_remote_post() adds wp_http_validate_url() as belt-and-suspenders.
  • Timeouts. 'timeout' => $timeout passed explicitly (line 603); the connect-vs-total split is preserved inside the filter by setting CURLOPT_CONNECTTIMEOUT = 15 on the live handle (line 549), since WP collapses both into one arg.
  • Error handling. is_wp_error($response) check at line 636; HTTP status read from $state->early_status (header callback) with wp_remote_retrieve_response_code() as fallback (line 627). The describe_streaming_error() rate-limit log path is intact at line 646.
  • Custom headers preserved. array_merge(['Content-Type'…,'Accept'…], $headers) at line 607 keeps subclass headers (x-api-key, anthropic-version, Authorization) intact and lets defaults be overridden if needed.
  • Streaming semantics preserved. CURLOPT_WRITEFUNCTION still splits on \n and calls $on_line() synchronously per line; connection_aborted() short-write at lines 574/590 preserves the visitor-abort path.
  • No fopen / stream_socket_client / fsockopen fallback. Confirmed by grep -rnE "fopen|stream_socket_client|fsockopen|file_get_contents.*http" includes/ — only an unrelated fopen('php://output') for CSV streaming in class-opentrust-admin-questions.php.
  • Fail-loud sentinel. The curl_hook_ran flag (line 535, set at 547, checked at 621) returns a clean error if WP picks the Streams transport, so visitors never get silently buffered output. The pre-flight function_exists('curl_init') check at line 517 covers the cURL-missing case.

QA gate (per analysis.md §"Open verification")

The author's PR body acknowledges the single critical manual gate: open /trust-center/ask/, confirm tokens stream word-by-word (not all-at-once), and confirm "Stop" aborts within ~1 s. The Requests transport invokes WRITEFUNCTION synchronously during curl_exec (wp-includes/Requests/src/Transport/Curl.php:205), so this should hold — but it remains the one item the static review cannot verify. Please confirm the QA pass before merging.

Minor non-blocking observations

  • Redundant but harmless: curl_setopt($handle, CURLOPT_FOLLOWLOCATION, false) at line 550 duplicates 'redirection' => 0 passed to wp_safe_remote_post() (line 604). Belt-and-suspenders — keep it or drop it, either is fine.
  • SSL verify already on by default. 'sslverify' => true (line 605) is the WP default but explicit is good for review legibility.
  • http_request_args exposure. As called out in analysis.md §"Risk / edge cases", admins can now intercept via http_request_args — same surface as any other wp_safe_remote_* call. Worth a brief inline note if you want belt-and-suspenders documentation, but not required.

— Claude (automated review on behalf of @nolderoos)

nolderoos and others added 2 commits May 13, 2026 15:38
The previous code installed both CURLOPT_WRITEFUNCTION and CURLOPT_HEADERFUNCTION
via the http_api_curl filter. Replacing HEADERFUNCTION clobbered WP's Requests Curl
transport stream_headers() method, leaving its internal $this->headers buffer empty.
After curl_exec, Requests::parse_response() called strpos('', "\r\n\r\n"), got false,
and threw \WpOrg\Requests\Exception('Missing header/body separator', 'requests.no_crlf_separator')
out of wp-includes/Requests/src/Requests.php:737. WP wrapped it as WP_Error, the
upstream Anthropic call returned ['ok' => false, 'error' => 'Missing header/body
separator'], and the chat UI rendered that exact string as a red error banner
beneath an empty assistant bubble — even on successful upstream streams.

The round-2 analysis at wporg-review/04-curl-vs-http-api/analysis.md:16 predicted
$this->headers would stay empty but assumed WP would "bubble up a response array
with empty body, empty headers, falsy code." It does not; parse_response throws
before WP can wrap the response.

Fix:
  - Remove the CURLOPT_HEADERFUNCTION setopt entirely so Requests' stream_headers
    runs unmodified and accumulates the header block ending in \r\n\r\n. After
    our WRITEFUNCTION consumes the body, Requests' parser finds the separator
    (headers + empty body) and returns a normal response array.
  - Capture early_status lazily inside WRITEFUNCTION via curl_getinfo($ch,
    CURLINFO_HTTP_CODE). cURL guarantees the status line is parsed before any
    body callback fires, so this is reliable. Keeps the same error-body routing
    semantics for non-2xx upstream responses.
  - After wp_safe_remote_post returns, copy headers from
    wp_remote_retrieve_headers($response) into $state->response_headers so
    describe_streaming_error() still surfaces retry-after / anthropic-ratelimit-*
    / x-ratelimit-* hints in the error path.
  - Add a load-bearing comment above the filter explaining why HEADERFUNCTION
    must not be re-added.

Net diff: +38 / -28. No change to streaming semantics, visitor-abort handling,
host allowlist, SSL verification, or error-body shape. The wp.org reviewer's
constraint (route outbound HTTP through wp_safe_remote_post / wp_safe_remote_get
and use http_api_curl only as the documented escape hatch for setopt) is
preserved — and tightened, since this drops one setopt call.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Line refs in includes/providers/class-opentrust-chat-provider.php shifted
when the CURLOPT_HEADERFUNCTION block was deleted in d54bc42:
  - "AI streaming requires the WordPress cURL transport.": 622 → 620
  - "Provider returned HTTP %d": 664 → 674, 719 → 729

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@nolderoos
nolderoos merged commit 23aa31f into main May 14, 2026
10 checks passed
@nolderoos
nolderoos deleted the fix/curl-to-http-api branch May 14, 2026 12:12
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.

Replace raw cURL with WP HTTP API + http_api_curl filter for SSE streaming

1 participant