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>
This commit is contained in:
peptiderepo
2026-04-21 11:34:37 +07:00
committed by GitHub
parent 33d3ba4ea1
commit 80a7e11a2b
11 changed files with 661 additions and 123 deletions

View File

@@ -0,0 +1,133 @@
<?php
/**
* Tests for the v0.8.2 one-shot migration that reschedules the daily
* generation cron in the site's configured timezone. Exercises both
* the "first run" path and the "already migrated, no-op" path.
*
* See thread scheduled-gen-timezone/01-cto-handoff.md.
*
* @package PRAutoBlogger\Tests\Core
*/
namespace PRAutoBlogger\Tests\Core;
use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey\Functions;
class ActivatorMigrationTest extends BaseTestCase {
/**
* Track cron scheduling side effects so we can assert on them.
*
* @var array<string, array{scheduled_at: int|null, recurrence: string|null, cleared: bool}>
*/
private array $cron_state = [];
/**
* Track the v0.8.2 migration flag across get_option/update_option calls.
*
* @var array<string, mixed>
*/
private array $options = [];
protected function setUp(): void {
parent::setUp();
$this->cron_state = [
'prautoblogger_daily_generation' => [
'scheduled_at' => null,
'recurrence' => null,
'cleared' => false,
],
];
// Start with a pre-existing cron simulating the v<0.8.2 UTC-interpreted
// schedule, so the migration has something to clear.
$this->cron_state['prautoblogger_daily_generation']['scheduled_at'] = strtotime( 'tomorrow 03:00 UTC' );
$this->cron_state['prautoblogger_daily_generation']['recurrence'] = 'daily';
// Baseline options.
$this->options = [
'prautoblogger_schedule_time' => '06:00',
'prautoblogger_log_level' => 'info',
];
Functions\when( 'get_option' )->alias(
fn( $key, $default = false ) => $this->options[ $key ] ?? $default
);
Functions\when( 'update_option' )->alias(
function ( $key, $value ) {
$this->options[ $key ] = $value;
return true;
}
);
Functions\when( 'wp_next_scheduled' )->alias(
fn( $hook ) => $this->cron_state[ $hook ]['scheduled_at'] ?? false
);
Functions\when( 'wp_clear_scheduled_hook' )->alias(
function ( $hook ) {
if ( isset( $this->cron_state[ $hook ] ) ) {
$this->cron_state[ $hook ]['scheduled_at'] = null;
$this->cron_state[ $hook ]['cleared'] = true;
}
}
);
Functions\when( 'wp_schedule_event' )->alias(
function ( $timestamp, $recurrence, $hook ) {
$this->cron_state[ $hook ]['scheduled_at'] = (int) $timestamp;
$this->cron_state[ $hook ]['recurrence'] = (string) $recurrence;
return true;
}
);
Functions\when( 'wp_timezone' )->alias(
static fn() => new \DateTimeZone( 'Asia/Singapore' )
);
}
/**
* Migration clears the UTC-scheduled event and reschedules in SGT.
* Flag is set so the next pass is a no-op.
*/
public function test_db_version_migration_reschedules_existing_cron(): void {
$before_timestamp = $this->cron_state['prautoblogger_daily_generation']['scheduled_at'];
$this->assertNotNull( $before_timestamp, 'Precondition: stale cron was pre-seeded.' );
\PRAutoBlogger_Activator::reschedule_daily_in_site_timezone_v082();
// Hook was cleared and then re-scheduled in one pass.
$this->assertTrue( $this->cron_state['prautoblogger_daily_generation']['cleared'] );
$after = $this->cron_state['prautoblogger_daily_generation']['scheduled_at'];
$this->assertNotNull( $after );
$this->assertNotSame( $before_timestamp, $after, 'Migration should produce a different timestamp.' );
// Re-scheduled timestamp maps to 06:00 SGT (22:00 UTC prev day).
$utc = ( new \DateTimeImmutable( '@' . $after ) )->setTimezone( new \DateTimeZone( 'UTC' ) );
$this->assertSame( '22:00', $utc->format( 'H:i' ) );
// Flag was set.
$this->assertSame( '1', $this->options['prautoblogger_migrated_schedule_tz_v082'] ?? null );
}
/**
* Running the migration twice is idempotent — the second pass must
* return immediately without clearing or rescheduling.
*/
public function test_db_version_migration_idempotent(): void {
\PRAutoBlogger_Activator::reschedule_daily_in_site_timezone_v082();
// Reset the cleared marker so we can detect a second clear.
$this->cron_state['prautoblogger_daily_generation']['cleared'] = false;
$timestamp_after_first = $this->cron_state['prautoblogger_daily_generation']['scheduled_at'];
\PRAutoBlogger_Activator::reschedule_daily_in_site_timezone_v082();
// No second clear, no re-schedule.
$this->assertFalse( $this->cron_state['prautoblogger_daily_generation']['cleared'] );
$this->assertSame(
$timestamp_after_first,
$this->cron_state['prautoblogger_daily_generation']['scheduled_at']
);
}
}

