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:
136
includes/class-schema-installer.php
Normal file
136
includes/class-schema-installer.php
Normal file
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Creates / updates the plugin's custom database tables via `dbDelta`.
|
||||
*
|
||||
* Extracted from `PRAutoBlogger_Activator` in v0.8.2 to keep that class
|
||||
* under the 300-line cap once the timezone-aware cron migration landed.
|
||||
* The Activator delegates to `install()` on activate and on db-version
|
||||
* upgrade; schema definitions live here and only here.
|
||||
*
|
||||
* Triggered by: PRAutoBlogger_Activator::activate().
|
||||
* Dependencies: WordPress $wpdb, dbDelta() from wp-admin/includes/upgrade.php.
|
||||
*
|
||||
* @see class-activator.php — Sole caller; delegates on activate and db-version bump.
|
||||
* @see ARCHITECTURE.md — Data model section documents each table's purpose.
|
||||
*/
|
||||
class PRAutoBlogger_Schema_Installer {
|
||||
|
||||
/**
|
||||
* Create (or upgrade) all plugin tables.
|
||||
*
|
||||
* `dbDelta` is idempotent and will create new tables, add missing
|
||||
* columns on existing tables, and add missing indexes — but it will
|
||||
* not drop columns or indexes. That matches the plugin's forward-only
|
||||
* schema-migration policy.
|
||||
*
|
||||
* Side effects: up to five `CREATE TABLE` / `ALTER TABLE` statements.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function install(): void {
|
||||
global $wpdb;
|
||||
|
||||
$charset_collate = $wpdb->get_charset_collate();
|
||||
$prefix = $wpdb->prefix . 'prautoblogger_';
|
||||
|
||||
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
|
||||
|
||||
// Source data — raw posts/comments from social platforms.
|
||||
$sql_source_data = "CREATE TABLE {$prefix}source_data (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
source_type VARCHAR(50) NOT NULL,
|
||||
source_id VARCHAR(255) NOT NULL,
|
||||
subreddit VARCHAR(255) DEFAULT NULL,
|
||||
title TEXT DEFAULT NULL,
|
||||
content LONGTEXT DEFAULT NULL,
|
||||
author VARCHAR(255) DEFAULT NULL,
|
||||
score INT DEFAULT 0,
|
||||
comment_count INT DEFAULT 0,
|
||||
permalink VARCHAR(500) DEFAULT NULL,
|
||||
collected_at DATETIME NOT NULL,
|
||||
metadata_json LONGTEXT DEFAULT NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY source_unique (source_type, source_id),
|
||||
KEY source_collected (source_type, collected_at)
|
||||
) {$charset_collate};";
|
||||
|
||||
// Analysis results — detected patterns from source data.
|
||||
$sql_analysis = "CREATE TABLE {$prefix}analysis_results (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
analysis_type VARCHAR(50) NOT NULL,
|
||||
topic VARCHAR(500) NOT NULL,
|
||||
summary TEXT DEFAULT NULL,
|
||||
frequency INT DEFAULT 1,
|
||||
relevance_score FLOAT DEFAULT 0,
|
||||
source_ids_json LONGTEXT DEFAULT NULL,
|
||||
analyzed_at DATETIME NOT NULL,
|
||||
metadata_json LONGTEXT DEFAULT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY type_relevance (analysis_type, relevance_score),
|
||||
KEY analyzed_at (analyzed_at)
|
||||
) {$charset_collate};";
|
||||
|
||||
// Generation log — every API call with cost tracking. `run_id`
|
||||
// groups all entries from a single pipeline execution so
|
||||
// `link_generation_logs()` can accurately attribute costs to a post.
|
||||
$sql_generation_log = "CREATE TABLE {$prefix}generation_log (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
post_id BIGINT UNSIGNED DEFAULT NULL,
|
||||
run_id VARCHAR(36) DEFAULT NULL,
|
||||
stage VARCHAR(50) NOT NULL,
|
||||
provider VARCHAR(50) NOT NULL,
|
||||
model VARCHAR(100) NOT NULL,
|
||||
prompt_tokens INT DEFAULT 0,
|
||||
completion_tokens INT DEFAULT 0,
|
||||
estimated_cost DECIMAL(10,6) DEFAULT 0,
|
||||
request_json LONGTEXT DEFAULT NULL,
|
||||
response_status VARCHAR(20) NOT NULL DEFAULT 'success',
|
||||
error_message TEXT DEFAULT NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY post_id (post_id),
|
||||
KEY run_id (run_id),
|
||||
KEY created_at (created_at),
|
||||
KEY stage (stage)
|
||||
) {$charset_collate};";
|
||||
|
||||
// Content scores — post performance metrics for self-improvement.
|
||||
$sql_content_scores = "CREATE TABLE {$prefix}content_scores (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
post_id BIGINT UNSIGNED NOT NULL,
|
||||
pageviews INT DEFAULT 0,
|
||||
avg_time_on_page FLOAT DEFAULT 0,
|
||||
bounce_rate FLOAT DEFAULT 0,
|
||||
comment_count INT DEFAULT 0,
|
||||
composite_score FLOAT DEFAULT 0,
|
||||
score_factors_json LONGTEXT DEFAULT NULL,
|
||||
measured_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY post_id (post_id),
|
||||
KEY measured_at (measured_at),
|
||||
KEY composite_score (composite_score)
|
||||
) {$charset_collate};";
|
||||
|
||||
// Event log — structured application log entries for the admin log viewer.
|
||||
$sql_event_log = "CREATE TABLE {$prefix}event_log (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
level VARCHAR(10) NOT NULL DEFAULT 'info',
|
||||
context VARCHAR(100) DEFAULT NULL,
|
||||
message TEXT NOT NULL,
|
||||
meta_json LONGTEXT DEFAULT NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY level (level),
|
||||
KEY created_at (created_at),
|
||||
KEY level_created (level, created_at)
|
||||
) {$charset_collate};";
|
||||
|
||||
dbDelta( $sql_source_data );
|
||||
dbDelta( $sql_analysis );
|
||||
dbDelta( $sql_generation_log );
|
||||
dbDelta( $sql_content_scores );
|
||||
dbDelta( $sql_event_log );
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user