*/ private static $owned = array(); /** * Whether {@see releaseOwned()} is already registered for shutdown. * * @var bool */ private static $shutdown_registered = false; /** * Fully-qualified table name. * * @return string */ private static function table(): string { global $wpdb; return $wpdb->prefix . 'aipt_request_claims'; } /** * Attempt to claim $claim_key for this request. * * @param string $claim_key Caller-built, already-namespaced idempotency key; '' always bypasses (no dedup requested). * @param array $windows Seconds this call uses instead of the defaults: `cache` (how long a finished claim is * replayed, default 30), `pending` (how long a claim may sit pending before it counts as abandoned, default 120) and, only * when given, `alive` (the idle seconds up to which a client may treat the owner as alive, echoed in the 409). * @return array|WP_Error|null `array` = a prior identical request already * finished — serve this cached payload as-is. `WP_Error` (409) = a * prior identical request is still running — do not call the * provider again. `null` = this call now owns the claim: do the * work, then call {@see complete()} on success or {@see release()} * on any bail-out (a denial, a thrown error) so a legitimate retry * of the same id is never stuck behind this attempt. */ public static function claim( string $claim_key, array $windows = array() ) { if ( '' === $claim_key ) { return null; } $now = time(); $claimed = self::tryInsert( $claim_key, $now ); if ( true === $claimed ) { self::own( $claim_key, $now ); return null; } if ( null === $claimed ) { return null; } return self::resolveExisting( $claim_key, $now, $windows ); } /** * Read what a claim holds without claiming it, reclaiming it or changing * it: a replay-only request must never start paid work. * * @param string $claim_key Claim key; '' reads nothing. * @param array $windows The windows {@see claim()} takes. * @return array|WP_Error|null `array` = the cached payload of a finished * claim still inside its cache window. `WP_Error` (409) = the claim is * pending and not yet abandoned. `null` = nothing to serve: no row, a * stale one, or an abandoned pending one. */ public static function peek( string $claim_key, array $windows = array() ) { if ( '' === $claim_key ) { return null; } $row = self::readRow( $claim_key ); if ( null === $row ) { return null; } $idle = max( 0, time() - $row['created_at'] ); if ( 'done' === $row['status'] ) { $payload = json_decode( (string) $row['payload'], true ); return $idle < self::window( $windows, 'cache', self::CACHE_TTL_SECONDS ) && is_array( $payload ) ? $payload : null; } return $idle < self::window( $windows, 'pending', self::PENDING_TTL_SECONDS ) ? self::conflict( $idle, $windows ) : null; } /** * Heartbeat: tell other requests this one is still working on every claim * it owns, by moving the claim's `created_at` (the idle clock, and the * fence {@see complete()} and {@see release()} check) to now. * * Called around each provider call. It does nothing when this request * owns no claim, and writes at most once per {@see HEARTBEAT_SECONDS} for * a claim, so a run of fast calls costs no queries. A claim that no * longer matches (reclaimed after it was abandoned, or released) is * forgotten, so this request cannot complete it over a newer owner. * * @return void */ public static function touchOwned(): void { if ( array() === self::$owned ) { return; } global $wpdb; $table = self::table(); $now = time(); foreach ( self::$owned as $claim_key => $claimed_at ) { if ( $now - $claimed_at < self::HEARTBEAT_SECONDS ) { continue; } // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared $touched = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET created_at = %d WHERE claim_key = %s AND status = 'pending' AND created_at = %d", $now, $claim_key, $claimed_at ) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( 1 === (int) $touched ) { self::$owned[ $claim_key ] = $now; } elseif ( false !== $touched ) { unset( self::$owned[ $claim_key ] ); } } } /** * Release every claim this request still owns. Registered for shutdown on * the first claim, so a request that dies on a fatal error after claiming * does not leave a pending claim that blocks a person's retry until it * goes stale. Nothing is left to release after a normal run, which * completes or releases each claim. * * @internal Shutdown callback. * @return void */ public static function releaseOwned(): void { foreach ( array_keys( self::$owned ) as $claim_key ) { try { self::release( $claim_key ); } catch ( \Throwable $e ) { Logger::error( 'generation', 'Request claim could not be released at shutdown', array( 'error' => $e->getMessage() ) ); } } } /** * Record $claim_key's successful result so a repeat within * {@see CACHE_TTL_SECONDS} is served from cache instead of calling the * provider again. * * A no-op unless this request still owns the claim (see {@see $owned}). When * the result cannot be stored (a payload over `max_allowed_packet`, a lost * connection) the claim is released instead of left pending, so a retry is * not blocked behind a result that was never kept. * * @param string $claim_key Claim key this request owns (from a `null` {@see claim()} result). * @param array $payload Success envelope to cache. * @return void */ public static function complete( string $claim_key, array $payload ): void { if ( '' === $claim_key || ! isset( self::$owned[ $claim_key ] ) ) { return; } $claimed_at = self::$owned[ $claim_key ]; unset( self::$owned[ $claim_key ] ); global $wpdb; $table = self::table(); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared $stored = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET status = 'done', payload = %s, created_at = %d WHERE claim_key = %s AND status = 'pending' AND created_at = %d", wp_json_encode( $payload ), time(), $claim_key, $claimed_at ) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( false === $stored ) { Logger::error( 'generation', 'Request claim result could not be stored', array( 'error' => (string) $wpdb->last_error ) ); self::delete( $claim_key, $claimed_at ); } } /** * Release $claim_key without caching anything, so the very next request * sharing this id — not just one after {@see PENDING_TTL_SECONDS} — * may claim it fresh. Called whenever an owned claim does not end in a * cacheable success: the rate limit denied the call, or the work itself * failed. A no-op unless this request still owns the claim (see * {@see $owned}). * * @param string $claim_key Claim key this request owns. * @return void */ public static function release( string $claim_key ): void { if ( '' === $claim_key || ! isset( self::$owned[ $claim_key ] ) ) { return; } $claimed_at = self::$owned[ $claim_key ]; unset( self::$owned[ $claim_key ] ); self::delete( $claim_key, $claimed_at ); } /** * Delete the caller's own pending row (the fence: status and `created_at` * must still be the owner's). * * @param string $claim_key Claim key. * @param int $claimed_at The owner's `created_at`. * @return void */ private static function delete( string $claim_key, int $claimed_at ): void { global $wpdb; $table = self::table(); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE claim_key = %s AND status = 'pending' AND created_at = %d", $claim_key, $claimed_at ) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared } /** * Record that this request owns $claim_key, and arrange for it to be * released if the request dies before it completes or releases it. * * @param string $claim_key Claim key. * @param int $claimed_at `created_at` of the row this request now owns. * @return void */ private static function own( string $claim_key, int $claimed_at ): void { self::$owned[ $claim_key ] = $claimed_at; if ( ! self::$shutdown_registered ) { self::$shutdown_registered = true; register_shutdown_function( array( self::class, 'releaseOwned' ) ); } } /** * @param array $windows Per-call windows. * @param string $name Window name. * @param int $fallback Default seconds. * @return int */ private static function window( array $windows, string $name, int $fallback ): int { return isset( $windows[ $name ] ) ? (int) $windows[ $name ] : $fallback; } /** * @param string $claim_key Claim key. * @param int $now Current Unix timestamp. * @return bool|null `true` claimed, `false` a row already exists, `null` the write itself failed. */ private static function tryInsert( string $claim_key, int $now ): ?bool { global $wpdb; $table = self::table(); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared $result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$table} (claim_key, status, payload, created_at) VALUES (%s, 'pending', NULL, %d)", $claim_key, $now ) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( false === $result ) { return null; } return 1 === (int) $result; } /** * A claim row for $claim_key already exists: decide what the loser of * {@see tryInsert()} should do about it. * * @param string $claim_key Claim key. * @param int $now Current Unix timestamp. * @param array $windows Per-call windows. * @return array|WP_Error|null */ private static function resolveExisting( string $claim_key, int $now, array $windows ) { $row = self::readRow( $claim_key ); if ( null === $row ) { $retried = self::tryInsert( $claim_key, $now ); if ( true === $retried ) { self::own( $claim_key, $now ); } return false === $retried ? self::conflict( 0, $windows ) : null; } if ( 'done' === $row['status'] ) { if ( $now - $row['created_at'] < self::window( $windows, 'cache', self::CACHE_TTL_SECONDS ) ) { $payload = json_decode( (string) $row['payload'], true ); return is_array( $payload ) ? $payload : null; } return self::reclaim( $claim_key, 'done', $row['created_at'], $now, $windows ); } $idle = max( 0, $now - $row['created_at'] ); if ( $idle < self::window( $windows, 'pending', self::PENDING_TTL_SECONDS ) ) { return self::conflict( $idle, $windows ); } return self::reclaim( $claim_key, 'pending', $row['created_at'], $now, $windows ); } /** * Take over a claim that is either a stale cached result or an * abandoned in-flight attempt, guarded by an optimistic check * (`status`+`created_at` must still match what {@see resolveExisting()} * just read) so a second request racing the same reclaim cannot both * believe they won it. * * @param string $claim_key Claim key. * @param string $expected_status Status {@see resolveExisting()} read. * @param int $expected_age `created_at` {@see resolveExisting()} read. * @param int $now Current Unix timestamp. * @param array $windows Per-call windows, for the 409 a lost race answers. * @return WP_Error|null */ private static function reclaim( string $claim_key, string $expected_status, int $expected_age, int $now, array $windows ) { global $wpdb; $table = self::table(); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared $updated = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET status = 'pending', payload = NULL, created_at = %d WHERE claim_key = %s AND status = %s AND created_at = %d", $now, $claim_key, $expected_status, $expected_age ) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( 1 !== (int) $updated ) { return self::conflict( 0, $windows ); } self::own( $claim_key, $now ); return null; } /** * The 409 for a claim another request owns. * * `retry_after` tells a poller when to ask again (never more than * {@see MAX_RETRY_AFTER_SECONDS}, and no later than the moment the claim * may be reclaimed); `idle_seconds` is how long the owner has been silent, * so the poller can tell a live owner from a dead one. * * @param int $idle Seconds since the owner last touched the claim. * @param array $windows Per-call windows. * @return WP_Error */ private static function conflict( int $idle, array $windows ): WP_Error { $until_reclaimable = self::window( $windows, 'pending', self::PENDING_TTL_SECONDS ) - $idle; $data = array( 'status' => 409, 'retry_after' => max( 1, min( self::MAX_RETRY_AFTER_SECONDS, $until_reclaimable ) ), 'idle_seconds' => $idle, ); if ( isset( $windows['alive'] ) ) { $data['alive_seconds'] = (int) $windows['alive']; } return new WP_Error( 'aipt_blueprint_request_in_progress', __( 'An identical request is already being generated. Please wait a moment and try again.', 'ai-product-tools' ), $data ); } /** * @param string $claim_key Claim key. * @return array{status:string,payload:mixed,created_at:int}|null */ private static function readRow( string $claim_key ): ?array { global $wpdb; $table = self::table(); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared $row = $wpdb->get_row( $wpdb->prepare( "SELECT status, payload, created_at FROM {$table} WHERE claim_key = %s", $claim_key ) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( null === $row ) { return null; } return array( 'status' => (string) $row->status, 'payload' => $row->payload, 'created_at' => (int) $row->created_at, ); } }