View File

@@ -0,0 +1,91 @@
<?php
/**
* Tests for `PRAutoBlogger_Activator::next_daily_generation_timestamp()` —
* the v0.8.2 timezone-aware replacement for `strtotime("tomorrow HH:MM")`
* which evaluated in UTC regardless of the WordPress site timezone.
*
* See thread scheduled-gen-timezone/01-cto-handoff.md for the bug report.
*
* @package PRAutoBlogger\Tests\Core
*/
namespace PRAutoBlogger\Tests\Core;
use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey\Functions;
class ActivatorScheduleTest extends BaseTestCase {
/**
* Stub `wp_timezone()` to return the given tz id, and seed
* `prautoblogger_schedule_time` with the given value.
*/
private function with_site_tz_and_time( string $tz_id, string $time_str ): void {
$this->stub_get_option( [
'prautoblogger_schedule_time' => $time_str,
] );
Functions\when( 'wp_timezone' )->alias(
static fn() => new \DateTimeZone( $tz_id )
);
}
/**
* On an Asia/Singapore site (UTC+8), `schedule_time = 06:00` must
* resolve to 22:00 UTC the previous day — the prod bug from thread
* scheduled-gen-timezone seq 1.
*/
public function test_schedule_cron_uses_site_timezone(): void {
$this->with_site_tz_and_time( 'Asia/Singapore', '06:00' );
$timestamp = \PRAutoBlogger_Activator::next_daily_generation_timestamp();
$this->assertGreaterThan( 0, $timestamp );
$utc = ( new \DateTimeImmutable( '@' . $timestamp ) )->setTimezone( new \DateTimeZone( 'UTC' ) );
$this->assertSame( '22:00', $utc->format( 'H:i' ), 'Expected 06:00 SGT == 22:00 UTC previous day' );
// And it really is "tomorrow" in Singapore — date part should not be today SGT.
$sgt = ( new \DateTimeImmutable( '@' . $timestamp ) )->setTimezone( new \DateTimeZone( 'Asia/Singapore' ) );
$tomorrow_sgt = ( new \DateTimeImmutable( 'tomorrow', new \DateTimeZone( 'Asia/Singapore' ) ) )->format( 'Y-m-d' );
$this->assertSame( $tomorrow_sgt, $sgt->format( 'Y-m-d' ) );
}
/**
* UTC site, `06:00` input → 06:00 UTC. Behaviour unchanged for
* the always-UTC case; regression guard.
*/
public function test_schedule_cron_handles_utc_site(): void {
$this->with_site_tz_and_time( 'UTC', '06:00' );
$timestamp = \PRAutoBlogger_Activator::next_daily_generation_timestamp();
$utc = ( new \DateTimeImmutable( '@' . $timestamp ) )->setTimezone( new \DateTimeZone( 'UTC' ) );
$this->assertSame( '06:00', $utc->format( 'H:i' ) );
}
/**
* Nepal runs UTC+5:45. 06:00 local → 00:15 UTC. Guards against any
* integer-hour-offset assumptions in the conversion logic.
*/
public function test_schedule_cron_handles_fractional_offset(): void {
$this->with_site_tz_and_time( 'Asia/Kathmandu', '06:00' );
$timestamp = \PRAutoBlogger_Activator::next_daily_generation_timestamp();
$utc = ( new \DateTimeImmutable( '@' . $timestamp ) )->setTimezone( new \DateTimeZone( 'UTC' ) );
$this->assertSame( '00:15', $utc->format( 'H:i' ) );
}
/**
* Malformed `schedule_time` (e.g. blank string saved accidentally)
* must not throw — `absint()` clamps to 0:0 and the helper returns
* a valid timestamp. Regression guard against the "bricked schedule
* on bad input" failure mode.
*/
public function test_schedule_cron_survives_malformed_time_input(): void {
$this->with_site_tz_and_time( 'UTC', '' );
$timestamp = \PRAutoBlogger_Activator::next_daily_generation_timestamp();
$this->assertGreaterThan( 0, $timestamp );
}
}

View File

