Skip to content

Add HTTP client timeouts and remember unreachable package providers - #17127

Open
Jako wants to merge 3 commits into
modxcms:3.xfrom
Jako:fix-http-client-timeout-3.x
Open

Jako wants to merge 3 commits into
modxcms:3.xfrom
Jako:fix-http-client-timeout-3.x

Conversation

@Jako

@Jako Jako commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

The automatic update checks on manager pages (Package Management grid and Updates dashboard widget) use the shared HTTP client, which has no timeouts. If a provider can't be reached, each page load blocks until the OS gives up. On macOS that took about 75 s per package:

cURL error 28: Failed to connect to modstore.pro port 443 after 75002 ms

Failed checks were also cached as "no update", retried for every package once the cache expired, and logged once per package.

HTTP client timeouts. Two new system settings feed the shared Guzzle client in modX::buildHttpClientOptions():

  • http_connect_timeout (default 5 s)
  • http_stall_timeout (default 30 s): aborts a request that receives no data for that time, so large downloads that are still progressing aren't affected.

0 disables either timeout. Both require cURL.

Unreachable providers.

  • modTransportProvider::request() catches PSR-18 network exceptions. For the rest of the request, the provider counts as unreachable: further calls return immediately, and the failure is logged once per provider.
  • The failure is cached in providers/unreachable/{id} in the packages partition, so there's no schema change. A successful response or removing the provider clears it.
  • Automatic checks skip a provider that failed within auto_check_pkg_updates_cache_expire. Failed results are no longer cached. Manual actions always try the provider.
  • The UI shows the status: a status column with the error as a tooltip in the Providers grid, a warning icon in the Package Management grid, and a row for each unreachable provider with a "Providers" button in the Updates widget.

Hardening.

  • Credentials (api_key, username) are removed from all logged and stored client error messages.
  • latest() uses libxml_use_internal_errors(). Non-XML responses (such as a maintenance page) now return provider_err_invalid_xml instead of emitting warnings or, in the package-name branch, a fatal error.

How to test

  1. Point a provider's service URL to an unreachable host (e.g. https://10.255.255.1/) and assign a package to it.
  2. Enable auto_check_pkg_updates and clear core/cache/packages/.
  3. Open the dashboard or Package Management. The page should give up after http_connect_timeout and log the error once. Before, it hung about 75 s per package.
  4. Reload within the cache interval. The provider isn't requested again.
  5. Check that the status shows in all three places and that no api_key appears in the log or tooltip.
  6. Restore the URL and click "Check for Updates". The status clears, and "reachable again" is logged at INFO level.
  7. Change the timeout settings and confirm the limits follow them. 0 restores the old behaviour.

Related issue(s)/PR(s)

Resolves #17126

Compatibility notes

Universal. Setup creates the new settings. Until then, getOption() falls back to the defaults. The stall timeout is only applied if the cURL constants exist.

Breaking change assessment

  • No changes to existing public signatures.
  • New public methods: modTransportProvider::getUnreachable(), getUnreachableMessage(), isUnreachable(?int $interval = null), setUnreachable(?array $unreachable), and Workspace/Packages/GetList::getProvider(). modTransportProvider::remove() is overridden to clear the cached status.
  • Behaviour changes:
    • All requests from the shared client now use a 5 s connect timeout and a 30 s stall timeout. Both are configurable, and 0 disables them.
    • A provider that fails to connect is skipped by automatic checks until the cache interval passes.

Test coverage

modTransportProviderTest.php was extended with a Guzzle MockHandler, so no network access is needed. It covers:

  • a single request per unreachable provider
  • credential redaction
  • clearing the status on success and on removal
  • HTTP errors not being treated as connection failures
  • the retry interval
  • non-XML responses

Contributors

AI tool use

Claude Code (Claude Opus 5.5) traced the code paths and drafted the implementation, tests and description. The changes were checked on a local MODX 3.x install with a mocked HTTP client.

🤖 Generated with Claude Code

@Jako
Jako requested review from Mark-H and opengeek as code owners November 6, 2026 12:45
@codecov

