← Back
Editing: class-activity-signal.php
<?php namespace WPaaS; /** * Reports when this site was last used, for the hosting control plane's * hibernation scan. * * The control plane stops workloads that nobody is using any more. On Airo apps * it learns "last used" by polling the app's agent for a `last_message_at`, and * an app with no such reading is never a candidate. Managed WordPress has no * agent, so its sites read as permanently unknown: safe, and useless. * * This class closes that gap from inside WordPress, in two halves that share * nothing but one option row: * * write — real traffic advances a coarse timestamp (record_admin_activity(), * record_request_activity()) * read — `GET /airo/health` reports it (maybe_serve_health()) * * The response deliberately carries the same shape and field names as the Airo * agent's `/health`, so the control plane reads it with the code it already has * and nothing on the wire names WordPress: * * {"status":"healthy","timestamp":"…","version":"…","last_message_at":"…"} * * `version` doubles as the capability marker. A site that has never heard of * this class 404s the route, and a site whose gate is off answers nothing at all * — either way the control plane must read "I cannot tell you", not "idle". * That asymmetry is the whole safety property: a missing signal has to fail * towards leaving the site running. * * Everything here is gated on `GD_ACTIVITY_SIGNAL`, delivered in gd-config.php. * Undefined — which is every site outside Managed WordPress v1 — means the class * costs one constant check per request and nothing else: no option read, no * write, no route, no hooks. */ final class Activity_Signal { /** * Where the recorded timestamps live. * * A non-autoloaded option rather than a transient. A transient is evictable, * and on this platform the object cache is flushed routinely — losing the * value would read as "never used", which is the one wrong answer that ends * with a site being stopped while someone is using it. An option row survives * a flush; the object cache still absorbs the read. * * @var string */ const OPTION = 'gd_activity_signal'; /** * Payload schema version, so a later shape change can be recognised rather * than misread. An unrecognised version is treated as no data. * * @var int */ const SCHEMA = 1; /** * Minimum gap between writes of the same class, in seconds. * * The control plane's thresholds are in days, so six hours of granularity * costs nothing and bounds writes to four per class per day no matter how * busy the site is. * * @var int */ const THROTTLE = 21600; /** * The route this class answers. * * The same path the Airo publish and preview variants already serve, and * answered here before WordPress parses the request — see * maybe_serve_health() for why that matters on this platform. * * @var string */ const ROUTE = '/airo/health'; /** * The variant this site serves, as read at mu-plugin load. * * @var string|null */ private static $variant; /** * Class constructor. */ public function __construct() { if ( ! self::enabled() ) { return; } // Read the variant before anything else, while only mu-plugins have loaded: // see variant() for what an active plugin could otherwise do to it. $variant = self::variant(); // Answer the probe here, at mu-plugin load, and exit. Registering the // writers first would let the probe record itself as traffic and hold the // site up by observing it. $this->maybe_serve_health(); add_action( 'admin_init', [ $this, 'record_admin_activity' ] ); // Nothing reads a front-end timestamp recorded on staging, so it is not // recorded: the staging fold ignores it, and after a database copy in either // direction the row is discarded on its variant stamp. if ( 'staging' !== $variant ) { add_action( 'init', [ $this, 'record_request_activity' ] ); } } /** * Whether this site has been told to report activity. * * The constant is the only input, and only the control plane renders it. * Absence is the back-compat signal — a site that has never been delivered the * constant behaves exactly as it does today. Not filterable: the platform reads * this signal to decide a site's fate, so a site must not be able to fake or * suppress its own. * * @return bool */ public static function enabled() { return defined( 'GD_ACTIVITY_SIGNAL' ) ? (bool) GD_ACTIVITY_SIGNAL : false; } /** * Record authenticated activity in the WordPress admin. * * This is the class that decides a staging site's fate, and the one that best * matches "somebody is working on this site": admin navigation advances it, * while a site nobody has opened in weeks does not, however much crawler * traffic its front end sees. * * Background work is excluded on purpose. WP-Cron keeps firing on an * abandoned site, and admin-ajax carries the heartbeat of a tab left open — * counting either would make every site look permanently in use. * * @action admin_init * * @return void */ public function record_admin_activity() { if ( ! is_user_logged_in() || wp_doing_ajax() ) { return; } $this->record( 'admin' ); } /** * Record a front-end request. * * A lower bound, not a count: most visitor traffic is served by the page * cache and never reaches PHP. That is fine for the question being asked — * anything that gets here is evidence the site is still being served, and its * absence is not being read as proof of the opposite. The admin class above is * what carries a quiet-but-tended site. * * Live sites only. A staging site fielding front-end requests says nothing about * whether anyone still wants it, so the staging fold ignores this class — which * makes recording it there a write with no reader, competing with the one * timestamp that decides a staging copy's fate. * * @action init * * @return void */ public function record_request_activity() { if ( 'staging' === self::variant() ) { return; } if ( is_admin() || wp_doing_ajax() ) { return; } $this->record( 'request' ); } /** * Advance one class of the recorded timestamp, at most once per THROTTLE. * * @param string $class 'admin' or 'request'. * * @return void */ private function record( $class ) { if ( self::is_background() ) { return; } $now = time(); $payload = self::read(); if ( isset( $payload[ $class ] ) && ( $now - (int) $payload[ $class ] ) < self::THROTTLE ) { return; } $payload[ $class ] = $now; $payload['v'] = self::SCHEMA; $payload['variant'] = self::variant(); update_option( self::OPTION, $payload, false ); } /** * Answer `GET /airo/health` and exit, or return and let WordPress carry on. * * Answered from mu-plugin load rather than through the REST API or a rewrite, * because on this platform neither is dependable: `/wp-json` rewrites are * known-dead on Managed WordPress, and a rewrite would need a gateway rule * this repository does not own. By the time mu-plugins load, `$wpdb` and the * object cache are up but `WP::parse_request()` has not run — so this path can * read an option and exit before anything can 404 it. * * The response must never be cached. A cached body pins the timestamp, and a * pinned timestamp is either a site that can never be stopped or one that is * stopped while in use. * * @return void */ private function maybe_serve_health() { if ( self::is_background() || ! self::is_health_request() ) { return; } header( 'Content-Type: application/json; charset=utf-8' ); header( 'Cache-Control: no-store, no-cache, must-revalidate, max-age=0' ); header( 'Pragma: no-cache' ); header( 'X-Robots-Tag: noindex, nofollow' ); echo wp_json_encode( $this->health_payload() ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped exit; } /** * The body of the health response. * * Split from the emission above so that what the control plane reads can be * asserted without a process that exits. * * `last_message_at` is null rather than absent when nothing qualifies, which is * what the agent reports before its first message too. `version` is present * whenever this method runs at all — that is the capability marker, so it must * never become conditional. * * @return array */ public function health_payload() { $last = $this->fold( self::read() ); return [ 'status' => 'healthy', 'timestamp' => self::format( time() ), 'version' => (string) Plugin::version(), 'last_message_at' => $last ? self::format( $last ) : null, ]; } /** * Whether the current request is the health probe. * * Path-exact, with or without a trailing slash. A query string is ignored and * the method is not checked: this is a read with no side effects, and being * strict about either would only turn a working probe into a 404. * * @return bool */ public static function is_health_request() { $uri = isset( $_SERVER['REQUEST_URI'] ) ? (string) $_SERVER['REQUEST_URI'] : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput if ( '' === $uri ) { return false; } $path = (string) parse_url( $uri, PHP_URL_PATH ); // phpcs:ignore WordPress.WP.AlternativeFunctions return ( self::ROUTE === untrailingslashit( $path ) ); } /** * The single timestamp reported for this site, or 0 for none. * * Which classes count is a property of the variant, not of the reader: * * staging — admin only. Front-end traffic to a staging site is noise, and * counting it would keep a forgotten copy alive indefinitely. * publish — the later of admin and front-end. A live site with visitors is * in use whether or not anyone has logged in recently. * * @param array $payload * * @return int */ private function fold( array $payload ) { $admin = isset( $payload['admin'] ) ? (int) $payload['admin'] : 0; if ( 'staging' === self::variant() ) { return $admin; } $request = isset( $payload['request'] ) ? (int) $payload['request'] : 0; return max( $admin, $request ); } /** * The stored payload, or an empty array when there is nothing usable. * * A payload stamped with another variant is discarded rather than trusted. * Staging is populated by copying the live site's database wholesale, which * carries the live site's option row across with it — read as-is, a staging * site would inherit activity that happened somewhere else, and inherit it * again on every sync. Discarding it self-heals: the next qualifying request * rewrites the row with this site's own variant. * * @return array */ private static function read() { $payload = get_option( self::OPTION ); if ( ! is_array( $payload ) ) { return []; } if ( ! isset( $payload['v'] ) || self::SCHEMA !== (int) $payload['v'] ) { return []; } $variant = isset( $payload['variant'] ) ? (string) $payload['variant'] : ''; if ( $variant !== self::variant() ) { return []; } return $payload; } /** * Which variant of the app this site is. * * Read from `GD_STAGING_SITE` rather than through Plugin::is_staging_site(), * which passes the value through the `wpaas_is_staging_site` filter. Which * variant is being served is a fact the control plane renders into * gd-config.php, and here it decides both what a stored payload is allowed to * mean and which classes fold into the reported timestamp — neither belongs on * a filter a plugin can move. The constant is only rendered on a staging site, * so its absence is publish. * * Resolved once, from the constructor, and remembered. The health probe answers * during mu-plugin load while the writers run at `init`, by which time active * plugins have loaded — so a plugin defining this otherwise absent constant * would have the writers stamp `staging` on rows the probe then discards, and a * live site in daily use would report no activity at all. * * @return string */ private static function variant() { if ( null === self::$variant ) { self::$variant = ( defined( 'GD_STAGING_SITE' ) && GD_STAGING_SITE ) ? 'staging' : 'publish'; } return self::$variant; } /** * Whether this process is background work rather than a served request. * * Checked in both halves. Unlike the auto-prepended config chain, this plugin * also loads under WP-CLI — including the platform's own maintenance commands, * which run on sites nobody has touched in months. Recording those would report * every site as busy, and it is this guard, not the caller, that has to stop it: * the class is constructed before Plugin's own CLI branch. * * `PHP_SAPI` is deliberately not consulted. WP-CLI defines `WP_CLI` before * WordPress loads, so the check above already covers every command the platform * runs, and a bare `php` bootstrap that slipped through would only ever record * activity that is not there — which leaves a site running. The reverse mistake * stops a site somebody is using. * * @return bool */ private static function is_background() { return ( Plugin::is_wp_cli() || Plugin::is_wp_cron() || wp_doing_cron() ); } /** * Format a Unix timestamp the way the Airo agent formats its own. * * UTC, milliseconds, `Z` suffix. The recorded values are whole seconds, so the * milliseconds are always zero; they are emitted anyway so that one parser * reads both sources. * * @param int $timestamp * * @return string */ private static function format( $timestamp ) { return gmdate( 'Y-m-d\TH:i:s', (int) $timestamp ) . '.000Z'; } }
Save File
Cancel