state( $provider ); return $state['open_until'] > time(); } /** * Time at which the circuit breaker closes again. * * @param string $provider Provider name. * @return int Timestamp, or 0 while the breaker is closed. */ public function open_until( $provider ) { $state = $this->state( $provider ); return max( 0, $state['open_until'] ); } /** * Records a success and closes the circuit breaker. * * @param string $provider Provider name. * @return void */ public function record_success( $provider ) { delete_option( self::OPTION_PREFIX . $this->slug( $provider ) ); } /** * Records a failure and opens the circuit breaker when the threshold is exceeded. * * @param string $provider Provider name. * @param int $threshold Number of consecutive failures that opens the breaker. * @param int $cooldown Time the breaker stays open, in seconds. * @return bool True if the circuit breaker just opened. */ public function record_failure( $provider, $threshold = 5, $cooldown = 120 ) { $key = self::OPTION_PREFIX . $this->slug( $provider ); $state = $this->state( $provider ); ++$state['failures']; $state['last_error_at'] = time(); if ( $state['failures'] >= max( 1, (int) $threshold ) ) { $state['open_until'] = time() + max( 30, (int) $cooldown ); $state['failures'] = 0; } // autoload = no so it does not slow down every request. update_option( $key, $state, false ); return $state['open_until'] > time(); } /** * Reads the current state. * * @param string $provider Provider name. * @return array */ public function state( $provider ) { $default = array( 'failures' => 0, 'open_until' => 0, 'last_error_at' => 0, ); $stored = get_option( self::OPTION_PREFIX . $this->slug( $provider ), array() ); if ( ! is_array( $stored ) ) { return $default; } return wp_parse_args( $stored, $default ); } /** * Closes every circuit breaker; used when an administrator clicks restore. * * @return void */ public function reset_all() { foreach ( array( 'openai', 'gemini', 'embedding', 'vector' ) as $provider ) { delete_option( self::OPTION_PREFIX . $this->slug( $provider ) ); } } /** * Summarizes the state for display in the admin. * * @return array */ public function summary() { $summary = array(); foreach ( array( 'openai', 'gemini', 'embedding', 'vector' ) as $provider ) { $state = $this->state( $provider ); $summary[ $provider ] = array( 'open' => $state['open_until'] > time(), 'open_until' => $state['open_until'], 'failures' => $state['failures'], 'seconds_left' => max( 0, $state['open_until'] - time() ), ); } return $summary; } /** * Normalizes a name into a safe slug. * * @param string $provider Provider name. * @return string */ protected function slug( $provider ) { return substr( preg_replace( '/[^a-z0-9_]/', '', strtolower( (string) $provider ) ), 0, 40 ); } }