*/ private static $open = array(); /** * Test seam: fn(): float, unix time with sub-second precision. * * @var callable|null */ private static $clock = null; /** * The scope for a provider and the key it is called with. Only a short * hash of the key is kept, never the key. * * @param string $provider AIPT provider id. * @param string $api_key The key the client uses. * @return string */ public static function scope( string $provider, string $api_key ): string { return $provider . ':' . substr( hash( 'sha256', $api_key ), 0, 16 ); } /** * The failure that keeps this scope and model blocked, or null when a * call may go out. * * @param string $scope See scope(). * @param string $model Model id the call uses ('' for the client default). * @return ProviderCallException|null */ public static function openFailure( string $scope, string $model = '' ): ?ProviderCallException { foreach ( array( $scope, self::modelKey( $scope, $model ) ) as $key ) { if ( ! isset( self::$open[ $key ] ) ) { continue; } $until = self::$open[ $key ]['until']; if ( null !== $until && self::now() >= $until ) { unset( self::$open[ $key ] ); continue; } return self::$open[ $key ]['failure']; } return null; } /** * Remember a failure when it is run-wide; any other failure is ignored. * * @param string $scope See scope(). * @param string $model Model id the call used. * @param ProviderCallException $failure The failure. * @return void */ public static function record( string $scope, string $model, ProviderCallException $failure ): void { $reason = $failure->reason(); if ( ! $failure->isRunWide() ) { return; } $key = in_array( $reason, self::MODEL_REASONS, true ) ? self::modelKey( $scope, $model ) : $scope; $until = in_array( $reason, self::TRANSIENT_REASONS, true ) ? self::now() + self::coolDownSeconds( $failure->retryAfterSeconds() ) : null; self::$open[ $key ] = array( 'failure' => $failure, 'until' => $until, ); } /** * Close every circuit (tests, or a process that starts over). * * @return void */ public static function reset(): void { self::$open = array(); } /** * Test seam for the clock. * * @param callable|null $clock fn(): float, or null for the real clock. * @return void */ public static function useClock( ?callable $clock ): void { self::$clock = $clock; } private static function coolDownSeconds( ?int $retry_after ): int { $seconds = ( null !== $retry_after && $retry_after > 0 ) ? $retry_after : self::TRANSIENT_DEFAULT_SECONDS; return max( self::TRANSIENT_MIN_SECONDS, min( self::TRANSIENT_MAX_SECONDS, $seconds ) ); } private static function modelKey( string $scope, string $model ): string { return $scope . '|' . $model; } private static function now(): float { return null !== self::$clock ? (float) call_user_func( self::$clock ) : microtime( true ); } }