*/ private static $owned = array(); /** * 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). * @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 ) { if ( '' === $claim_key ) { return null; } $now = time(); $claimed = self::tryInsert( $claim_key, $now ); if ( true === $claimed ) { self::$owned[ $claim_key ] = $now; return null; } if ( null === $claimed ) { return null; } return self::resolveExisting( $claim_key, $now ); } /** * 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}). * * @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(); $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 ) ); } /** * 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 ] ); global $wpdb; $table = self::table(); $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE claim_key = %s AND status = 'pending' AND created_at = %d", $claim_key, $claimed_at ) ); } /** * @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(); $result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$table} (claim_key, status, payload, created_at) VALUES (%s, 'pending', NULL, %d)", $claim_key, $now ) ); 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. * @return array|WP_Error|null */ private static function resolveExisting( string $claim_key, int $now ) { $row = self::readRow( $claim_key ); if ( null === $row ) { $retried = self::tryInsert( $claim_key, $now ); if ( true === $retried ) { self::$owned[ $claim_key ] = $now; } return false === $retried ? self::conflict() : null; } if ( 'done' === $row['status'] ) { if ( $now - $row['created_at'] < 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 ); } if ( $now - $row['created_at'] < self::PENDING_TTL_SECONDS ) { return self::conflict(); } return self::reclaim( $claim_key, 'pending', $row['created_at'], $now ); } /** * 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. * @return WP_Error|null */ private static function reclaim( string $claim_key, string $expected_status, int $expected_age, int $now ) { global $wpdb; $table = self::table(); $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 ) ); if ( 1 !== (int) $updated ) { return self::conflict(); } self::$owned[ $claim_key ] = $now; return null; } /** * @return WP_Error */ private static function conflict(): WP_Error { 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' ), array( 'status' => 409 ) ); } /** * @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(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT status, payload, created_at FROM {$table} WHERE claim_key = %s", $claim_key ) ); if ( null === $row ) { return null; } return array( 'status' => (string) $row->status, 'payload' => $row->payload, 'created_at' => (int) $row->created_at, ); } }