Files
prautoblogger/includes/providers/class-cloudflare-image-support.php
peptiderepo 80a7e11a2b v0.8.2: CF images via AI Gateway + scheduled-gen timezone fix
* feat(images): route Cloudflare Workers AI via AI Gateway by default

Direct probe on 2026-04-21 confirmed the Cloudflare AI Gateway
route to Workers AI (`gateway.ai.cloudflare.com/.../workers-ai/@cf/...`)
is no longer 403ing — the upstream regression noted in v0.8.0's
ARCHITECTURE.md #16 and in thread image-pipeline seq 6 has been
resolved. Routing via the gateway gives us the same benefits we
already get for OpenRouter LLM calls: response caching, cost/latency
dashboard, rate limiting.

Changes:

- `Cloudflare_Image_Support::build_endpoint_url()` now prefers the
  gateway URL derived from the existing `prautoblogger_ai_gateway_base_url`
  option. Direct API remains the fallback.
- New private helper `build_gateway_workers_ai_url()` strips the
  OpenRouter path suffix from the configured gateway URL and appends
  `/workers-ai/{model}`. Returns empty string (fallback to direct) when:
  no gateway URL configured, the new toggle is off, or the URL isn't a
  valid `https://gateway.ai.cloudflare.com/...` shape.
- New admin toggle `prautoblogger_cf_image_via_gateway` (default on) in
  the Images section. Operators can disable to force direct API without
  clearing the LLM-path gateway URL.
- ARCHITECTURE.md #16 rewritten to reflect the v0.8.2+ gateway routing.
- CHANGELOG.md v0.8.2 entry under Changed.

Tests (new `CloudflareImageSupportTest`):

- Direct URL when gateway not configured.
- Gateway URL derived correctly when configured + toggle on.
- Toggle off forces direct URL even with gateway configured.
- Malformed gateway URL falls back to direct (defensive).
- `is_nsfw_error()` only matches error code 3030 (pinned separately so
  a tolerance regression fails early).

Cost impact: near-zero. Gateway adds a few ms of latency and enables
response caching — could *reduce* cost on identical prompts within the
configurable cache TTL.

Uninstall: new option covered by existing prautoblogger_% LIKE sweep.

Implements Commit 1b (narrow AI-Gateway-migration scope) per thread
image-pipeline seq 7.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* chore(cost): seed new toggles in activator defaults; tighten URL stripper

QA review on cd45ae2 surfaced two things; one real, one hallucinated:

- **Real (fixed):** `prautoblogger_cf_image_via_gateway` and v0.8.1's
  `prautoblogger_image_nsfw_retry` weren't seeded in
  `Activator::set_default_options()`. Belt-and-braces — the `get_option()`
  fallback at the read site already defaults to '1', so no user-visible
  regression exists, but seeding the options follows the established
  pattern for every other plugin setting and makes intent legible to
  operators inspecting `wp_options` directly.
- **Hallucinated (rejected):** the reviewer claimed
  `CloudflareImageSupportTest` methods 2–5 were empty stubs. Verified
  — every test has real `$this->assert*` calls (10 total across the 5
  cases). Ignoring. Flagging the false-positive to the CTO per the
  qa-review quality-tracking protocol.

Also clarified the docblock + tightened the ternary inside
`build_gateway_workers_ai_url()` — explicit `strrpos` false-check
instead of the `?:` short-circuit, so a no-slash base (defensive edge)
falls through cleanly instead of returning a weirdly-sliced URL.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(schedule): interpret `prautoblogger_schedule_time` in site timezone

Per thread scheduled-gen-timezone seq 1: WordPress core calls
`date_default_timezone_set('UTC')` early in bootstrap, so the activator's
`strtotime("tomorrow HH:MM")` was resolving in UTC regardless of the
site's configured timezone. On peptiderepo.com (Asia/Singapore, UTC+8)
a `schedule_time` of `06:00` fired at 14:00 local.

Fold this into the existing v0.8.2 branch (PR #102) since both this fix
and the earlier CF-image-gateway change target the same version and
touch overlapping files (activator, settings-fields-extended).

Changes:

- `Activator::next_daily_generation_timestamp()` — new public helper
  that reads `prautoblogger_schedule_time`, constructs a
  `DateTimeImmutable('tomorrow', wp_timezone())`, applies the
  configured hour/minute, returns a Unix timestamp. Defensive fallback
  to the old UTC-interpretation behaviour on any DateTime parse error
  so a bad tz string can't brick the schedule.
- `Activator::schedule_cron()` delegates to the helper instead of
  calling `strtotime` directly.
- New `Activator::reschedule_daily_in_site_timezone_v082()` — one-shot
  migration that clears the stale UTC-scheduled event and re-queues
  using the helper. Gated by `prautoblogger_migrated_schedule_tz_v082`
  option so it runs exactly once. Logs an INFO line comparing
  before/after next_run for auditability.
- `class-prautoblogger.php::on_check_db_version()` invokes the
  migration on every admin_init; the one-shot flag handles re-run
  guarding (no DB_VERSION bump needed — the migration is independent
  of the schema version).
- Settings description for "Generation Time" now says
  "...in your site's configured timezone (Settings → General →
  Timezone). Current site timezone: <wp_timezone_string()>" instead
  of the ambiguous "server timezone" phrasing.

File-size compliance:
- Adding the timezone helpers pushed `class-activator.php` to 352
  lines. Extracted the 104-line `create_tables()` SQL to a new
  `class-schema-installer.php` (136 lines). Activator now 245 lines,
  schema file fully dedicated to dbDelta.

Tests (new):

- `ActivatorScheduleTest` — SGT 06:00 → 22:00 UTC prev day; UTC 06:00
  → 06:00 UTC (no-op case); Asia/Kathmandu UTC+5:45 → 00:15 UTC
  (fractional offset); malformed time input doesn't throw.
- `ActivatorMigrationTest` — pre-seeded UTC cron gets cleared and
  rescheduled in SGT; second pass is idempotent.

CHANGELOG v0.8.2 entry now also covers the timezone fix under Fixed +
the description wording change under Changed.

Implements thread `scheduled-gen-timezone` seq 1 spec.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: peptiderepo <peptiderepo@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 11:34:37 +07:00

230 lines
8.1 KiB
PHP

<?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
);
}
}