|
/** |
|
* Tell a Next.js front end to revalidate when WPGraphQL Smart Cache purges. |
|
* |
|
* Paste into a snippets plugin with scope "run everywhere", or use as an |
|
* mu-plugin. With Code Snippets, omit the opening <?php tag. |
|
* |
|
* Without this, a decoupled front end using ISR serves stale pages until its |
|
* revalidate window lapses AND something requests the page. On a low-traffic |
|
* URL that can be a long time, and a deleted post keeps rendering at its old |
|
* address in the meantime. |
|
* |
|
* This hooks Smart Cache's `graphql_purge` rather than WordPress's save and |
|
* delete hooks, so it inherits all of Smart Cache's work: it already decided |
|
* the change is public and cache-relevant, and it already tracks terms, users, |
|
* menus and media, not just posts. Smart Cache emits a cache KEY rather than a |
|
* URL, so the only job left here is turning keys into paths. |
|
* |
|
* No plugin patch needed. `graphql_purge` is a public action and the keys are |
|
* plain `Relay::toGlobalId()` values, which is `base64("type:id")`. |
|
* |
|
* A more general purge-webhook approach lives at |
|
* https://gist.github.com/jasonbahl/684f4a39ee7988086559df67d1bdab35 |
|
*/ |
|
|
|
define( 'REVALIDATE_ENDPOINT', 'https://example.com/api/revalidate' ); |
|
|
|
// The same value as WPGRAPHQL_REVALIDATE_SECRET in the front end's environment. |
|
define( 'REVALIDATE_SECRET', '' ); |
|
|
|
/** |
|
* Paths that are affected by any content change. |
|
* |
|
* A post appears on more than its own URL, so revalidating only the permalink |
|
* leaves the archive and the home page stale. |
|
*/ |
|
function revalidate_always_paths() { |
|
return apply_filters( 'revalidate_always_paths', [ '/', '/blog' ] ); |
|
} |
|
|
|
/** |
|
* Whether to log what is queued and what the front end reported back. |
|
* |
|
* Failures are always logged. This only controls the chatty lines: the paths |
|
* in each batch and the endpoint's success count. Turn it on while wiring this |
|
* up, because a revalidation that silently does nothing looks exactly like one |
|
* that worked. |
|
* |
|
* add_filter( 'revalidate_debug', '__return_true' ); |
|
*/ |
|
function revalidate_debug() { |
|
return (bool) apply_filters( 'revalidate_debug', defined( 'WP_DEBUG' ) && WP_DEBUG ); |
|
} |
|
|
|
function revalidate_log( $message ) { |
|
if ( ! revalidate_debug() ) { |
|
return; |
|
} |
|
|
|
error_log( '[revalidate] ' . $message ); |
|
} |
|
|
|
/** |
|
* Path portion of a URL, or null. |
|
* |
|
* Only the path is sent. get_permalink() and friends build on home_url(), so |
|
* on a headless install where home_url points at the front end these are |
|
* already the right origin, but the front end should decide what a path maps |
|
* to regardless. |
|
*/ |
|
function revalidate_path( $url ) { |
|
if ( ! $url || is_wp_error( $url ) ) { |
|
return null; |
|
} |
|
|
|
$path = wp_parse_url( $url, PHP_URL_PATH ); |
|
|
|
if ( ! $path ) { |
|
return null; |
|
} |
|
|
|
// Match the front end's route exactly. WordPress permalinks end in a |
|
// slash; Next.js defaults to `trailingSlash: false` and 308s `/foo/` to |
|
// `/foo`, so its cache is keyed on the unslashed form. Sending the slashed |
|
// path is the worst kind of wrong here: the endpoint happily reports |
|
// `revalidated` for a path that is not a route, so it looks like it works |
|
// while nothing is rebuilt. Flip this if your front end sets |
|
// `trailingSlash: true`. |
|
$path = '/' . trim( $path, '/' ); |
|
|
|
return $path; |
|
} |
|
|
|
/** |
|
* Archive paths a post appears on: its terms and its author. |
|
* |
|
* Smart Cache purges term and user nodes when a RELATIONSHIP changes, but a |
|
* plain content edit only purges the post node itself. Without this, renaming |
|
* a post never reaches /category/x or /author/y, and those pages sit on the |
|
* old title until their ISR window lapses and someone requests them. |
|
* |
|
* Filterable because a post with many terms can push a batch toward the |
|
* endpoint's 100 path limit. |
|
*/ |
|
function revalidate_archive_paths_for_post( $post ) { |
|
if ( ! apply_filters( 'revalidate_post_archives', true, $post ) ) { |
|
return []; |
|
} |
|
|
|
$paths = []; |
|
|
|
foreach ( get_object_taxonomies( $post->post_type, 'objects' ) as $taxonomy ) { |
|
if ( empty( $taxonomy->public ) ) { |
|
continue; |
|
} |
|
|
|
$terms = get_the_terms( $post, $taxonomy->name ); |
|
|
|
if ( empty( $terms ) || is_wp_error( $terms ) ) { |
|
continue; |
|
} |
|
|
|
foreach ( $terms as $term ) { |
|
$paths[] = revalidate_path( get_term_link( $term ) ); |
|
} |
|
} |
|
|
|
if ( ! empty( $post->post_author ) ) { |
|
$paths[] = revalidate_path( get_author_posts_url( (int) $post->post_author ) ); |
|
} |
|
|
|
return array_values( array_filter( $paths ) ); |
|
} |
|
|
|
/** |
|
* Turn one Smart Cache key into the paths it affects. |
|
* |
|
* Keys come in four shapes: |
|
* - base64("post:123") / ("term:4") / ("user:7") for a single node |
|
* - "list:<type>" when a collection of that type changed |
|
* - "skipped:<type>" when the key header was truncated, no new information |
|
* - "graphql:Query" a purge-everything |
|
* |
|
* @param string $key |
|
* @return string[] |
|
*/ |
|
function revalidate_paths_for_key( $key ) { |
|
if ( ! is_string( $key ) || '' === $key ) { |
|
return []; |
|
} |
|
|
|
// Truncated-header bookkeeping, the node itself is purged separately. |
|
if ( 0 === strpos( $key, 'skipped:' ) ) { |
|
return []; |
|
} |
|
|
|
// Purge everything. Rebuild the entry points rather than trying to |
|
// enumerate the site, which would blow past the endpoint's path limit. |
|
if ( 'graphql:Query' === $key ) { |
|
return revalidate_always_paths(); |
|
} |
|
|
|
if ( 0 === strpos( $key, 'list:' ) ) { |
|
// A collection changed. The individual node that caused it is purged |
|
// under its own key, so this only needs the shared pages. |
|
return revalidate_always_paths(); |
|
} |
|
|
|
// Single node. Relay global IDs are base64("type:id"). |
|
$decoded = base64_decode( $key, true ); |
|
|
|
if ( false === $decoded || false === strpos( $decoded, ':' ) ) { |
|
return []; |
|
} |
|
|
|
list( $type, $id ) = array_pad( explode( ':', $decoded, 2 ), 2, null ); |
|
|
|
$id = absint( $id ); |
|
|
|
if ( ! $id ) { |
|
return []; |
|
} |
|
|
|
$paths = []; |
|
|
|
switch ( $type ) { |
|
case 'post': |
|
$post = get_post( $id ); |
|
|
|
// Only content the front end actually renders. Revisions and |
|
// autosaves never reach it. |
|
if ( $post && ! wp_is_post_revision( $post ) ) { |
|
$type_object = get_post_type_object( $post->post_type ); |
|
|
|
if ( $type_object && $type_object->public ) { |
|
$paths[] = revalidate_path( get_permalink( $id ) ); |
|
$paths = array_merge( $paths, revalidate_always_paths() ); |
|
$paths = array_merge( $paths, revalidate_archive_paths_for_post( $post ) ); |
|
} |
|
} |
|
break; |
|
|
|
case 'term': |
|
$paths[] = revalidate_path( get_term_link( $id ) ); |
|
break; |
|
|
|
case 'user': |
|
$paths[] = revalidate_path( get_author_posts_url( $id ) ); |
|
break; |
|
} |
|
|
|
$paths = array_values( array_filter( $paths ) ); |
|
|
|
revalidate_log( sprintf( 'key %s -> %s', $key, $paths ? implode( ', ', $paths ) : '(none)' ) ); |
|
|
|
return $paths; |
|
} |
|
|
|
/** |
|
* Where pending paths live between the edit request and the cron flush. |
|
* |
|
* An option rather than the in-request queue alone, so that several edits made |
|
* before the flush runs all ride the same rebuild. See the scheduling note in |
|
* the shutdown handler for why that matters. |
|
*/ |
|
const REVALIDATE_PENDING_OPTION = 'revalidate_pending_paths'; |
|
|
|
/** |
|
* Queue paths for this request, flushed once on shutdown. |
|
* |
|
* Smart Cache emits several purges for a single edit: the node, the lists it |
|
* belongs to, its author, its terms. Batching means one HTTP call with a |
|
* deduplicated list rather than a dozen. |
|
*/ |
|
function revalidate_queue( $paths = null ) { |
|
static $queue = []; |
|
|
|
if ( null === $paths ) { |
|
return $queue; |
|
} |
|
|
|
foreach ( (array) $paths as $path ) { |
|
if ( is_string( $path ) && '' !== $path && ! in_array( $path, $queue, true ) ) { |
|
$queue[] = $path; |
|
} |
|
} |
|
|
|
return $queue; |
|
} |
|
|
|
add_action( |
|
'graphql_purge', |
|
function ( $key ) { |
|
revalidate_queue( revalidate_paths_for_key( $key ) ); |
|
}, |
|
10, |
|
1 |
|
); |
|
|
|
/** |
|
* How long to wait before telling the front end to rebuild. |
|
* |
|
* This exists because of a race. If a CDN or proxy sits between the front end |
|
* and WordPress, its purge and this revalidation both leave WordPress on |
|
* `shutdown`, fire and forget, with no ordering between them. Revalidate too |
|
* early and the front end refetches through a proxy that has not been purged |
|
* yet, caches the stale response, and gives it a fresh lease. That is worse |
|
* than not revalidating at all: without this the page would have expired |
|
* normally, and now it will not. |
|
* |
|
* Set to 0 if the front end talks to WordPress directly. |
|
*/ |
|
function revalidate_delay_seconds() { |
|
return (int) apply_filters( 'revalidate_delay_seconds', 15 ); |
|
} |
|
|
|
const REVALIDATE_CRON_HOOK = 'revalidate_send_paths'; |
|
|
|
/** |
|
* Add paths to the pending set. Returns the merged set. |
|
*/ |
|
function revalidate_add_pending( array $paths ) { |
|
$pending = get_option( REVALIDATE_PENDING_OPTION, [] ); |
|
|
|
if ( ! is_array( $pending ) ) { |
|
$pending = []; |
|
} |
|
|
|
$merged = array_values( array_unique( array_merge( $pending, $paths ) ) ); |
|
|
|
update_option( REVALIDATE_PENDING_OPTION, $merged, false ); |
|
|
|
return $merged; |
|
} |
|
|
|
/** |
|
* Take the pending set and clear it in one step. |
|
*/ |
|
function revalidate_take_pending() { |
|
$pending = get_option( REVALIDATE_PENDING_OPTION, [] ); |
|
|
|
delete_option( REVALIDATE_PENDING_OPTION ); |
|
|
|
return is_array( $pending ) ? $pending : []; |
|
} |
|
|
|
add_action( |
|
REVALIDATE_CRON_HOOK, |
|
function () { |
|
$paths = revalidate_take_pending(); |
|
|
|
// Cron is not user facing, so this call can block long enough to read |
|
// the response and report what the front end actually did. |
|
revalidate_send( $paths, true ); |
|
}, |
|
10, |
|
0 |
|
); |
|
|
|
/** |
|
* Hand off at the end of the request. |
|
*/ |
|
add_action( |
|
'shutdown', |
|
function () { |
|
$paths = revalidate_queue(); |
|
|
|
if ( empty( $paths ) ) { |
|
return; |
|
} |
|
|
|
$delay = revalidate_delay_seconds(); |
|
|
|
if ( $delay <= 0 ) { |
|
revalidate_send( $paths ); |
|
return; |
|
} |
|
|
|
// Accumulate into the pending set, then schedule ONE flush with no |
|
// arguments. |
|
// |
|
// wp_schedule_single_event() refuses an event whose hook and args match |
|
// one already scheduled within ten minutes, keyed on |
|
// md5( serialize( $event->args ) ). Passing the paths as args would |
|
// make that key change per edit, so editing two different posts would |
|
// book two rebuilds, while editing the SAME post twice would produce an |
|
// identical key and the second edit would be silently dropped. Neither |
|
// is what we want. |
|
// |
|
// With no args the key is constant, so one pending flush coalesces |
|
// every edit made before it runs, across posts. That is correct rather |
|
// than merely cheap: revalidation refetches whatever WordPress holds at |
|
// send time, not at queue time, so a single rebuild already reflects |
|
// every edit that landed before it. |
|
revalidate_add_pending( $paths ); |
|
|
|
$scheduled = wp_schedule_single_event( time() + $delay, REVALIDATE_CRON_HOOK ); |
|
|
|
if ( false !== $scheduled ) { |
|
return; |
|
} |
|
|
|
// Core refused it. Usually that means a flush is already pending and |
|
// will carry these paths, which is the coalescing above working. |
|
// |
|
// The exception is an event stuck in the past, which happens when cron |
|
// is not draining. Core counts ALL past identical events as duplicates |
|
// when scheduling a near-future one, so a single stuck entry would |
|
// block every later revalidation, silently and indefinitely. |
|
$next = wp_next_scheduled( REVALIDATE_CRON_HOOK ); |
|
|
|
if ( $next && $next >= time() ) { |
|
revalidate_log( 'flush already pending, paths merged into it' ); |
|
return; |
|
} |
|
|
|
error_log( '[revalidate] no usable scheduled event, sending immediately' ); |
|
revalidate_send( revalidate_take_pending() ); |
|
} |
|
); |
|
|
|
/** |
|
* POST the paths to the front end. |
|
* |
|
* @param string[] $paths Paths to rebuild. |
|
* @param bool $blocking Whether to wait for and report the response. Safe |
|
* from cron, never from a request an editor is |
|
* waiting on. |
|
*/ |
|
function revalidate_send( array $paths, $blocking = false ) { |
|
if ( empty( $paths ) || ! REVALIDATE_SECRET || ! REVALIDATE_ENDPOINT ) { |
|
return; |
|
} |
|
|
|
// The endpoint accepts at most 100 paths per call. |
|
$paths = array_slice( array_values( array_unique( $paths ) ), 0, 100 ); |
|
|
|
revalidate_log( sprintf( 'sending %d paths: %s', count( $paths ), implode( ', ', $paths ) ) ); |
|
|
|
$response = wp_remote_post( |
|
REVALIDATE_ENDPOINT, |
|
[ |
|
'headers' => [ |
|
'Content-Type' => 'application/json', |
|
'x-wpgraphql-revalidate-secret' => REVALIDATE_SECRET, |
|
], |
|
'body' => wp_json_encode( [ 'paths' => $paths ] ), |
|
'timeout' => $blocking ? 15 : 5, |
|
// Do not make an editor wait on the front end to rebuild. |
|
'blocking' => (bool) $blocking, |
|
] |
|
); |
|
|
|
if ( is_wp_error( $response ) ) { |
|
error_log( '[revalidate] request failed: ' . $response->get_error_message() ); |
|
return; |
|
} |
|
|
|
if ( ! $blocking ) { |
|
return; |
|
} |
|
|
|
$code = (int) wp_remote_retrieve_response_code( $response ); |
|
$raw = wp_remote_retrieve_body( $response ); |
|
|
|
if ( 200 !== $code ) { |
|
error_log( sprintf( '[revalidate] endpoint returned %d: %s', $code, $raw ) ); |
|
return; |
|
} |
|
|
|
$body = json_decode( $raw, true ); |
|
|
|
// A path the front end could not rebuild is the failure mode this whole |
|
// snippet exists to prevent, and it is invisible unless we look. A path |
|
// that is not a route is reported as revalidated, so an empty `failed` |
|
// list is necessary but not sufficient: check the page too. |
|
if ( ! empty( $body['failed'] ) && is_array( $body['failed'] ) ) { |
|
foreach ( $body['failed'] as $failure ) { |
|
error_log( |
|
sprintf( |
|
'[revalidate] path failed: %s (%s)', |
|
isset( $failure['path'] ) ? $failure['path'] : '?', |
|
isset( $failure['error'] ) ? $failure['error'] : '?' |
|
) |
|
); |
|
} |
|
} |
|
|
|
revalidate_log( |
|
sprintf( |
|
'endpoint rebuilt %d, failed %d', |
|
isset( $body['revalidated'] ) ? count( (array) $body['revalidated'] ) : 0, |
|
isset( $body['failed'] ) ? count( (array) $body['failed'] ) : 0 |
|
) |
|
); |
|
} |