codecov Bot commented Nov 6, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 61.11111% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 22.19%. Comparing base (5a484de) to head (5eef6bd).
⚠️ Report is 41 commits behind head on 3.x.

Files with missing lines Patch % Lines
.../src/Revolution/Transport/modTransportProvider.php 0.00% 6 Missing ⚠️
...volution/Processors/Workspace/Packages/GetList.php 0.00% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##                3.x   #17127      +/-   ##
============================================
+ Coverage     21.67%   22.19%   +0.51%     
- Complexity    10786    10839      +53     
============================================
  Files           566      567       +1     
  Lines         33149    33317     +168     
============================================
+ Hits           7186     7394     +208     
+ Misses        25963    25923      -40     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Mark-H

Mark-H commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator

This PR adds a separate update_check_http_client service, which is used only by the automatic update checks:

This line stands out to me: architecturally speaking, if it's only used by one thing, why is it a global service? Can we let modTransportProvider handle this internally?

@Jako
Jako force-pushed the fix-http-client-timeout-3.x branch from 706c7b7 to 0c21c75 Compare November 6, 2026 13:49
@Jako

Jako commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, I have changed it to be added only in the modTransportProvider.

There is one drawback: if an integrator registers a client that isn't Guzzle, update checks still work but run without the timeouts. PSR-18 has no standard way to pass them. That was the reason why Claude did not suggested this.

@opengeek opengeek left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for tracking this down, and for the quick rework. Passing per-request options to the shared client is much better than a second service: custom ClientInterface registrations are respected, and nothing can go missing from the container. However, I would like to see a change to where the main fix lives, and there are a couple of things to fix in the current code.

The fix belongs on the shared client

The hang in #17126 happens while connecting (Failed to connect to modstore.pro port 443 after 75002 ms). The underlying problem is that the shared client has no connect_timeout. This PR covers only the automatic checks, so the manual "Check for Updates" button, provider browse/search, downloadUrl(), SoftwareUpdate/GetFile and dependency resolution all still block for 75 s or more on the same unreachable provider. In libcurl the connect phase covers DNS, TCP and the TLS handshake. Capping it doesn't limit how long a working transfer can take, so a default is safe for every request.

A server that accepts the connection and then goes silent can be handled on the shared client too, without a total cap that would kill large downloads. curl's low-speed limit aborts only a transfer that has stopped making progress, and Guzzle passes it through:

private function buildHttpClientOptions() {
    $opts = [];
    // ... proxy options as today ...

    $connectTimeout = (float)$this->getOption('http_connect_timeout', null, 5, true);
    if ($connectTimeout > 0) {
        $opts['connect_timeout'] = $connectTimeout;
    }
    $stallTimeout = (int)$this->getOption('http_stall_timeout', null, 30, true);
    if ($stallTimeout > 0 && defined('CURLOPT_LOW_SPEED_TIME')) {
        $opts['curl'] = [
            CURLOPT_LOW_SPEED_LIMIT => 1,
            CURLOPT_LOW_SPEED_TIME => $stallTimeout,
        ];
    }
    return $opts;
}

