Make WordPress Core

Opened 10 years ago

Last modified 6 weeks ago

#39473 new enhancement

get_routes() called multiple times within single REST request causing the rest_endpoints() filter to also fire more than once

Reported by: ruud@… Owned by:
Priority: normal Milestone: Awaiting Review
Component: REST API Version: 4.4
Severity: normal Keywords: good-first-bug has-patch has-unit-tests
Cc: Focuses:

Description

Hi all,

Many thanks for creating the REST API, and also for getting it into core! :)

When I had a closer look at how to integrate this in our projects I noticed something peculiar with the rest_endpoints() filter: it is called multiple times over; in some cases twice, in others three times.

So I did a little digging around and found that the root cause seemed to be the use of get_routes() at multiple locations:

  • in the rest_pre_dispatch filter (rest_handle_options_request)
  • in the rest_post_dispatch filter (rest_send_allow_header)
  • in the dispatch() itself
  • in the get_index() method
  • in the get_namespace_index() method

After looking how these locations interact with each other, I couldn't detect any code which altered the generated route map between consecutive calls to get_routes().

I will add a patch in which I propose to store the generated route map in the class, and re-use that one instead of generating yet again the same array (and also re-filtering the same array).

Since the name 'endpoints' is already taken, and being used in the initialization as well, I thought it would be prune to use another variable name: $route_map, which is also being used in the current doc-block.

I did not profile this patch (not really sure how to do that), so I'm not sure if storing this rather large associative array is a good thing to do. However generating it multiple times (and re-filtering it also) may also be quite 'expensive'.

Thanks,
Ruud

Attachments (5)

39473.patch​ (5.1 KB ) - added by ruud@… 10 years ago.
39473-2.patch​ (2.0 KB ) - added by ruud@… 10 years ago.
Patch against version 4.7.1, extra level of indentation removed, made getter/setter functions protected
39473-3.patch​ (2.1 KB ) - added by ruud@… 10 years ago.
Methods now public, added clarification about use of $route_map vs $endpoints
39473-2023-1.patch​ (3.1 KB ) - added by mreishus 4 years ago.
refreshed for 2023; handling new $route_namespace parameter
39473.diff​ (3.8 KB ) - added by motylanogha 8 months ago.
Refreshed patch for current trunk with route map caching and 4 unit tests. Cache is invalidated on register_route(). All 1052 REST API tests pass

Download all attachments as: .zip

Change History (21)

#1 @ruud@…
10 years ago

  • Component General → REST API
  • Keywords has-patch dev-feedback added

#2 @rmccue
10 years ago

This seems OK, but could potentially break when switching between sites with multisite. I'd be curious to hear from @jnylen0 on that point.

#3 @jnylen0
10 years ago

I'm not worried about this. Code really shouldn't rely on get_routes being recomputed, and I'm not aware of any that does. But if there is a need to do this in the future, said "interesting" code can call set_route_map( null ).

We should also remove the extra level of indentation and most of the whitespace changes in this patch by switching the conditional around:

if ( ! empty( $endpoints ) ) {
    return $endpoints;
}

#4 @ruud@…
10 years ago

Hi Ryan and James,

Thanks for having a look at this patch.

What is your opinion about introducing a new variable $route_map, instead of re-using $endpoints?
I this patch I did not use $endpoints with a test for it being empty because it is not, it gets initialized with the default root endpoint.

I have time to fix any code for this patch today, so let me know.

Thanks,
Ruud

@ruud@…
10 years ago

Patch against version 4.7.1, extra level of indentation removed, made getter/setter functions protected

#5 @ruud@…
10 years ago

Since the $route_map is a protected variable inside this class, I thought it may be appropriate to also use the getter and setter as protected functions for this class.

#6 @jnylen0
10 years ago

The getter/setter functions should be public in case other code needs to manipulate the cached route map.

I think we can resolve the remaining naming issues here by calling the variable inside the method $route_map instead of $endpoints. Think of it this way: $endpoints is the raw endpoints and $route_map is the parsed and sanitized map from a regex to an endpoint.

@ruud@…
10 years ago

Methods now public, added clarification about use of $route_map vs $endpoints

#7 @ruud@…
10 years ago

@jnylen0. I agree with your assessment about the naming issues. Do you also mean to change all references to $endpoints (except the $this->endpoints) to $route_map in get_routes() ?

#8 @TimothyBlynJacobs
6 years ago

  • Keywords needs-refresh needs-unit-tests good-first-bug added; has-patch dev-feedback removed

I don't think we should expose the ability to overwrite the internal request map entirely, I think we should change this to something more specific that only allows for clearing it out. Perhaps ::clear_route_map.

@mreishus
4 years ago

refreshed for 2023; handling new $route_namespace parameter

#9 @mreishus
4 years ago

I'm happy to revive this; get_routes() in the meantime now has a parameter: get_routes( $route_namespace ). I came up with an idea in the attached patch above, but it doesn't feel quite right. Any ideas?

