held_profile_id === $profile_id && $this->held_op === $op ) { return true; } $key = self::keyFor( $profile_id ); $token = bin2hex( random_bytes( 8 ) ); $payload = array( 'op' => $op, 'ts' => time(), 'token' => $token, 'expires_at' => time() + self::TTL_SECONDS, ); if ( ! \add_option( $key, $payload, '', 'no' ) ) { $existing = \get_option( $key ); $expired = is_array( $existing ) && isset( $existing['expires_at'] ) && (int) $existing['expires_at'] < time(); if ( ! $expired ) { return false; } \delete_option( $key ); if ( ! \add_option( $key, $payload, '', 'no' ) ) { return false; } $verify = \get_option( $key ); if ( ! is_array( $verify ) || ( $verify['token'] ?? null ) !== $token ) { return false; } } $this->held_profile_id = $profile_id; $this->held_op = $op; $this->held_token = $token; return true; } /** * Release the lock if this instance currently holds it. * * Safe to call when the instance does not hold a lock (no-op). Does NOT * release a lock held by a DIFFERENT instance — protects against a * later handler accidentally clearing an earlier handler's mutex. * * @return void */ public function release(): void { if ( $this->held_profile_id === null ) { return; } $key = self::keyFor( $this->held_profile_id ); $current = \get_option( $key ); if ( is_array( $current ) && ( $current['token'] ?? null ) === $this->held_token ) { \delete_option( $key ); } $this->held_profile_id = null; $this->held_op = null; $this->held_token = null; } /** * Auto-release on instance destruction so a thrown exception inside a * REST handler can't leave the lock held until the transient expires. */ public function __destruct() { $this->release(); } /** * Is any operation currently locked on the given profile? * * @param int $profile_id Target profile. * @return bool */ public static function isHeld( int $profile_id ): bool { $value = \get_option( self::keyFor( $profile_id ) ); if ( ! is_array( $value ) || ! isset( $value['op'] ) ) { return false; } if ( isset( $value['expires_at'] ) && (int) $value['expires_at'] < time() ) { return false; } return true; } /** * Which operation is currently locked on the given profile, if any. * * @param int $profile_id Target profile. * @return string|null Operation label or null when not held. */ public static function currentOp( int $profile_id ): ?string { $value = \get_option( self::keyFor( $profile_id ) ); if ( ! is_array( $value ) || ! isset( $value['op'] ) ) { return null; } if ( isset( $value['expires_at'] ) && (int) $value['expires_at'] < time() ) { return null; } return (string) $value['op']; } /** * Compose the transient key for a given profile. * * @param int $profile_id Target profile. * @return string Transient key. */ private static function keyFor( int $profile_id ): string { return 'aipt_storeindex_op_lock_' . $profile_id; } }