(The setting names and defaults are only suggestions. They'd need entries in transport.core.system_settings.php and the lexicon, as in this PR. Guzzle's read_timeout won't do this job, because it only applies with stream => true. The stream handler ignores the curl options, but it does honor connect_timeout.)

Please make that the core of the PR. Keeping your per-request override for the automatic checks on top of it is fine, since a hard total cap on the page-render path is reasonable. In that case, please also cover the two points below.

If the per-request override stays

  • send() doesn't behave like sendRequest(). Client::sendRequest() forces http_errors => false and allow_redirects => false, but send() uses Guzzle's defaults: it throws on 4xx/5xx and follows up to 5 redirects. On the update-check path, a provider error response now becomes an exception that request() logs as an error, and the provider's XML <error> message is lost. Every cold-cache dashboard load writes one error-log entry per affected package. Merging ['http_errors' => false, 'allow_redirects' => false] into the options keeps the PSR-18 behaviour.
  • Empty settings turn the timeouts off. getUpdateCheckRequestOptions() calls getOption() without skipEmpty. If an admin clears one of the number fields, the value is saved as '', (float)'' is 0, and the timeout is disabled. Please pass true as the 4th argument.

Smaller points:

  • Setting names. The auto_check_pkg_updates_* settings also apply to the MODX core check, which runs even when auto_check_pkg_updates is off. The names should reflect that.
  • Connect timeout lexicon. "Use 0 to wait indefinitely" isn't true: with cURL, 0 falls back to libcurl's 300 s connect default.
  • Non-Guzzle clients. A non-Guzzle PSR-18 client silently gets no timeouts. That's fine, but it's worth saying so in the setting description.
  • Long line. The sendRequestWithOptions() signature is 142 characters.

Skip a provider once it has failed

Timeouts apply to each request, so the total still grows with the number of packages. Ten extras from one dead provider cost 10 × the connect timeout, and with a provider that connects and then stalls, 10 × the stall or total timeout. Once a provider fails during a checkForUpdates() run, please record that (e.g. in providerCache) and skip that provider's remaining packages. Without this, the dashboard can still hang for a long time.

Follow-up (not blocking)

When the core check fails, widget.updates.php caches the result for an hour, and updates.tpl then shows MODX as up to date. That isn't new, but a tighter timeout makes it more likely, and it could hide a security release. A short cache lifetime for failed checks, and a "couldn't check" state, would be worth a separate PR.

A test with a mock client would also be good, covering the getClient() requestFactory fix and how the options are passed.

Happy to help with any of this. Let me know if you see a case where a shared connect timeout plus the stall limit doesn't cover something the per-request timeouts do.

@Jako
Jako force-pushed the fix-http-client-timeout-3.x branch from 0c21c75 to 88f4ad8 Compare November 10, 2026 16:12
The shared HTTP client has no timeouts, so an unreachable or hanging
package provider blocks the manager until the OS gives up on the
connection (about 75 seconds per package on macOS). The automatic update
checks of the Extras grid and the Updates dashboard widget run while the
page is rendered, so a single dead provider could block the page load
for minutes.

HTTP client timeouts:
- Add the http_connect_timeout (default 5 seconds) and http_stall_timeout
  (default 30 seconds) system settings and use them as defaults of the
  shared Guzzle client in modX::buildHttpClientOptions(). The stall
  timeout aborts a request that receives no data for that time (cURL
  low speed limit), so large but progressing downloads are not affected.
  A value of 0 disables the respective timeout.

Unreachable providers:
- modTransportProvider::request() catches PSR-18 network exceptions
  (connection failed or timed out) separately. The provider is then
  remembered as unreachable for the current request, further requests to
  it return immediately, and the failure is logged once per provider
  instead of once per package.
- The failure (first failure, last try and error message) is stored in
  the unused properties field of the provider, so no schema change is
  needed. It is removed by the next successful response. The query string
  is removed from the stored and logged error message, since it contains
  the provider credentials.
- The automatic update check skips a provider that failed within the
  auto_check_pkg_updates_cache_expire time and no longer caches the
  result of a failed check, so updates show up as soon as the provider is
  reachable again. Manual actions always try the provider.
- The providers grid shows the connection status with the error as a
  tooltip, the Extras grid shows a warning icon next to the provider
  name, and the Updates dashboard widget lists each unreachable provider
  with a link to the providers tab.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Jako
Jako force-pushed the fix-http-client-timeout-3.x branch from 88f4ad8 to 9b94cec Compare November 10, 2026 16:19
@Jako Jako changed the title Use short timeouts for the automatic update checks Add HTTP client timeouts and remember unreachable package providers Nov 10, 2026
@Jako

Jako commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor Author

I have recreated the PR on base of your buildHttpClientOptions extension. The provider timeout check stores negative results in the properties of the provider (this can be separated into new added columns too) and lists a provider and its extras with a warning in the grids and in the dashboard grid.

image image image

A test with a mock client is added too.

@Jako

Jako commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

I try to fix the tests tomorrow.

@Jako
Jako force-pushed the fix-http-client-timeout-3.x branch from e4628e7 to 98bca1f Compare November 11, 2026 10:38
Test modTransportProvider with a Guzzle MockHandler that replaces the
shared HTTP client service, so no network access is needed. The tests
cover remembering an unreachable provider during the request, storing
the failure without the provider credentials, keeping the first failure
time, clearing the failure after a response, not treating HTTP errors as
connection failures and the retry interval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Jako
Jako force-pushed the fix-http-client-timeout-3.x branch from 98bca1f to be7e0e9 Compare November 11, 2026 10:42
@Jako

Jako commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

The tests are fixed.

@Jako
Jako requested a review from opengeek November 11, 2026 10:46

@opengeek opengeek left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for fixing the tests. CI is green, and the provider tests pass for me locally on PHP 8.1. The timeout part is where I wanted it. There are two changes I would like to see before merging.

Please store the unreachable state in the cache, not the provider record

Keeping it in the provider's properties column means a page view writes to the database. It also bumps updated (ON UPDATE CURRENT_TIMESTAMP), two concurrent requests can overwrite each other's read-modify-write, and runtime state ends up in a record admins edit. Please keep it in the packages cache partition instead, e.g. one entry per provider ID that expires after the package update cache interval. That keeps the same skip-and-retry behaviour, and the grids and widget can still show "since" and "last try" from the entry. It's fine that clearing the cache resets it.

Please take the expiry directly from auto_check_pkg_updates_cache_expire. Don't use PackagesGetList::$updatesCacheExpire for it: SoftwareUpdate/GetList creates that processor without calling initialize(), so on the dashboard the value stays at its default of 300 s, not the configured 15 minutes.

Please update the PR description

It still describes the first version: the update_check_http_client service, setClient(), the auto_check_pkg_updates_* settings, and "No unit tests added". The "How to test" steps and the breaking change assessment need updating too, since the timeouts now apply to every outgoing request through the shared client. Please also state the remaining worst case: a provider that accepts the connection and then sends nothing costs one page load up to http_stall_timeout per retry interval.

A correction from me

In my earlier review I said that Guzzle's stream handler honors connect_timeout. It doesn't: StreamHandler only supports timeout and read_timeout. Please add "Requires the cURL extension." to the http_connect_timeout description, as you already did for the stall timeout.

Optional

  • Credential redaction. It only applies in the NetworkExceptionInterface branch, and it replaces the locally built $uri. Redacting the query string from (string)$request->getUri() would be sturdier, and the generic ClientExceptionInterface branch still logs the full URI, including api_key.
  • Non-XML responses. libxml_use_internal_errors() in latest() would stop the PHP warning on a non-XML provider response.
  • Dashboard button label. For an unreachable provider, the button says "Update" but opens the Providers tab. "View" or "Providers" would be clearer.

Thanks again, this is close.

Unreachable providers:
- Store the failed connection in the MODX cache (providers/unreachable/{id}
  in the packages partition) instead of the provider properties field. The
  provider row is no longer saved during an update check, and the cache
  entry is removed together with the provider.
- Take the retry interval of isUnreachable() directly from the
  auto_check_pkg_updates_cache_expire setting. SoftwareUpdate/GetList
  creates the packages GetList processor without initialize(), so the
  dashboard widget used the default of 300 seconds instead of the setting.

Provider requests:
- Remove the query string with the provider credentials from the error
  message of every client exception, based on the URI of the sent request.
  The generic client exception branch logged the full URI with the API key.
- Parse the responses in latest() with internal libxml errors, so a non-XML
  response does not emit PHP warnings. The package name branch now returns
  provider_err_invalid_xml instead of calling getName() on false.

Manager:
- Label the dashboard button of an unreachable provider "Providers", since
  it opens the providers tab.
- Mention that the HTTP connect timeout requires the cURL extension.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Jako
Jako requested a review from opengeek November 16, 2026 22:29
@Jako

Jako commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author

Claude asked one thing during going through the requested changes: getRepositories(), transfer(), verify() and the other simplexml_load_string() calls still parse without loadXml(). Some of them also have no check for a failed parse. Should them be switched too?

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.

[Bug]: A not responding package provider is causing timeouts

3 participants