This patch also doesn't solve the problem of get_routes() being called more than once, because the $route_namespace optimization was applied to the main callsite of get_routes(), but not the others. But that could be tackled as a second step.

Last edited 4 years ago by mreishus (previous) (diff)

#10 @obenland
4 years ago

  • Keywords dev-feedback added; needs-refresh removed

#11 @TimothyBlynJacobs
2 years ago

#57455 was marked as a duplicate.

@motylanogha
8 months ago

Refreshed patch for current trunk with route map caching and 4 unit tests. Cache is invalidated on register_route(). All 1052 REST API tests pass

#12 @motylanogha
8 months ago

  • Keywords has-patch has-unit-tests added; needs-unit-tests dev-feedback removed

This ticket was mentioned in ​PR #11694 on ​WordPress/wordpress-develop by ​@motylanogha.


7 months ago
#13

get_routes() is called multiple times per request (route matching, schema generation, OPTIONS handling). The result is deterministic between route registrations, so this PR memoizes the per-namespace map on the server instance and busts the cache whenever register_route() mutates $this->endpoints.

Tests cover:

  • rest_endpoints filter fires once across repeated calls
  • Cache keyed by namespace
  • Cache invalidated when a new route is registered
  • Cached and uncached results are identical

Note for reviewers: caching the post-rest_endpoints-filter result means filters added after the first call to get_routes() no longer take effect for that request. This matches the perf goal but is a documented filter-contract change worth weighing — happy to refactor to cache only the pre-filter map if reviewers prefer.

#14 @motylanogha
5 months ago

PR #11694 still applies cleanly to current trunk (7.1-alpha) with full CI green, and includes unit tests covering the memoized per-namespace route map and its invalidation on register_route(). Requesting a review for 7.1 consideration.

​@motylanogha commented on ​PR #11694:


8 weeks ago
#15

Rebased cleanly onto current trunk to resolve the conflict in WP_REST_Server::get_routes() (incorporating the trunk @phpstan-var annotation) and dropped the redundant PHPStan baseline commit. All 133 Tests_REST_Server tests pass cleanly locally with 0 PHPCS violations.

#16 @mahbubwpwist
6 weeks ago

Test Report

Patch tested: ​https://github.com/WordPress/wordpress-develop/pull/11694 (head e62466b, includes current trunk)

Environment

  • WordPress: 7.2-alpha-63166-src (trunk ab2373a)
  • PHP: 8.4.23 (CLI, no OPcache, no Xdebug)
  • Database: MySQL 8.0.35
  • OS: macOS 15.3
  • Plugins: none
  • Run through PHPUnit, single site and multisite (-c tests/phpunit/multisite.xml)

Tests_REST_Server passes with the PR applied (133 tests).

1. rest_endpoints filter calls per request

Fresh WP_REST_Server for each request, same as a real request:

Request trunk PR
GET / 2 1
GET /wp/v2 2 2
OPTIONS /wp/v2/posts 1 1
GET /wp/v2/types 1 1

GET /wp/v2 does not improve because the cache is keyed by namespace, so get_routes() and get_routes( 'wp/v2' ) each still run the filter once.

2. Behavior change: the cached map is the filtered result

Because the map is cached after rest_endpoints runs, any callback whose output depends on context keeps its first result for the life of the server:

Scenario trunk PR
Filter added after the first get_routes() call applied ignored
Filter hides /wp/v2/users unless current_user_can( 'manage_options' ), then wp_set_current_user( $admin_id ) route appears route still hidden
Multisite: filter depends on get_current_blog_id(), then switch_to_blog() map changes main site's map returned
register_rest_route() after the cache is filled route appears route appears (invalidation works)

The multisite case is the concern raised in comment:2.

Minimal reproduction for the user case:

<?php
add_filter( 'rest_endpoints', function ( $endpoints ) {
        if ( ! current_user_can( 'manage_options' ) ) {
                unset( $endpoints['/wp/v2/users'] );
        }
        return $endpoints;
} );

$server = rest_get_server();

wp_set_current_user( 0 );
var_dump( isset( $server->get_routes()['/wp/v2/users'] ) ); // false on both.

wp_set_current_user( $admin_id );
var_dump( isset( $server->get_routes()['/wp/v2/users'] ) ); // trunk: true, PR: false.

3. Cost of the call being saved

One uncached get_routes() call on trunk (average of 2,000 calls, 3 runs, stable within 3%):

  • Core routes only (133 routes): about 0.07 ms
  • Core plus 400 extra routes (534 routes): about 0.30 ms

So the PR saves at most one such call on GET /, and none on the other requests above. End-to-end dispatch timings for these requests differed by less than the run-to-run noise.

Notes

  • With the saving this small, it may not be worth changing the filter contract. Since rest_endpoints runs before normalization, caching only the unfiltered map would not save much either.
  • If the cache stays, clearing it on switch_blog and set_current_user would cover two of the cases above, but not a filter added after the first call.
  • Minor: $route_map_cache has @since 6.9.0; this would need the version it ships in.
Note: See TracTickets for help on using tickets.