@@ -0,0 +1,115 @@
<?php
/**
* Tests for PRAutoBlogger_Cloudflare_Image_Support — URL building in
* particular. The v0.8.2 gateway migration added a derivation path from
* the existing `prautoblogger_ai_gateway_base_url` OpenRouter gateway
* URL to the corresponding Workers AI URL at the same gateway root.
*
* @package PRAutoBlogger\Tests\Providers
*/
namespace PRAutoBlogger\Tests\Providers;
use PRAutoBlogger\Tests\BaseTestCase;
use Brain\Monkey\Functions;
class CloudflareImageSupportTest extends BaseTestCase {
private const ACCOUNT_ID = 'a16f4baa82a1074c47f696e7cb6d5995';
private const MODEL = '@cf/black-forest-labs/flux-1-schnell';
/**
* With no gateway URL configured, the support class returns the direct
* Workers AI API URL — the historical behaviour prior to v0.8.2.
*/
public function test_returns_direct_url_when_gateway_not_configured(): void {
$this->stub_get_option( [
'prautoblogger_ai_gateway_base_url' => '',
'prautoblogger_cf_image_via_gateway' => '1',
] );
$support = new \PRAutoBlogger_Cloudflare_Image_Support();
$url = $support->build_endpoint_url( self::ACCOUNT_ID, self::MODEL );
$this->assertStringStartsWith( 'https://api.cloudflare.com/client/v4/accounts/', $url );
$this->assertStringContainsString( self::ACCOUNT_ID, $url );
$this->assertStringEndsWith( self::MODEL, $url );
}
/**
* With the AI Gateway URL configured and the toggle on, image calls
* route through `gateway.ai.cloudflare.com/.../workers-ai/{model}` at
* the same gateway root as the OpenRouter LLM path.
*/
public function test_returns_gateway_url_when_configured_and_toggle_on(): void {
$this->stub_get_option( [
'prautoblogger_ai_gateway_base_url' => 'https://gateway.ai.cloudflare.com/v1/' . self::ACCOUNT_ID . '/peptiderepo-prod/openrouter',
'prautoblogger_cf_image_via_gateway' => '1',
] );
$support = new \PRAutoBlogger_Cloudflare_Image_Support();
$url = $support->build_endpoint_url( self::ACCOUNT_ID, self::MODEL );
$this->assertSame(
'https://gateway.ai.cloudflare.com/v1/' . self::ACCOUNT_ID . '/peptiderepo-prod/workers-ai/' . self::MODEL,
$url
);
}
/**
* The toggle overrides the gateway URL: operators can fall back to the
* direct API if the gateway regresses, without clearing the OpenRouter
* gateway setting that the LLM provider depends on.
*/
public function test_toggle_off_forces_direct_url_even_with_gateway_configured(): void {
$this->stub_get_option( [
'prautoblogger_ai_gateway_base_url' => 'https://gateway.ai.cloudflare.com/v1/' . self::ACCOUNT_ID . '/peptiderepo-prod/openrouter',
'prautoblogger_cf_image_via_gateway' => '0',
] );
$support = new \PRAutoBlogger_Cloudflare_Image_Support();
$url = $support->build_endpoint_url( self::ACCOUNT_ID, self::MODEL );
$this->assertStringStartsWith( 'https://api.cloudflare.com/client/v4/accounts/', $url );
}
/**
* A malformed gateway URL (e.g. http, or a totally different host) is
* rejected and the direct-API path is used instead. Defensive — a bad
* option value shouldn't break image generation.
*/
public function test_falls_back_to_direct_when_gateway_url_is_malformed(): void {
$this->stub_get_option( [
'prautoblogger_ai_gateway_base_url' => 'http://evil.example.com/openrouter',
'prautoblogger_cf_image_via_gateway' => '1',
] );
$support = new \PRAutoBlogger_Cloudflare_Image_Support();
$url = $support->build_endpoint_url( self::ACCOUNT_ID, self::MODEL );
$this->assertStringStartsWith( 'https://api.cloudflare.com/client/v4/accounts/', $url );
}
/**
* The NSFW detector must match on the documented error code without
* tripping on other 4xx bodies. (Covered at the provider level too,
* but worth pinning at the support class so a tolerance regression
* fails early.)
*/
public function test_is_nsfw_error_matches_code_3030_only(): void {
$support = new \PRAutoBlogger_Cloudflare_Image_Support();
$this->assertTrue(
$support->is_nsfw_error( '{"errors":[{"code":3030,"message":"NSFW"}]}' )
);
$this->assertFalse(
$support->is_nsfw_error( '{"errors":[{"code":7003,"message":"bad token"}]}' )
);
$this->assertFalse(
$support->is_nsfw_error( 'not json at all' )
);
$this->assertFalse(
$support->is_nsfw_error( '{}' )
);
}
}