cf-removal: delete Cloudflare Workers AI provider files + tests
Drops the four CF provider classes and their two test files. The OpenRouter AI Gateway path is unaffected — it reads prautoblogger_ai_gateway_base_url via class-open-router-config.php directly, with no dependency on the CF support class. Leaves class-cost-tracker.php line 165 'cloudflare-workers-ai' label intact for historical log integrity. Part of v0.10.0 (removing CF Workers AI as image provider). See convo/prautoblogger/threads/2026-04-cloudflare-workers-ai-removal/.
This commit is contained in:
@@ -1,78 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Pricing + model-id resolution helpers for the Cloudflare image provider.
|
||||
*
|
||||
* Kept separate from the provider so the provider stays under the 300-line
|
||||
* cap and so cost estimation can be unit-tested without spinning up HTTP
|
||||
* mocks. Mirrors the `class-open-router-pricing.php` split.
|
||||
*
|
||||
* Triggered by: PRAutoBlogger_Cloudflare_Image_Provider (both generate_image()
|
||||
* and estimate_cost() delegate here).
|
||||
* Dependencies: None — pure calculation + option reads.
|
||||
*
|
||||
* @see class-cloudflare-image-provider.php — Caller.
|
||||
* @see class-open-router-pricing.php — Sibling pattern for LLM pricing.
|
||||
*/
|
||||
class PRAutoBlogger_Cloudflare_Image_Pricing {
|
||||
|
||||
/**
|
||||
* Cloudflare Workers AI FLUX pricing (USD per megapixel), April 2026.
|
||||
* Single source of truth — update here if Cloudflare reprices.
|
||||
*/
|
||||
private const COST_PER_MP_SCHNELL_USD = 0.0011;
|
||||
|
||||
/**
|
||||
* Short-alias → fully-qualified Workers AI model id.
|
||||
*
|
||||
* FLUX.1 [dev] was removed from Cloudflare Workers AI in April 2026
|
||||
* (returns HTTP 400 "No route for that URI"). Only schnell remains.
|
||||
* Any saved setting referencing flux-1-dev falls through to schnell
|
||||
* via the null-coalesce in resolve_model().
|
||||
*
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private const MODEL_ALIAS_MAP = [
|
||||
'flux-1-schnell' => '@cf/black-forest-labs/flux-1-schnell',
|
||||
];
|
||||
|
||||
/**
|
||||
* Normalize a caller's model hint to a fully-qualified Workers AI id.
|
||||
*
|
||||
* Accepts short aliases (`flux-1-schnell`), fully-qualified names
|
||||
* (`@cf/black-forest-labs/...`), or empty. Empty input falls back to
|
||||
* the site option, then to the hardcoded default.
|
||||
*
|
||||
* @param string $hint Caller-supplied model identifier (may be empty).
|
||||
* @return string Fully-qualified Workers AI model id suitable for the URL path.
|
||||
*/
|
||||
public function resolve_model( string $hint ): string {
|
||||
$hint = trim( $hint );
|
||||
if ( '' === $hint ) {
|
||||
$hint = (string) get_option( 'prautoblogger_image_model', PRAUTOBLOGGER_DEFAULT_IMAGE_MODEL );
|
||||
}
|
||||
if ( 0 === strpos( $hint, '@cf/' ) ) {
|
||||
return $hint;
|
||||
}
|
||||
return self::MODEL_ALIAS_MAP[ $hint ] ?? self::MODEL_ALIAS_MAP['flux-1-schnell'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate USD cost for a single image at the given dimensions.
|
||||
*
|
||||
* FLUX is priced per megapixel of output. We clamp the MP floor at
|
||||
* 0.01 so a tiny thumbnail doesn't round to zero and bypass the
|
||||
* budget check.
|
||||
*
|
||||
* @param int $width Width in pixels.
|
||||
* @param int $height Height in pixels.
|
||||
* @param string $model Fully-qualified Workers AI model id (call resolve_model first).
|
||||
* @return float USD cost rounded to 6 decimals.
|
||||
*/
|
||||
public function estimate_cost( int $width, int $height, string $model ): float {
|
||||
$mp = max( 0.01, ( $width * $height ) / 1_000_000 );
|
||||
$rate = self::COST_PER_MP_SCHNELL_USD;
|
||||
return round( $mp * $rate, 6 );
|
||||
}
|
||||
}
|
||||
@@ -1,296 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Cloudflare Workers AI image provider — FLUX.1 family.
|
||||
*
|
||||
* Calls `https://api.cloudflare.com/client/v4/accounts/{id}/ai/run/{model}`
|
||||
* directly. We bypass the Cloudflare AI Gateway for v1 because the gateway
|
||||
* route to Workers AI currently 403s (see decision D-001); the OpenRouter
|
||||
* gateway path is unaffected.
|
||||
*
|
||||
* Triggered by: PRAutoBlogger_Image_Pipeline (commit 1b) during the content
|
||||
* generation run, after editorial review, before publish. Also
|
||||
* triggered by the admin "Test Connection" action.
|
||||
* Dependencies: PRAutoBlogger_Encryption (token decryption), PRAutoBlogger_Logger
|
||||
* (WARN/ERROR lines), PRAutoBlogger_Cloudflare_Image_Pricing
|
||||
* (model resolution + cost estimation).
|
||||
*
|
||||
* @see interface-image-provider.php Interface this class implements.
|
||||
* @see class-cloudflare-image-pricing.php Cost + model id helpers.
|
||||
* @see class-cloudflare-image-support.php Token, account, URL, and log helpers.
|
||||
* @see class-cloudflare-image-validator.php Credential check helper.
|
||||
* @see class-open-router-provider.php Sibling provider; same retry pattern.
|
||||
* @see ARCHITECTURE.md External API Integrations, key decision #16.
|
||||
*/
|
||||
class PRAutoBlogger_Cloudflare_Image_Provider implements PRAutoBlogger_Image_Provider_Interface {
|
||||
|
||||
private const PROVIDER_ID = 'cloudflare_workers_ai';
|
||||
private const MIN_DIMENSION_PX = 64;
|
||||
private const MAX_DIMENSION_PX = 2048;
|
||||
private const DEFAULT_STEPS_SCHNELL = 4;
|
||||
private const RETRY_AFTER_CAP_S = 60;
|
||||
|
||||
/**
|
||||
* Pricing + model-id resolver. Constructed once per provider instance.
|
||||
*
|
||||
* @var PRAutoBlogger_Cloudflare_Image_Pricing
|
||||
*/
|
||||
private PRAutoBlogger_Cloudflare_Image_Pricing $pricing;
|
||||
|
||||
/**
|
||||
* Token, account, URL, and log helpers — pulled out of this class to
|
||||
* keep it under the 300-line cap.
|
||||
*
|
||||
* @var PRAutoBlogger_Cloudflare_Image_Support
|
||||
*/
|
||||
private PRAutoBlogger_Cloudflare_Image_Support $support;
|
||||
|
||||
/**
|
||||
* Construct the provider with its default pricing + support helpers.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->pricing = new PRAutoBlogger_Cloudflare_Image_Pricing();
|
||||
$this->support = new PRAutoBlogger_Cloudflare_Image_Support();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a single image from a prompt at the requested dimensions.
|
||||
*
|
||||
* Retries 5xx / 429 / network errors with exponential backoff bounded
|
||||
* by PRAUTOBLOGGER_MAX_RETRIES. 4xx other than 429 fail loudly on the
|
||||
* first attempt — retrying a bad prompt or a bad token wastes money.
|
||||
*
|
||||
* Side effects: one HTTP request per attempt; one Logger line per attempt.
|
||||
*
|
||||
* {@inheritDoc}
|
||||
*
|
||||
* @throws \InvalidArgumentException If dimensions out of range or prompt empty.
|
||||
* @throws \RuntimeException On auth failure, bad response shape, or retry exhaustion.
|
||||
*/
|
||||
public function generate_image( string $prompt, int $width, int $height, array $options = [] ): array {
|
||||
// FLUX.1 requires dimensions divisible by 8; round to nearest valid value.
|
||||
$width = (int) ( round( $width / 8 ) * 8 );
|
||||
$height = (int) ( round( $height / 8 ) * 8 );
|
||||
|
||||
$this->assert_valid_dimensions( $width, $height );
|
||||
$prompt = trim( $prompt );
|
||||
if ( '' === $prompt ) {
|
||||
throw new \InvalidArgumentException(
|
||||
esc_html__( 'Image prompt cannot be empty.', 'prautoblogger' )
|
||||
);
|
||||
}
|
||||
|
||||
$account_id = $this->support->get_account_id();
|
||||
$api_token = $this->support->get_api_token();
|
||||
$model = $this->pricing->resolve_model( (string) ( $options['model'] ?? '' ) );
|
||||
|
||||
$body = [
|
||||
'prompt' => $prompt,
|
||||
'width' => $width,
|
||||
'height' => $height,
|
||||
'steps' => (int) ( $options['steps'] ?? self::DEFAULT_STEPS_SCHNELL ),
|
||||
];
|
||||
if ( isset( $options['seed'] ) ) {
|
||||
$body['seed'] = (int) $options['seed'];
|
||||
}
|
||||
|
||||
$url = $this->support->build_endpoint_url( $account_id, $model );
|
||||
$headers = [
|
||||
'Authorization' => 'Bearer ' . $api_token,
|
||||
'Content-Type' => 'application/json',
|
||||
'Accept' => 'image/*',
|
||||
];
|
||||
$started_at = microtime( true );
|
||||
$last_error = '';
|
||||
|
||||
for ( $attempt = 1; $attempt <= PRAUTOBLOGGER_MAX_RETRIES; $attempt++ ) {
|
||||
$response = wp_remote_post(
|
||||
$url,
|
||||
[
|
||||
'timeout' => PRAUTOBLOGGER_API_TIMEOUT_SECONDS,
|
||||
'headers' => $headers,
|
||||
'body' => wp_json_encode( $body ),
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
$last_error = $response->get_error_message();
|
||||
$this->support->log_retryable_failure( $attempt, 'network', $last_error );
|
||||
$this->sleep_for_attempt( $attempt );
|
||||
continue;
|
||||
}
|
||||
|
||||
$status = (int) wp_remote_retrieve_response_code( $response );
|
||||
$raw = (string) wp_remote_retrieve_body( $response );
|
||||
|
||||
if ( 429 === $status || $status >= 500 ) {
|
||||
$last_error = sprintf( 'HTTP %d: %s', $status, substr( $raw, 0, 300 ) );
|
||||
$this->support->log_retryable_failure( $attempt, (string) $status, $last_error );
|
||||
if ( $attempt < PRAUTOBLOGGER_MAX_RETRIES ) {
|
||||
$retry_after = (int) wp_remote_retrieve_header( $response, 'retry-after' );
|
||||
$this->sleep_for_attempt( $attempt, $retry_after );
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( $status >= 400 ) {
|
||||
$this->support->log_client_error( $status, $api_token, $account_id, $raw );
|
||||
$this->support->throw_if_nsfw( $raw );
|
||||
throw new \RuntimeException(
|
||||
sprintf(
|
||||
/* translators: %1$d: HTTP status, %2$s: error body. */
|
||||
esc_html__( 'Cloudflare Workers AI error (HTTP %1$d): %2$s', 'prautoblogger' ),
|
||||
$status,
|
||||
esc_html( substr( $raw, 0, 300 ) )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Success. FLUX on Workers AI returns either raw image bytes
|
||||
// (Content-Type: image/*) or a JSON envelope with base64 under
|
||||
// `result.image`. Handle both without branching the caller.
|
||||
$mime = (string) wp_remote_retrieve_header( $response, 'content-type' );
|
||||
[ $raw, $mime ] = $this->normalize_response_body( $raw, $mime );
|
||||
|
||||
return [
|
||||
'bytes' => $raw,
|
||||
'mime_type' => $mime,
|
||||
'width' => $width,
|
||||
'height' => $height,
|
||||
'model' => $model,
|
||||
'seed' => isset( $body['seed'] ) ? (int) $body['seed'] : null,
|
||||
'cost_usd' => $this->pricing->estimate_cost( $width, $height, $model ),
|
||||
'latency_ms' => (int) ( ( microtime( true ) - $started_at ) * 1000 ),
|
||||
];
|
||||
}
|
||||
|
||||
throw new \RuntimeException(
|
||||
sprintf(
|
||||
/* translators: %1$d: max retries, %2$s: last error. */
|
||||
esc_html__( 'Cloudflare Workers AI failed after %1$d attempts. Last error: %2$s', 'prautoblogger' ),
|
||||
PRAUTOBLOGGER_MAX_RETRIES,
|
||||
esc_html( $last_error )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sequential fallback — Cloudflare Workers AI does not support batching.
|
||||
*
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function generate_image_batch( array $requests ): array {
|
||||
$results = [];
|
||||
foreach ( $requests as $key => $req ) {
|
||||
try {
|
||||
$results[ $key ] = $this->generate_image( $req['prompt'], $req['width'], $req['height'], $req['options'] ?? [] );
|
||||
} catch ( PRAutoBlogger_Image_NSFW_Blocked $e ) {
|
||||
// Tag NSFW so the pipeline's retry layer can rebuild the prompt.
|
||||
$results[ $key ] = [ 'error' => $e->getMessage(), 'error_type' => 'nsfw_blocked' ];
|
||||
} catch ( \Throwable $e ) {
|
||||
$results[ $key ] = [ 'error' => $e->getMessage() ];
|
||||
}
|
||||
}
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate the USD cost of a single generation call.
|
||||
*
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function estimate_cost( int $width, int $height, array $options = [] ): float {
|
||||
$model = $this->pricing->resolve_model( (string) ( $options['model'] ?? '' ) );
|
||||
return $this->pricing->estimate_cost( $width, $height, $model );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string Machine-readable provider id used in logs and settings.
|
||||
*/
|
||||
public function get_provider_name(): string {
|
||||
return self::PROVIDER_ID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify credentials are present and the API is reachable.
|
||||
*
|
||||
* Delegates to PRAutoBlogger_Cloudflare_Image_Validator so the HTTP probe
|
||||
* and error-shape code can be tested and sized independently.
|
||||
*
|
||||
* Side effects: one HTTP GET via the validator; one Logger line on failure.
|
||||
*
|
||||
* @return array{status: string, message: string, debug?: string}
|
||||
*/
|
||||
public function validate_credentials_detailed(): array {
|
||||
return ( new PRAutoBlogger_Cloudflare_Image_Validator() )->run();
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforce the interface's dimension contract.
|
||||
*
|
||||
* @param int $width Width in pixels.
|
||||
* @param int $height Height in pixels.
|
||||
* @return void
|
||||
* @throws \InvalidArgumentException If either dimension is outside [MIN, MAX].
|
||||
*/
|
||||
private function assert_valid_dimensions( int $width, int $height ): void {
|
||||
if (
|
||||
$width < self::MIN_DIMENSION_PX || $width > self::MAX_DIMENSION_PX ||
|
||||
$height < self::MIN_DIMENSION_PX || $height > self::MAX_DIMENSION_PX
|
||||
) {
|
||||
throw new \InvalidArgumentException(
|
||||
sprintf(
|
||||
/* translators: %1$d: width, %2$d: height, %3$d: min, %4$d: max. */
|
||||
esc_html__( 'Image dimensions %1$dx%2$d are outside the supported range (%3$d–%4$d px per axis).', 'prautoblogger' ),
|
||||
$width,
|
||||
$height,
|
||||
self::MIN_DIMENSION_PX,
|
||||
self::MAX_DIMENSION_PX
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a 2xx response into [bytes, mime-type] whether the body
|
||||
* arrives as raw image bytes or as a JSON envelope with base64 image.
|
||||
*
|
||||
* @param string $raw Raw response body.
|
||||
* @param string $mime Response Content-Type header value (may be empty).
|
||||
* @return array{0: string, 1: string} [image bytes, mime type]
|
||||
* @throws \RuntimeException If the body matches neither expected shape.
|
||||
*/
|
||||
private function normalize_response_body( string $raw, string $mime ): array {
|
||||
if ( '' !== $mime && 0 === stripos( $mime, 'image/' ) ) {
|
||||
return [ $raw, $mime ];
|
||||
}
|
||||
$decoded = json_decode( $raw, true );
|
||||
if ( is_array( $decoded ) && isset( $decoded['result']['image'] ) && is_string( $decoded['result']['image'] ) ) {
|
||||
$bytes = (string) base64_decode( $decoded['result']['image'], true );
|
||||
if ( '' !== $bytes ) {
|
||||
return [ $bytes, 'image/png' ];
|
||||
}
|
||||
}
|
||||
throw new \RuntimeException(
|
||||
esc_html__( 'Cloudflare Workers AI returned an unexpected response shape.', 'prautoblogger' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sleep between retries. Retry-After header value wins when present,
|
||||
* otherwise exponential backoff from the PRAUTOBLOGGER_* constants.
|
||||
*
|
||||
* @param int $attempt 1-based attempt number that just failed.
|
||||
* @param int $retry_after_secs Retry-After header value (0 if absent).
|
||||
* @return void
|
||||
*/
|
||||
private function sleep_for_attempt( int $attempt, int $retry_after_secs = 0 ): void {
|
||||
$backoff = PRAUTOBLOGGER_RETRY_BASE_DELAY_SECONDS * (int) pow( 2, $attempt - 1 );
|
||||
$delay = $retry_after_secs > 0 ? min( $retry_after_secs, self::RETRY_AFTER_CAP_S ) : $backoff;
|
||||
if ( $delay > 0 ) {
|
||||
sleep( $delay );
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,229 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Small support helpers for the Cloudflare image provider — credential
|
||||
* lookups, URL building, and structured log lines.
|
||||
*
|
||||
* Split out of the provider so the provider stays under the 300-line cap
|
||||
* and so these tiny pieces are individually testable. Pure functions plus
|
||||
* one logger forward; no state.
|
||||
*
|
||||
* Triggered by: PRAutoBlogger_Cloudflare_Image_Provider only.
|
||||
* Dependencies: PRAutoBlogger_Encryption (token decryption),
|
||||
* PRAutoBlogger_Logger (WARN/ERROR forwarding).
|
||||
*
|
||||
* @see class-cloudflare-image-provider.php Sole caller.
|
||||
*/
|
||||
class PRAutoBlogger_Cloudflare_Image_Support {
|
||||
|
||||
/**
|
||||
* Decrypt the Cloudflare API token from the settings option.
|
||||
*
|
||||
* @return string Plaintext token, or empty string if not set / decrypt fails.
|
||||
*/
|
||||
public function get_api_token(): string {
|
||||
$stored = (string) get_option( 'prautoblogger_cloudflare_ai_token', '' );
|
||||
if ( '' === $stored ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// If the token is already encrypted (has "enc:" prefix), decrypt it.
|
||||
if ( PRAutoBlogger_Encryption::is_encrypted( $stored ) ) {
|
||||
return (string) PRAutoBlogger_Encryption::decrypt( $stored );
|
||||
}
|
||||
|
||||
// Legacy: token was saved as plaintext before the field was added to
|
||||
// the encrypted list in sanitize_field(). Encrypt it now so future
|
||||
// reads go through the normal path, then return the plaintext value.
|
||||
$cipher = PRAutoBlogger_Encryption::encrypt( $stored );
|
||||
if ( '' !== $cipher ) {
|
||||
update_option( 'prautoblogger_cloudflare_ai_token', $cipher );
|
||||
}
|
||||
return $stored;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the Cloudflare account ID from settings.
|
||||
*
|
||||
* @return string Account UUID, or empty string.
|
||||
*/
|
||||
public function get_account_id(): string {
|
||||
return trim( (string) get_option( 'prautoblogger_cloudflare_account_id', '' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the Workers AI run URL for a given account + model.
|
||||
*
|
||||
* By default routes through the Cloudflare AI Gateway we already use for
|
||||
* OpenRouter — the gateway route to Workers AI was observed 403ing in
|
||||
* April 2026 (see ARCHITECTURE.md #16), but manual probe on 2026-04-21
|
||||
* shows it's now returning 200. Gateway routing gives us response caching,
|
||||
* cost logging, rate limiting, and provider fallback for free.
|
||||
*
|
||||
* Direct-API fallback kicks in automatically when either the
|
||||
* `prautoblogger_ai_gateway_base_url` option is empty (no gateway
|
||||
* configured at all) or the new `prautoblogger_cf_image_via_gateway`
|
||||
* toggle is off (explicit opt-out for if the gateway route regresses).
|
||||
*
|
||||
* @param string $account_id Cloudflare account UUID.
|
||||
* @param string $model Fully-qualified Workers AI model id (e.g. @cf/black-forest-labs/flux-1-schnell).
|
||||
* @return string Fully-formed HTTPS URL.
|
||||
*/
|
||||
public function build_endpoint_url( string $account_id, string $model ): string {
|
||||
$gateway_url = $this->build_gateway_workers_ai_url( $account_id, $model );
|
||||
if ( '' !== $gateway_url ) {
|
||||
return $gateway_url;
|
||||
}
|
||||
return sprintf(
|
||||
'https://api.cloudflare.com/client/v4/accounts/%s/ai/run/%s',
|
||||
rawurlencode( $account_id ),
|
||||
ltrim( $model, '/' )
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a Workers AI URL rooted at the same AI Gateway we already use
|
||||
* for OpenRouter. Returns empty string when the gateway isn't configured
|
||||
* or the admin toggle opts out — the caller falls back to direct API.
|
||||
*
|
||||
* The existing `prautoblogger_ai_gateway_base_url` option points at
|
||||
* `https://gateway.ai.cloudflare.com/v1/{account}/{gateway}/openrouter`
|
||||
* for the LLM path; we strip the `/openrouter` suffix and append
|
||||
* `/workers-ai/{model}` for the image path. Defensive: only emits a URL
|
||||
* that pattern-matches, so a bad option value quietly falls back.
|
||||
*
|
||||
* @param string $account_id Cloudflare account UUID (kept for symmetry; not used in URL derivation).
|
||||
* @param string $model Fully-qualified Workers AI model id.
|
||||
* @return string Gateway URL, or empty string if unavailable.
|
||||
*/
|
||||
private function build_gateway_workers_ai_url( string $account_id, string $model ): string {
|
||||
unset( $account_id );
|
||||
if ( '1' !== (string) get_option( 'prautoblogger_cf_image_via_gateway', '1' ) ) {
|
||||
return '';
|
||||
}
|
||||
$gateway_base = rtrim( (string) get_option( 'prautoblogger_ai_gateway_base_url', '' ), '/' );
|
||||
if ( '' === $gateway_base ) {
|
||||
return '';
|
||||
}
|
||||
// Must be an https CF AI Gateway URL.
|
||||
if ( 0 !== stripos( $gateway_base, 'https://gateway.ai.cloudflare.com/' ) ) {
|
||||
return '';
|
||||
}
|
||||
// The configured URL ends with `/openrouter` (LLM route). The gateway
|
||||
// root — shared with the Workers AI route — is everything before the
|
||||
// last `/`. If no `/` is present (defensive), we drop back to direct API.
|
||||
$last_slash = strrpos( $gateway_base, '/' );
|
||||
if ( false === $last_slash ) {
|
||||
return '';
|
||||
}
|
||||
$gateway_root = substr( $gateway_base, 0, $last_slash );
|
||||
if ( '' === $gateway_root ) {
|
||||
return '';
|
||||
}
|
||||
return sprintf( '%s/workers-ai/%s', $gateway_root, ltrim( $model, '/' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a WARN line for a retryable failure.
|
||||
*
|
||||
* @param int $attempt 1-based attempt number.
|
||||
* @param string $failure_class Either 'network' or HTTP status code as string.
|
||||
* @param string $detail Short failure detail for the log.
|
||||
* @return void
|
||||
*/
|
||||
public function log_retryable_failure( int $attempt, string $failure_class, string $detail ): void {
|
||||
PRAutoBlogger_Logger::instance()->warning(
|
||||
sprintf(
|
||||
'Cloudflare image gen %s failure (attempt %d/%d): %s',
|
||||
$failure_class,
|
||||
$attempt,
|
||||
PRAUTOBLOGGER_MAX_RETRIES,
|
||||
$detail
|
||||
),
|
||||
'cloudflare-image'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Log an unrecoverable 4xx with triage context. Never logs the full
|
||||
* secret — only a 4-char token prefix and a 6-char account prefix.
|
||||
*
|
||||
* @param int $status HTTP status returned by Cloudflare.
|
||||
* @param string $api_token Plaintext token.
|
||||
* @param string $account_id Account UUID.
|
||||
* @param string $raw Raw response body (truncated to 300 chars in the log).
|
||||
* @return void
|
||||
*/
|
||||
public function log_client_error( int $status, string $api_token, string $account_id, string $raw ): void {
|
||||
PRAutoBlogger_Logger::instance()->error(
|
||||
sprintf(
|
||||
'Cloudflare image gen HTTP %d (token_prefix=%s, token_len=%d, account=%s): %s',
|
||||
$status,
|
||||
substr( $api_token, 0, 4 ),
|
||||
strlen( $api_token ),
|
||||
substr( $account_id, 0, 6 ),
|
||||
substr( $raw, 0, 300 )
|
||||
),
|
||||
'cloudflare-image'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cloudflare Workers AI error code for NSFW content rejection.
|
||||
*
|
||||
* Observed on FLUX.1 schnell on 2026-04-20 when backfilling the post
|
||||
* "Semaglutide vs Tirzepatide". Documented upstream as
|
||||
* `AiError: Input prompt contains NSFW content.`
|
||||
*/
|
||||
public const ERROR_CODE_NSFW = 3030;
|
||||
|
||||
/**
|
||||
* Return true when the Cloudflare response body contains the NSFW
|
||||
* content-filter error code (3030).
|
||||
*
|
||||
* The body shape is `{"errors":[{"code":3030,"message":"..."}],...}`.
|
||||
* Parsing is tolerant: any JSON decode failure or missing key returns
|
||||
* false, so a malformed 4xx never masquerades as NSFW.
|
||||
*
|
||||
* @param string $raw Raw response body from Cloudflare.
|
||||
* @return bool True when at least one error entry carries code 3030.
|
||||
*/
|
||||
public function is_nsfw_error( string $raw ): bool {
|
||||
$decoded = json_decode( $raw, true );
|
||||
if ( ! is_array( $decoded ) || empty( $decoded['errors'] ) || ! is_array( $decoded['errors'] ) ) {
|
||||
return false;
|
||||
}
|
||||
foreach ( $decoded['errors'] as $err ) {
|
||||
if ( is_array( $err ) && (int) ( $err['code'] ?? 0 ) === self::ERROR_CODE_NSFW ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Throw a typed NSFW exception when the response body signals CF's
|
||||
* content-filter rejection (code 3030). No-op otherwise.
|
||||
*
|
||||
* Centralised so callers stay at one line at the call site and so the
|
||||
* exception-construction shape can't drift between call sites.
|
||||
*
|
||||
* @param string $raw Raw response body.
|
||||
* @return void
|
||||
* @throws PRAutoBlogger_Image_NSFW_Blocked When the body contains code 3030.
|
||||
*/
|
||||
public function throw_if_nsfw( string $raw ): void {
|
||||
if ( ! $this->is_nsfw_error( $raw ) ) {
|
||||
return;
|
||||
}
|
||||
throw new PRAutoBlogger_Image_NSFW_Blocked(
|
||||
sprintf(
|
||||
/* translators: %s: truncated error body. */
|
||||
esc_html__( 'Cloudflare Workers AI rejected the prompt as NSFW: %s', 'prautoblogger' ),
|
||||
esc_html( substr( $raw, 0, 300 ) )
|
||||
),
|
||||
$raw
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Credential + connectivity validator for the Cloudflare image provider.
|
||||
*
|
||||
* Split out of the provider to keep each file under the 300-line cap and
|
||||
* to keep the validation path easy to unit-test without spinning up the
|
||||
* retry loop. The provider's `validate_credentials_detailed()` delegates
|
||||
* straight to `run()` here.
|
||||
*
|
||||
* Triggered by: PRAutoBlogger_Cloudflare_Image_Provider::validate_credentials_detailed()
|
||||
* which is called by the admin "Test Connection" action.
|
||||
* Dependencies: PRAutoBlogger_Encryption (token decryption), PRAutoBlogger_Logger
|
||||
* (WARN/ERROR lines), wp_remote_get().
|
||||
*
|
||||
* @see class-cloudflare-image-provider.php Parent class that delegates here.
|
||||
* @see interface-image-provider.php Return-shape contract.
|
||||
*/
|
||||
class PRAutoBlogger_Cloudflare_Image_Validator {
|
||||
|
||||
private const TIMEOUT_SECONDS = 15;
|
||||
|
||||
/**
|
||||
* Run a non-destructive credential check.
|
||||
*
|
||||
* Lightweight probe: hits the account-scoped AI models listing endpoint.
|
||||
* Never generates a real image — that would cost money on every click.
|
||||
*
|
||||
* Side effects: one HTTP GET; one Logger line on failure.
|
||||
*
|
||||
* @return array{status: string, message: string, debug?: string}
|
||||
*/
|
||||
public function run(): array {
|
||||
$account_id = trim( (string) get_option( 'prautoblogger_cloudflare_account_id', '' ) );
|
||||
if ( '' === $account_id ) {
|
||||
return $this->err(
|
||||
'account_id_empty',
|
||||
__( 'Cloudflare account ID is not set. Go to PRAutoBlogger → Settings → Images.', 'prautoblogger' )
|
||||
);
|
||||
}
|
||||
|
||||
$stored = (string) get_option( 'prautoblogger_cloudflare_ai_token', '' );
|
||||
$api_token = '';
|
||||
if ( '' !== $stored ) {
|
||||
// Handle legacy plaintext tokens (saved before the field was in the encrypted list).
|
||||
$api_token = PRAutoBlogger_Encryption::is_encrypted( $stored )
|
||||
? (string) PRAutoBlogger_Encryption::decrypt( $stored )
|
||||
: $stored;
|
||||
}
|
||||
if ( '' === $api_token ) {
|
||||
return $this->err(
|
||||
'token_empty',
|
||||
__( 'Cloudflare API token is not set. Go to PRAutoBlogger → Settings → Images.', 'prautoblogger' )
|
||||
);
|
||||
}
|
||||
|
||||
$response = wp_remote_get(
|
||||
sprintf(
|
||||
'https://api.cloudflare.com/client/v4/accounts/%s/ai/models/search?per_page=1',
|
||||
rawurlencode( $account_id )
|
||||
),
|
||||
[
|
||||
'timeout' => self::TIMEOUT_SECONDS,
|
||||
'headers' => [
|
||||
'Authorization' => 'Bearer ' . $api_token,
|
||||
'Content-Type' => 'application/json',
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
$msg = $response->get_error_message();
|
||||
PRAutoBlogger_Logger::instance()->error(
|
||||
sprintf( 'Cloudflare credential check wp_error: %s', $msg ),
|
||||
'cloudflare-image'
|
||||
);
|
||||
return $this->err(
|
||||
'wp_error:' . $msg,
|
||||
sprintf(
|
||||
/* translators: %s: transport-layer error message. */
|
||||
esc_html__( 'Network error reaching Cloudflare: %s', 'prautoblogger' ),
|
||||
esc_html( $msg )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
$status = (int) wp_remote_retrieve_response_code( $response );
|
||||
if ( 200 === $status ) {
|
||||
return [
|
||||
'status' => 'ok',
|
||||
'message' => __( 'Cloudflare Workers AI connected.', 'prautoblogger' ),
|
||||
];
|
||||
}
|
||||
|
||||
$body = (string) wp_remote_retrieve_body( $response );
|
||||
PRAutoBlogger_Logger::instance()->warning(
|
||||
sprintf( 'Cloudflare credential check HTTP %d: %s', $status, substr( $body, 0, 200 ) ),
|
||||
'cloudflare-image'
|
||||
);
|
||||
return $this->err(
|
||||
sprintf( 'http_%d', $status ),
|
||||
sprintf(
|
||||
/* translators: %1$d: HTTP status, %2$s: response body. */
|
||||
esc_html__( 'Cloudflare returned HTTP %1$d. %2$s', 'prautoblogger' ),
|
||||
$status,
|
||||
esc_html( substr( $body, 0, 200 ) )
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{status: string, message: string, debug: string}
|
||||
*/
|
||||
private function err( string $debug, string $message ): array {
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => $message,
|
||||
'debug' => $debug,
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user