Compare commits
6 Commits
claude/fix
...
claude/pra
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22ae7e7bd3 | ||
|
|
77ef941b3d | ||
|
|
732ef9b1fb | ||
|
|
f10e1772b3 | ||
|
|
02e9aabea6 | ||
|
|
50369bb644 |
2
.github/workflows/cto-review.yml
vendored
2
.github/workflows/cto-review.yml
vendored
@@ -451,7 +451,7 @@ jobs:
|
||||
if rev.get("concerns"):
|
||||
lines.append("**Concerns:**")
|
||||
for c in rev["concerns"]:
|
||||
sev = c["severity"].upper()
|
||||
sev = c.get("severity", "UNKNOWN").upper()
|
||||
f = f"`{c['file']}`" if c.get("file") else ""
|
||||
lines.append(f"- **{sev}** {f} — {c['issue']}")
|
||||
lines.append("")
|
||||
|
||||
@@ -128,7 +128,8 @@ prautoblogger/
|
||||
│ ├── class-prautoblogger.php # Main orchestrator — registers all hooks, delegates execution
|
||||
│ ├── class-pipeline-schema-installer.php # v0.18.0 substrate tables (prompts, run_sources, run_decisions, runs, run_stages)
|
||||
│ ├── class-migrate-prompt-seed-v0180.php # One-shot v0.18.0 prompt-registry seed migration
|
||||
│ ├── class-executor.php # Cron handlers, generation AJAX (start + status), model registry
|
||||
│ ├── class-executor.php # Cron handlers, generation AJAX (delegates start + status to poller), model registry
|
||||
│ ├── class-generation-status-poller.php # Generation AJAX handlers: status transient renewal, lock-age orphan detection (R2b/R3), abort_orphaned_run
|
||||
│ ├── class-ajax-handlers.php # Non-generation AJAX: images, models, test connections
|
||||
│ ├── class-generation-lock.php # DB-level atomic mutex for single-writer generation
|
||||
│ ├── class-activator.php # Activation: create DB tables, set defaults, schedule cron
|
||||
@@ -213,6 +214,8 @@ prautoblogger/
|
||||
│ │ ├── class-runware-image-pricing.php # FLUX schnell/dev cost table + resolver
|
||||
│ │ ├── class-runware-image-support.php # Key, response parsing, retry, dimension snap
|
||||
│ │ ├── class-runware-image-batch.php # True parallel curl_multi batch dispatcher
|
||||
│ │ ├── class-runware-model-catalog.php # Live model catalog sync: modelSearch pagination, cache v2, failure cooldown
|
||||
│ │ ├── class-runware-catalog-fetcher.php # HTTP fetch + normalize_models for Runware modelSearch (extracted for 300-line rule)
|
||||
│ │ └── (new providers go here — see CONVENTIONS.md)
|
||||
│ │
|
||||
│ ├── services/
|
||||
@@ -337,11 +340,19 @@ Hostinger's 120-second LiteSpeed connection timeout. The frontend polls for stat
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
**Fallback detection:** If Hostinger kills the PHP process before it updates the
|
||||
transient (despite `ignore_user_abort`), the status endpoint detects the orphan after
|
||||
180 seconds by checking for recently-created posts with `_prautoblogger_run_id` meta.
|
||||
It also releases any stale generation lock. After 600 seconds (STATUS_TTL), it gives
|
||||
up unconditionally and reports a timeout.
|
||||
**Fallback detection (v0.18.3 R2b/R3):** The status transient is renewed on every stage
|
||||
transition via `update_generation_stage()` (`Pipeline_Status::broadcast()`), so its TTL
|
||||
always counts from the last activity rather than run start. When a status poll finds the
|
||||
transient absent:
|
||||
|
||||
- **Lock within TTL (`lock_age ≤ STATUS_TTL = 600s`):** the background process is still alive
|
||||
but has not broadcast yet (or the transient was evicted). `handle_missing_transient()` returns
|
||||
`status: running` (R3) — button stays in-progress, no state change.
|
||||
- **Lock exceeded TTL (`lock_age > STATUS_TTL`):** background process died without releasing the
|
||||
lock. `abort_orphaned_run()` marks the `runs` row `failed`, releases the generation lock, deletes
|
||||
the status transient and queue option, and returns `status: error` with "infrastructure timeout"
|
||||
(R2b). A daily `Run_Reaper::sweep_stuck_runs()` at 2× `EXPECTED_RUN_SECONDS` (~3600s) remains
|
||||
the backstop for runs the poll path never sees.
|
||||
|
||||
---
|
||||
|
||||
|
||||
61
CHANGELOG.md
61
CHANGELOG.md
@@ -5,6 +5,67 @@ All notable changes to PRAutoBlogger will be documented in this file.
|
||||
Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project uses [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [0.18.3] - 2026-06-12
|
||||
|
||||
GA4-context SQL fix, manual-run resilience, and honest status on transient expiry
|
||||
(CTO thread `2026-06-pipeline-v2-phase1` seq 38).
|
||||
|
||||
### Fixed
|
||||
- **Analysis-prompts SQL / GA4 self-improvement loop (R1 — P2)**: `phpcs:ignore` annotation
|
||||
was embedded inside the SQL string literal in `class-analysis-prompts.php:81` (same pattern
|
||||
as the v0.18.2 cost-reporter fix). MariaDB rejected the query on every pipeline run,
|
||||
causing `get_performance_context()` to always return `''` — the LLM research/analysis
|
||||
stage has had no historical performance context since v0.16.0. Annotation moved to the
|
||||
`// phpcs:ignore` pragma above `get_results()`. Sibling occurrence also fixed in
|
||||
`class-post-assembler.php:112` (same pattern). Regression + behavioral tests added to
|
||||
`AnalysisPromptsTest`.
|
||||
- **Manual-run resilience — transient renewal (R2a)**: `update_generation_stage()` in the
|
||||
new `PRAutoBlogger_Generation_Status_Poller` now renews the STATUS_TTL on every stage
|
||||
update, ensuring the status transient outlasts any single LLM call even when `Pipeline_
|
||||
Status::broadcast()` is delayed by a long model call.
|
||||
- **Manual-run resilience — stuck-run detection (R2b)**: `on_ajax_generation_status()`
|
||||
now detects when the status transient is absent but the generation lock has been held
|
||||
longer than STATUS_TTL seconds — indicative of a Hostinger background-process kill.
|
||||
Marks the stuck run `failed` in the audit ledger, releases the lock, and returns
|
||||
`status: error` with an "infrastructure timeout" message instead of silently resetting
|
||||
to idle.
|
||||
- **Honest status when transient gone but lock held (R3)**: when the status transient is
|
||||
absent but the lock is held within TTL, `on_ajax_generation_status()` now returns
|
||||
`status: running` with `started_at` from the lock timestamp (rather than `status: idle`)
|
||||
so the Generate Now button reflects reality during long background runs.
|
||||
|
||||
### Changed
|
||||
- **Executor split (300-line rule)**: `class-executor.php` was at 351 lines. AJAX generation
|
||||
handlers (`on_ajax_generate_now`, `on_ajax_generation_status`, `abort_orphaned_run`,
|
||||
`update_generation_stage`) extracted to new `class-generation-status-poller.php` (260 lines).
|
||||
Executor retains cron handlers and delegates AJAX calls to the poller. Public API unchanged.
|
||||
- **Generation_Lock**: new `get_acquired_at()` method returns the Unix timestamp when the
|
||||
lock was set, used by R2b/R3 to determine lock age without touching the pipeline run table.
|
||||
|
||||
### Added
|
||||
- **Runware catalog `modelSearch` migration**: `class-runware-model-catalog.php` migrated
|
||||
from the retired `taskType:models` endpoint to the current `taskType:modelSearch` API.
|
||||
Payload format: `[{taskType:authentication,apiKey:...},{taskType:modelSearch,
|
||||
taskUUID:<uuid4>,offset:N,limit:N}]`. Response normalization updated for the new shape:
|
||||
`air` identifier replaces `id`, `capabilities[]` array replaces `taskType`/`requiresImage`
|
||||
(filter: entry must contain `"io:text-to-image"`), `comment` field maps to `description`.
|
||||
Logic extracted to `class-runware-catalog-fetcher.php` companion (300-line rule). Cache
|
||||
option key bumped to `prautoblogger_runware_model_cache_v2` to cleanly invalidate v1 rows.
|
||||
- **Pagination for `modelSearch`**: fetcher paginates via `offset`/`limit` up to 5 pages of
|
||||
100 results = 500 models inspected. Runware's catalog has 320k+ entries (mostly community
|
||||
checkpoints); 5 pages reliably captures all curated text-to-image models. A page-cap
|
||||
warning is logged if the cap is reached before exhausting `totalResults`. Client-side
|
||||
`io:text-to-image` capability filter applied — no server-side filter is available.
|
||||
- **Negative-result failure cooldown**: `sync()` records a failure timestamp in
|
||||
`prautoblogger_runware_catalog_last_failure_at` on every error path. `get_models()`
|
||||
gates re-trigger through `is_in_failure_cooldown()`, which respects a configurable
|
||||
window from `prautoblogger_runware_catalog_failure_cooldown_seconds` (default 3600s / 1h,
|
||||
never hardcoded at point of use). A successful sync clears the timestamp. This caps the
|
||||
admin-page-load cascade (42 errors/day observed) to ~24/day even when the cache is absent.
|
||||
- **Hardcoded fallback list preserved**: unchanged; carried prod through the entire
|
||||
`taskType:models` outage. Tests verify it is always non-empty and correctly priced.
|
||||
|
||||
|
||||
## [0.18.2] - 2026-06-12
|
||||
|
||||
Four confirmed-live maintenance fixes (CTO thread `2026-06-pipeline-v2-phase1` seq 25).
|
||||
|
||||
@@ -4,25 +4,26 @@ declare(strict_types=1);
|
||||
/**
|
||||
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
|
||||
*
|
||||
* Cron/AJAX handlers for content generation, metrics collection, model registry.
|
||||
* Cron handlers for content generation and metrics collection.
|
||||
*
|
||||
* What: Daily generation, manual generation, queued-article processing,
|
||||
* and metrics collection cron handlers. AJAX generation handlers
|
||||
* live in PRAutoBlogger_Generation_Status_Poller (v0.18.3 split).
|
||||
* Triggered by: PRAutoBlogger hook registration.
|
||||
* Dependencies: Pipeline_Runner, Metrics_Collector, Generation_Lock, Logger.
|
||||
*
|
||||
* @see class-prautoblogger.php — Hook wiring.
|
||||
* @see core/class-pipeline-runner.php — Actual generation pipeline.
|
||||
* @see class-generation-lock.php — DB mutex.
|
||||
* @see class-generation-status-poller.php — "Generate Now" AJAX + status poll.
|
||||
* @see class-prautoblogger.php — Hook wiring.
|
||||
* @see core/class-pipeline-runner.php — Actual generation pipeline.
|
||||
* @see class-generation-lock.php — DB mutex.
|
||||
*/
|
||||
class PRAutoBlogger_Executor {
|
||||
|
||||
/** @var PRAutoBlogger_OpenRouter_Model_Registry|null Lazy-loaded singleton. */
|
||||
private ?PRAutoBlogger_OpenRouter_Model_Registry $model_registry = null;
|
||||
|
||||
/** Transient key for background generation status. */
|
||||
private const STATUS_TRANSIENT = 'prautoblogger_generation_status';
|
||||
|
||||
/** How long to keep the result available for polling (seconds). */
|
||||
private const STATUS_TTL = 600;
|
||||
/** @var PRAutoBlogger_Generation_Status_Poller|null Lazy-loaded poller. */
|
||||
private ?PRAutoBlogger_Generation_Status_Poller $poller = null;
|
||||
|
||||
/**
|
||||
* Handle the daily generation cron event.
|
||||
@@ -58,20 +59,6 @@ class PRAutoBlogger_Executor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark this process's run failed after a fatal pipeline error
|
||||
* (no-op outside a run; a governor-halted run stays halted — final
|
||||
* states are sticky).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function mark_current_run_failed(): void {
|
||||
$run_id = PRAutoBlogger_Run_Context::current_run_id();
|
||||
if ( null !== $run_id ) {
|
||||
PRAutoBlogger_Run_State::mark_status( $run_id, 'failed' );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the metrics collection cron event.
|
||||
* Side effects: API calls to GA4, database writes to ab_content_scores.
|
||||
@@ -89,79 +76,12 @@ class PRAutoBlogger_Executor {
|
||||
|
||||
/**
|
||||
* AJAX handler: kick off manual generation as a background cron job.
|
||||
*
|
||||
* Returns immediately so the browser never hits Hostinger's 120-second
|
||||
* connection timeout. The frontend polls on_ajax_generation_status()
|
||||
* every few seconds to get progress and final results.
|
||||
* Delegates to PRAutoBlogger_Generation_Status_Poller.
|
||||
*
|
||||
* Side effects: schedules a WP-Cron event, writes a status transient.
|
||||
*/
|
||||
public function on_ajax_generate_now(): void {
|
||||
check_ajax_referer( 'prautoblogger_generate_now', 'nonce' );
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'prautoblogger' ) ), 403 );
|
||||
return;
|
||||
}
|
||||
|
||||
$force = isset( $_POST['force'] ) && '1' === $_POST['force'];
|
||||
if ( $force ) {
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
delete_transient( self::STATUS_TRANSIENT );
|
||||
}
|
||||
|
||||
// Check if a run is already in progress.
|
||||
$current = get_transient( self::STATUS_TRANSIENT );
|
||||
if ( is_array( $current ) && 'running' === ( $current['status'] ?? '' ) ) {
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'background' => true,
|
||||
'message' => __( 'Generation already in progress.', 'prautoblogger' ),
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Write initial "running" status for the frontend to poll.
|
||||
set_transient(
|
||||
self::STATUS_TRANSIENT,
|
||||
array(
|
||||
'status' => 'running',
|
||||
'stage' => __( 'Starting generation...', 'prautoblogger' ),
|
||||
'started' => time(),
|
||||
'last_updated' => time(),
|
||||
),
|
||||
self::STATUS_TTL
|
||||
);
|
||||
|
||||
// Schedule immediate one-shot cron event. WordPress will fire this
|
||||
// on the next page load (or via wp-cron.php) in a separate PHP process
|
||||
// that is not subject to the 120-second connection timeout.
|
||||
if ( ! wp_next_scheduled( 'prautoblogger_manual_generation' ) ) {
|
||||
wp_schedule_single_event( time(), 'prautoblogger_manual_generation' );
|
||||
}
|
||||
|
||||
// Spawn the cron immediately via a non-blocking loopback request
|
||||
// so we don't depend on the next visitor to trigger it.
|
||||
spawn_cron();
|
||||
|
||||
// Direct non-blocking loopback to wp-cron.php — ensures the event
|
||||
// fires even if DISABLE_WP_CRON is true or spawn_cron() no-ops.
|
||||
wp_remote_post(
|
||||
site_url( 'wp-cron.php?doing_wp_cron=' . sprintf( '%.22F', microtime( true ) ) ),
|
||||
array(
|
||||
'timeout' => 0.01,
|
||||
'blocking' => false,
|
||||
'sslverify' => false,
|
||||
)
|
||||
);
|
||||
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'background' => true,
|
||||
'message' => __( 'Generation started in background. Polling for status...', 'prautoblogger' ),
|
||||
)
|
||||
);
|
||||
$this->poller()->on_ajax_generate_now();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -179,18 +99,18 @@ class PRAutoBlogger_Executor {
|
||||
|
||||
if ( ! PRAutoBlogger_Generation_Lock::acquire() ) {
|
||||
set_transient(
|
||||
self::STATUS_TRANSIENT,
|
||||
PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT,
|
||||
array(
|
||||
'status' => 'error',
|
||||
'message' => __( 'Could not acquire generation lock. Another run may be in progress.', 'prautoblogger' ),
|
||||
),
|
||||
self::STATUS_TTL
|
||||
PRAutoBlogger_Generation_Status_Poller::STATUS_TTL
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->update_generation_stage( __( 'Collecting sources from Reddit...', 'prautoblogger' ) );
|
||||
$this->poller()->update_generation_stage( __( 'Collecting sources from Reddit...', 'prautoblogger' ) );
|
||||
|
||||
$runner = ( new PRAutoBlogger_Pipeline_Runner() )->set_skip_dedup( true );
|
||||
$results = $runner->run();
|
||||
@@ -199,7 +119,7 @@ class PRAutoBlogger_Executor {
|
||||
// When articles ARE queued, the pipeline handles status + lock release.
|
||||
if ( ! get_option( 'prautoblogger_article_queue' ) ) {
|
||||
set_transient(
|
||||
self::STATUS_TRANSIENT,
|
||||
PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT,
|
||||
array(
|
||||
'status' => 'complete',
|
||||
'generated' => $results['generated'],
|
||||
@@ -207,7 +127,7 @@ class PRAutoBlogger_Executor {
|
||||
'rejected' => $results['rejected'],
|
||||
'cost' => $results['cost'],
|
||||
),
|
||||
self::STATUS_TTL
|
||||
PRAutoBlogger_Generation_Status_Poller::STATUS_TTL
|
||||
);
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
}
|
||||
@@ -217,12 +137,12 @@ class PRAutoBlogger_Executor {
|
||||
'pipeline'
|
||||
);
|
||||
set_transient(
|
||||
self::STATUS_TRANSIENT,
|
||||
PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT,
|
||||
array(
|
||||
'status' => 'error',
|
||||
'message' => $e->getMessage(),
|
||||
),
|
||||
self::STATUS_TTL
|
||||
PRAutoBlogger_Generation_Status_Poller::STATUS_TTL
|
||||
);
|
||||
$this->mark_current_run_failed();
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
@@ -247,89 +167,44 @@ class PRAutoBlogger_Executor {
|
||||
delete_option( 'prautoblogger_article_queue' );
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
set_transient(
|
||||
self::STATUS_TRANSIENT,
|
||||
PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT,
|
||||
array(
|
||||
'status' => 'error',
|
||||
'message' => $e->getMessage(),
|
||||
),
|
||||
self::STATUS_TTL
|
||||
PRAutoBlogger_Generation_Status_Poller::STATUS_TTL
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** AJAX: return generation status for frontend polling. Recovers orphaned runs. */
|
||||
/** AJAX: return generation status for frontend polling. Delegates to poller. */
|
||||
public function on_ajax_generation_status(): void {
|
||||
check_ajax_referer( 'prautoblogger_generate_now', 'nonce' );
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'prautoblogger' ) ), 403 );
|
||||
return;
|
||||
}
|
||||
|
||||
$status = get_transient( self::STATUS_TRANSIENT );
|
||||
if ( ! is_array( $status ) ) {
|
||||
wp_send_json_success( array( 'status' => 'idle' ) );
|
||||
return;
|
||||
}
|
||||
|
||||
if ( 'running' === $status['status'] ) {
|
||||
$elapsed = time() - ( $status['started'] ?? 0 );
|
||||
|
||||
// Absolute timeout — give up after 10 minutes.
|
||||
if ( $elapsed > self::STATUS_TTL ) {
|
||||
$this->abort_orphaned_run( __( 'Generation timed out. Check the Activity Log.', 'prautoblogger' ) );
|
||||
return;
|
||||
}
|
||||
|
||||
// After 90s, check if a queued job died and needs re-scheduling.
|
||||
if ( $elapsed > 90 && get_option( 'prautoblogger_article_queue' ) ) {
|
||||
if ( ! wp_next_scheduled( PRAutoBlogger_Pipeline_Runner::CRON_ACTION ) ) {
|
||||
wp_schedule_single_event( time(), PRAutoBlogger_Pipeline_Runner::CRON_ACTION );
|
||||
spawn_cron();
|
||||
}
|
||||
}
|
||||
|
||||
// Stall = 5 min since last stage update (not since start).
|
||||
$last_activity = $status['last_updated'] ?? $status['started'] ?? 0;
|
||||
$idle_seconds = time() - $last_activity;
|
||||
if ( $idle_seconds > 300 ) {
|
||||
$this->abort_orphaned_run( __( 'Generation stalled. Check Activity Log.', 'prautoblogger' ) );
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
wp_send_json_success( $status );
|
||||
}
|
||||
|
||||
/** Clean up an orphaned generation run and report error. */
|
||||
private function abort_orphaned_run( string $message ): void {
|
||||
// v0.18.0: the dead run renders as failed/"incomplete" in audit
|
||||
// queries instead of silently lingering as 'running'.
|
||||
$queue = get_option( 'prautoblogger_article_queue' );
|
||||
if ( is_array( $queue ) && ! empty( $queue['run_id'] ) ) {
|
||||
PRAutoBlogger_Run_State::mark_status( (string) $queue['run_id'], 'failed' );
|
||||
}
|
||||
delete_transient( self::STATUS_TRANSIENT );
|
||||
delete_option( 'prautoblogger_article_queue' );
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'status' => 'error',
|
||||
'message' => $message,
|
||||
)
|
||||
);
|
||||
$this->poller()->on_ajax_generation_status();
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: update the generation stage for frontend polling.
|
||||
* Lazy-load the generation status poller.
|
||||
*
|
||||
* @param string $stage Human-readable stage description.
|
||||
* @return PRAutoBlogger_Generation_Status_Poller
|
||||
*/
|
||||
private function update_generation_stage( string $stage ): void {
|
||||
$current = get_transient( self::STATUS_TRANSIENT );
|
||||
if ( is_array( $current ) ) {
|
||||
$current['stage'] = $stage;
|
||||
$current['last_updated'] = time();
|
||||
set_transient( self::STATUS_TRANSIENT, $current, self::STATUS_TTL );
|
||||
private function poller(): PRAutoBlogger_Generation_Status_Poller {
|
||||
if ( null === $this->poller ) {
|
||||
$this->poller = new PRAutoBlogger_Generation_Status_Poller();
|
||||
}
|
||||
return $this->poller;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark this process's run failed after a fatal pipeline error
|
||||
* (no-op outside a run; a governor-halted run stays halted — final
|
||||
* states are sticky).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function mark_current_run_failed(): void {
|
||||
$run_id = PRAutoBlogger_Run_Context::current_run_id();
|
||||
if ( null !== $run_id ) {
|
||||
PRAutoBlogger_Run_State::mark_status( $run_id, 'failed' );
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -76,6 +76,29 @@ class PRAutoBlogger_Generation_Lock {
|
||||
return null !== $row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Unix timestamp when the lock was acquired, or null if not held.
|
||||
*
|
||||
* Returns null when the lock is not set. The timestamp is the value written
|
||||
* by acquire() — used by the status poller to detect infrastructure-timeout
|
||||
* runs (lock held longer than STATUS_TTL → background PHP process died).
|
||||
*
|
||||
* @return int|null Unix timestamp, or null when the lock is absent.
|
||||
*/
|
||||
public static function get_acquired_at(): ?int {
|
||||
global $wpdb;
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
$row = $wpdb->get_var(
|
||||
$wpdb->prepare(
|
||||
"SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
|
||||
self::LOCK_NAME
|
||||
)
|
||||
);
|
||||
|
||||
return null !== $row ? (int) $row : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Release the generation mutex.
|
||||
*
|
||||
|
||||
260
includes/class-generation-status-poller.php
Normal file
260
includes/class-generation-status-poller.php
Normal file
@@ -0,0 +1,260 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
|
||||
*
|
||||
* AJAX handlers for "Generate Now" + status polling.
|
||||
*
|
||||
* What: Two AJAX endpoints: kick-off (fire-and-forget cron spawn) and the
|
||||
* status poll that drives the admin UI spinner. Extracted from
|
||||
* PRAutoBlogger_Executor in v0.18.3 to keep each file under 300 lines.
|
||||
*
|
||||
* R2/R3 resilience (v0.18.3):
|
||||
* - R2(a): on_ajax_generate_now() renews the transient with the
|
||||
* full STATUS_TTL on every stage update via update_generation_stage().
|
||||
* - R2(b): on_ajax_generation_status() detects lock-held-but-transient-gone
|
||||
* when the lock has been held > STATUS_TTL seconds (Hostinger background-
|
||||
* process death); marks the stuck run failed + surfaces a human-readable
|
||||
* "infrastructure timeout" message for the Activity Log.
|
||||
* - R3: on_ajax_generation_status() returns status:running (with
|
||||
* started_at) when the transient is absent but the lock IS held and
|
||||
* within TTL — so the button reflects reality during long runs rather
|
||||
* than silently resetting to idle.
|
||||
*
|
||||
* Who calls it: PRAutoBlogger hook registration (wp_ajax_prautoblogger_*).
|
||||
* Dependencies: PRAutoBlogger_Generation_Lock, PRAutoBlogger_Run_State,
|
||||
* PRAutoBlogger_Run_Context, PRAutoBlogger_Pipeline_Runner,
|
||||
* PRAutoBlogger_Logger.
|
||||
*
|
||||
* @see class-executor.php — Cron handlers (daily, manual, queued).
|
||||
* @see class-generation-lock.php — DB mutex (acquire/release/timestamps).
|
||||
* @see core/class-pipeline-status.php — Transient broadcast helpers.
|
||||
* @see ARCHITECTURE.md #21 — Run lifecycle and reaper design.
|
||||
*/
|
||||
class PRAutoBlogger_Generation_Status_Poller {
|
||||
|
||||
/** Transient key for background generation status (shared with Pipeline_Status). */
|
||||
public const STATUS_TRANSIENT = 'prautoblogger_generation_status';
|
||||
|
||||
/**
|
||||
* How long (seconds) to keep the status transient readable.
|
||||
* Renewed on every stage transition so a long run doesn't expire it early.
|
||||
*/
|
||||
public const STATUS_TTL = 600;
|
||||
|
||||
/**
|
||||
* AJAX handler: kick off manual generation as a background cron job.
|
||||
*
|
||||
* Returns immediately so the browser never hits Hostinger's connection
|
||||
* timeout. The frontend polls on_ajax_generation_status() every few
|
||||
* seconds for progress and final results.
|
||||
*
|
||||
* Side effects: schedules a WP-Cron event, writes a status transient.
|
||||
*/
|
||||
public function on_ajax_generate_now(): void {
|
||||
check_ajax_referer( 'prautoblogger_generate_now', 'nonce' );
|
||||
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'prautoblogger' ) ), 403 );
|
||||
return;
|
||||
}
|
||||
|
||||
$force = isset( $_POST['force'] ) && '1' === $_POST['force'];
|
||||
if ( $force ) {
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
delete_transient( self::STATUS_TRANSIENT );
|
||||
}
|
||||
|
||||
// Check if a run is already in progress.
|
||||
$current = get_transient( self::STATUS_TRANSIENT );
|
||||
if ( is_array( $current ) && 'running' === ( $current['status'] ?? '' ) ) {
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'background' => true,
|
||||
'message' => __( 'Generation already in progress.', 'prautoblogger' ),
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Write initial "running" status for the frontend to poll.
|
||||
set_transient(
|
||||
self::STATUS_TRANSIENT,
|
||||
array(
|
||||
'status' => 'running',
|
||||
'stage' => __( 'Starting generation...', 'prautoblogger' ),
|
||||
'started' => time(),
|
||||
'last_updated' => time(),
|
||||
),
|
||||
self::STATUS_TTL
|
||||
);
|
||||
|
||||
// Schedule immediate one-shot cron event. WordPress will fire this
|
||||
// on the next page load (or via wp-cron.php) in a separate PHP process
|
||||
// not subject to the connection timeout.
|
||||
if ( ! wp_next_scheduled( 'prautoblogger_manual_generation' ) ) {
|
||||
wp_schedule_single_event( time(), 'prautoblogger_manual_generation' );
|
||||
}
|
||||
|
||||
// Spawn the cron immediately via a non-blocking loopback request
|
||||
// so we don't depend on the next visitor to trigger it.
|
||||
spawn_cron();
|
||||
|
||||
// Direct non-blocking loopback to wp-cron.php — ensures the event
|
||||
// fires even if DISABLE_WP_CRON is true or spawn_cron() no-ops.
|
||||
wp_remote_post(
|
||||
site_url( 'wp-cron.php?doing_wp_cron=' . sprintf( '%.22F', microtime( true ) ) ),
|
||||
array(
|
||||
'timeout' => 0.01,
|
||||
'blocking' => false,
|
||||
'sslverify' => false,
|
||||
)
|
||||
);
|
||||
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'background' => true,
|
||||
'message' => __( 'Generation started in background. Polling for status...', 'prautoblogger' ),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** AJAX: return generation status for frontend polling. Recovers orphaned runs. */
|
||||
public function on_ajax_generation_status(): void {
|
||||
check_ajax_referer( 'prautoblogger_generate_now', 'nonce' );
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'prautoblogger' ) ), 403 );
|
||||
return;
|
||||
}
|
||||
|
||||
$status = get_transient( self::STATUS_TRANSIENT );
|
||||
|
||||
// R2(b) + R3: transient is gone — check the lock before returning idle.
|
||||
if ( ! is_array( $status ) ) {
|
||||
$this->handle_missing_transient();
|
||||
return;
|
||||
}
|
||||
|
||||
if ( 'running' === $status['status'] ) {
|
||||
$elapsed = time() - ( $status['started'] ?? 0 );
|
||||
|
||||
// Absolute timeout — give up after STATUS_TTL.
|
||||
if ( $elapsed > self::STATUS_TTL ) {
|
||||
$this->abort_orphaned_run( __( 'Generation timed out. Check the Activity Log.', 'prautoblogger' ) );
|
||||
return;
|
||||
}
|
||||
|
||||
// After 90s, check if a queued job died and needs re-scheduling.
|
||||
if ( $elapsed > 90 && get_option( 'prautoblogger_article_queue' ) ) {
|
||||
if ( ! wp_next_scheduled( PRAutoBlogger_Pipeline_Runner::CRON_ACTION ) ) {
|
||||
wp_schedule_single_event( time(), PRAutoBlogger_Pipeline_Runner::CRON_ACTION );
|
||||
spawn_cron();
|
||||
}
|
||||
}
|
||||
|
||||
// Stall = 5 min since last stage update (not since start).
|
||||
$last_activity = $status['last_updated'] ?? $status['started'] ?? 0;
|
||||
$idle_seconds = time() - $last_activity;
|
||||
if ( $idle_seconds > 300 ) {
|
||||
$this->abort_orphaned_run( __( 'Generation stalled. Check Activity Log.', 'prautoblogger' ) );
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
wp_send_json_success( $status );
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the case where the status transient is absent.
|
||||
*
|
||||
* R3: if lock is HELD and within TTL → return status:running so the
|
||||
* button reflects reality during long background runs.
|
||||
* R2(b): if lock is held but has been held > STATUS_TTL → the background
|
||||
* PHP process died without releasing it; mark the run failed and
|
||||
* surface "infrastructure timeout" to the UI.
|
||||
*
|
||||
* @return void Sends JSON and exits.
|
||||
*/
|
||||
private function handle_missing_transient(): void {
|
||||
$acquired_at = PRAutoBlogger_Generation_Lock::get_acquired_at();
|
||||
|
||||
if ( null === $acquired_at ) {
|
||||
// Lock not held — genuinely idle.
|
||||
wp_send_json_success( array( 'status' => 'idle' ) );
|
||||
return;
|
||||
}
|
||||
|
||||
$lock_age = time() - $acquired_at;
|
||||
|
||||
if ( $lock_age > self::STATUS_TTL ) {
|
||||
// Lock held longer than STATUS_TTL: background process died.
|
||||
// R2(b): mark the stuck run failed + surface a clear error.
|
||||
PRAutoBlogger_Logger::instance()->warning(
|
||||
sprintf(
|
||||
'Status transient absent and lock held for %ds (> %ds TTL) — background process died; marking run failed.',
|
||||
$lock_age,
|
||||
self::STATUS_TTL
|
||||
),
|
||||
'pipeline'
|
||||
);
|
||||
$this->abort_orphaned_run(
|
||||
__( 'Generation failed — infrastructure timeout. Check Activity Log for details.', 'prautoblogger' )
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// R3: lock is fresh (within TTL) but transient is gone — long run in
|
||||
// progress (pipeline broadcast hasn't fired yet, or transient was
|
||||
// evicted by object-cache pressure). Return running so the button
|
||||
// does not silently reset to idle.
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'status' => 'running',
|
||||
'stage' => __( 'Generation in progress (background). Check Activity Log for details.', 'prautoblogger' ),
|
||||
'started' => $acquired_at,
|
||||
'last_updated' => $acquired_at,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/** Clean up an orphaned generation run and report error. */
|
||||
private function abort_orphaned_run( string $message ): void {
|
||||
// Mark the stuck run as failed in the audit ledger.
|
||||
$queue = get_option( 'prautoblogger_article_queue' );
|
||||
if ( is_array( $queue ) && ! empty( $queue['run_id'] ) ) {
|
||||
PRAutoBlogger_Run_State::mark_status( (string) $queue['run_id'], 'failed' );
|
||||
}
|
||||
// Also attempt to close the current active run from Run_Context.
|
||||
$run_id = PRAutoBlogger_Run_Context::current_run_id();
|
||||
if ( null !== $run_id ) {
|
||||
PRAutoBlogger_Run_State::mark_status( $run_id, 'failed' );
|
||||
}
|
||||
delete_transient( self::STATUS_TRANSIENT );
|
||||
delete_option( 'prautoblogger_article_queue' );
|
||||
PRAutoBlogger_Generation_Lock::release();
|
||||
wp_send_json_success(
|
||||
array(
|
||||
'status' => 'error',
|
||||
'message' => $message,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the generation stage text for frontend polling.
|
||||
* Renews the transient TTL at every call so a long run doesn't expire it.
|
||||
*
|
||||
* @param string $stage Human-readable stage description.
|
||||
*/
|
||||
public function update_generation_stage( string $stage ): void {
|
||||
$current = get_transient( self::STATUS_TRANSIENT );
|
||||
if ( is_array( $current ) ) {
|
||||
$current['stage'] = $stage;
|
||||
$current['last_updated'] = time();
|
||||
// R2(a): renew the TTL on every stage update so the transient
|
||||
// outlives any single LLM call (STATUS_TTL from last activity).
|
||||
set_transient( self::STATUS_TRANSIENT, $current, self::STATUS_TTL );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,9 +76,9 @@ class PRAutoBlogger_Analysis_Prompts {
|
||||
global $wpdb;
|
||||
$scores_table = $wpdb->prefix . 'prautoblogger_content_scores';
|
||||
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$top_posts = $wpdb->get_results(
|
||||
"SELECT cs.post_id, cs.composite_score, p.post_title // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
"SELECT cs.post_id, cs.composite_score, p.post_title
|
||||
FROM {$scores_table} cs
|
||||
JOIN {$wpdb->posts} p ON p.ID = cs.post_id
|
||||
WHERE cs.composite_score > 0
|
||||
|
||||
@@ -108,8 +108,8 @@ class PRAutoBlogger_Post_Assembler {
|
||||
// Find the unlinked research cost row for this run.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
|
||||
$research_row = $wpdb->get_row(
|
||||
$wpdb->prepare(
|
||||
"SELECT id, estimated_cost, provider, model, prompt_tokens, completion_tokens // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
"SELECT id, estimated_cost, provider, model, prompt_tokens, completion_tokens
|
||||
FROM {$table}
|
||||
WHERE run_id = %s AND stage = 'llm_research' AND post_id IS NULL
|
||||
LIMIT 1",
|
||||
|
||||
211
includes/providers/class-runware-catalog-fetcher.php
Normal file
211
includes/providers/class-runware-catalog-fetcher.php
Normal file
@@ -0,0 +1,211 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
|
||||
*
|
||||
* Runware modelSearch API fetcher — handles pagination and response normalization
|
||||
* for the Runware model catalog sync.
|
||||
*
|
||||
* Extracted from PRAutoBlogger_Runware_Model_Catalog for the 300-line rule.
|
||||
* Provides two public methods consumed by the catalog class:
|
||||
* - fetch_all_text_to_image(): paginates modelSearch and returns raw results.
|
||||
* - normalize_models(): converts raw results to Image_Model_Registry shape.
|
||||
*
|
||||
* API note (2026-06-12): Runware retired taskType:models. The replacement is
|
||||
* taskType:modelSearch — requires auth+modelSearch tasks, returns paginated
|
||||
* results with `air` identifiers and `capabilities[]`. Text-to-image filtering
|
||||
* is client-side (no server-side capability filter is available). The catalog
|
||||
* has 320k+ entries (mostly community checkpoints); we cap at PAGE_CAP pages
|
||||
* of PAGE_SIZE results to bound request cost while covering curated t2i models.
|
||||
*
|
||||
* @see class-runware-model-catalog.php — Caller; owns caching, cooldown, and fallback.
|
||||
* @see class-image-model-registry.php — Consumes the normalized model shape.
|
||||
*/
|
||||
class PRAutoBlogger_Runware_Catalog_Fetcher {
|
||||
|
||||
private const RUNWARE_API_URL = 'https://api.runware.ai/v1';
|
||||
private const HTTP_TIMEOUT_SEC = 30;
|
||||
|
||||
/**
|
||||
* Maximum pages to fetch per sync cycle.
|
||||
* 5 pages × 100 results = 500 models inspected.
|
||||
* Curated Runware-native text-to-image models number ~50 in the first 500.
|
||||
*/
|
||||
private const PAGE_CAP = 5;
|
||||
private const PAGE_SIZE = 100;
|
||||
|
||||
/**
|
||||
* Fetch all text-to-image model results via paginated modelSearch calls.
|
||||
*
|
||||
* Issues up to PAGE_CAP requests against the Runware /v1 endpoint, each
|
||||
* sending an auth task + a modelSearch task with offset/limit. Stops early
|
||||
* when all available results have been fetched. Returns the raw result
|
||||
* objects (unfiltered — normalize_models() applies the capability filter).
|
||||
*
|
||||
* @param string $api_key Decrypted Runware API key.
|
||||
* @return array<int, array<string, mixed>> Raw modelSearch result objects.
|
||||
* @throws \RuntimeException On HTTP error or malformed response for any page.
|
||||
*/
|
||||
public function fetch_all_text_to_image( string $api_key ): array {
|
||||
$all_results = array();
|
||||
$offset = 0;
|
||||
$pages_fetched = 0;
|
||||
$total = PHP_INT_MAX; // Set after first page.
|
||||
|
||||
do {
|
||||
$page = $this->fetch_page( $api_key, $offset, self::PAGE_SIZE );
|
||||
if ( empty( $page['results'] ) ) {
|
||||
break;
|
||||
}
|
||||
|
||||
$all_results = array_merge( $all_results, $page['results'] );
|
||||
$total = (int) $page['totalResults'];
|
||||
$offset += self::PAGE_SIZE;
|
||||
++$pages_fetched;
|
||||
|
||||
if ( count( $all_results ) >= $total ) {
|
||||
break;
|
||||
}
|
||||
} while ( $pages_fetched < self::PAGE_CAP );
|
||||
|
||||
if ( $pages_fetched >= self::PAGE_CAP && count( $all_results ) < $total ) {
|
||||
PRAutoBlogger_Logger::instance()->info(
|
||||
sprintf(
|
||||
'Runware catalog: reached page cap (%d pages, %d models fetched of %d total). '
|
||||
. 'Increase PAGE_CAP if curated models are being missed.',
|
||||
self::PAGE_CAP,
|
||||
count( $all_results ),
|
||||
$total
|
||||
),
|
||||
'runware-catalog'
|
||||
);
|
||||
}
|
||||
|
||||
return $all_results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize raw modelSearch result objects to the Image_Model_Registry shape.
|
||||
*
|
||||
* Filters to models with "io:text-to-image" in capabilities[].
|
||||
* Uses the `air` field as the model id (e.g. "runware:100@1").
|
||||
* Uses the `comment` field as the human-readable description.
|
||||
* cost_per_image is always null here — merged by the catalog class.
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $raw_models Raw modelSearch results.
|
||||
* @return array<int, array<string, mixed>> Normalized models.
|
||||
*/
|
||||
public function normalize_models( array $raw_models ): array {
|
||||
$normalized = array();
|
||||
|
||||
foreach ( $raw_models as $raw ) {
|
||||
if ( ! is_array( $raw ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$capabilities = is_array( $raw['capabilities'] ?? null ) ? $raw['capabilities'] : array();
|
||||
if ( ! in_array( 'io:text-to-image', $capabilities, true ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$air = (string) ( $raw['air'] ?? '' );
|
||||
if ( '' === $air ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized[] = array(
|
||||
'id' => $air,
|
||||
'name' => (string) ( $raw['name'] ?? $air ),
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => null,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => (string) ( $raw['comment'] ?? '' ),
|
||||
);
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a single page of modelSearch results.
|
||||
*
|
||||
* Sends [authentication, modelSearch] task pair to /v1.
|
||||
* A fresh auth task is required per request per Runware's WebSocket-based
|
||||
* API contract (each HTTP POST is a stateless task array).
|
||||
*
|
||||
* @param string $api_key Decrypted Runware API key.
|
||||
* @param int $offset Pagination offset (0-based).
|
||||
* @param int $limit Page size.
|
||||
* @return array{results: array<int, array<string, mixed>>, totalResults: int}
|
||||
* @throws \RuntimeException On HTTP error or malformed response.
|
||||
*/
|
||||
private function fetch_page( string $api_key, int $offset, int $limit ): array {
|
||||
$payload = array(
|
||||
array(
|
||||
'taskType' => 'authentication',
|
||||
'apiKey' => $api_key,
|
||||
),
|
||||
array(
|
||||
'taskType' => 'modelSearch',
|
||||
'taskUUID' => wp_generate_uuid4(),
|
||||
'offset' => $offset,
|
||||
'limit' => $limit,
|
||||
),
|
||||
);
|
||||
|
||||
$response = wp_remote_post(
|
||||
self::RUNWARE_API_URL,
|
||||
array(
|
||||
'timeout' => self::HTTP_TIMEOUT_SEC,
|
||||
'headers' => array( 'Content-Type' => 'application/json' ),
|
||||
'body' => wp_json_encode( $payload ),
|
||||
)
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
throw new \RuntimeException(
|
||||
sprintf( 'Runware modelSearch unreachable: %s', $response->get_error_message() )
|
||||
);
|
||||
}
|
||||
|
||||
$status = (int) wp_remote_retrieve_response_code( $response );
|
||||
if ( 200 !== $status ) {
|
||||
throw new \RuntimeException(
|
||||
sprintf( 'Runware modelSearch returned HTTP %d', $status )
|
||||
);
|
||||
}
|
||||
|
||||
$raw = (string) wp_remote_retrieve_body( $response );
|
||||
$decoded = json_decode( $raw, true );
|
||||
|
||||
if ( ! is_array( $decoded ) ) {
|
||||
throw new \RuntimeException( 'Runware modelSearch response is not valid JSON.' );
|
||||
}
|
||||
|
||||
if ( isset( $decoded['errors'] ) && is_array( $decoded['errors'] ) && ! empty( $decoded['errors'] ) ) {
|
||||
$first_msg = '';
|
||||
if ( ! empty( $decoded['errors'][0]['message'] ) ) {
|
||||
$first_msg = ': ' . (string) $decoded['errors'][0]['message'];
|
||||
}
|
||||
throw new \RuntimeException( 'Runware modelSearch API error' . $first_msg );
|
||||
}
|
||||
|
||||
$data = $decoded['data'] ?? array();
|
||||
if ( ! is_array( $data ) || empty( $data ) ) {
|
||||
return array(
|
||||
'results' => array(),
|
||||
'totalResults' => 0,
|
||||
);
|
||||
}
|
||||
|
||||
$item = $data[0];
|
||||
$results = is_array( $item['results'] ?? null ) ? $item['results'] : array();
|
||||
$total = isset( $item['totalResults'] ) ? (int) $item['totalResults'] : 0;
|
||||
|
||||
return array(
|
||||
'results' => $results,
|
||||
'totalResults' => $total,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -4,18 +4,30 @@ declare(strict_types=1);
|
||||
/**
|
||||
* phpcs:ignore WordPress.Files.FileName.InvalidClassFileName -- class naming convention differs from WordPress standard
|
||||
*
|
||||
* Runware model catalog sync — fetches live model list via Runware's /v1 endpoint,
|
||||
* filters to text-to-image tasks, caches normalized results, and falls back to
|
||||
* hardcoded list on API failure.
|
||||
* Runware model catalog sync — orchestrates periodic fetching, caching, failure
|
||||
* cooldown, and fallback for the Runware model list.
|
||||
*
|
||||
* What: Syncs Runware's model catalog periodically (daily cron + on-demand AJAX),
|
||||
* caches the results in WP options, and merges pricing data from the pricing
|
||||
* class when Runware's API doesn't expose it.
|
||||
* What: Syncs Runware's model catalog (daily cron + on-demand AJAX), caches
|
||||
* normalized results in WP options (v2 schema key — see below), merges
|
||||
* pricing, and enforces a per-failure cooldown to stop admin-page-load
|
||||
* cascades when the API is broken or the key is misconfigured.
|
||||
* Who triggers it: Daily cron (prautoblogger_sync_runware_models), AJAX "Sync now"
|
||||
* button in PRAdmin, and lazy-load via PRAutoBlogger_Image_Model_Registry.
|
||||
* Dependencies: PRAutoBlogger_Logger, PRAutoBlogger_Runware_Image_Pricing,
|
||||
* PRAutoBlogger_Image_Model_Registry.
|
||||
* Dependencies: PRAutoBlogger_Runware_Catalog_Fetcher, PRAutoBlogger_Logger,
|
||||
* PRAutoBlogger_Runware_Image_Pricing, PRAutoBlogger_Image_Model_Registry.
|
||||
*
|
||||
* Cache schema note: option key is prautoblogger_runware_model_cache_v2 (bumped
|
||||
* from v1) to cleanly invalidate cached rows that used the old taskType:models
|
||||
* response shape (taskType/requiresImage fields). The v1 option is left in place
|
||||
* and will be purged by the next WP options cleanup pass.
|
||||
*
|
||||
* Failure cooldown: prautoblogger_runware_catalog_last_failure_at records the
|
||||
* last failure timestamp. is_in_failure_cooldown() checks it against
|
||||
* prautoblogger_runware_catalog_failure_cooldown_seconds (default 3600s). This
|
||||
* caps errors from admin page loads to ~24/day (24h / 1h cooldown) rather than
|
||||
* 40+/day from every Settings/picker page load triggering a live sync.
|
||||
*
|
||||
* @see class-runware-catalog-fetcher.php — Pagination + normalize (extracted for 300-line rule).
|
||||
* @see class-runware-image-pricing.php — Authoritative pricing source & fallback models.
|
||||
* @see admin/class-image-model-registry.php — Caller; merges Runware + OpenRouter lists.
|
||||
* @see class-prautoblogger.php — Registers daily cron + AJAX hook.
|
||||
@@ -23,20 +35,27 @@ declare(strict_types=1);
|
||||
*/
|
||||
class PRAutoBlogger_Runware_Model_Catalog {
|
||||
|
||||
private const RUNWARE_API_URL = 'https://api.runware.ai/v1';
|
||||
private const CACHE_TTL_SECONDS = 86400;
|
||||
private const HTTP_TIMEOUT_SECONDS = 30;
|
||||
|
||||
/**
|
||||
* Fetch the Runware model catalog, normalize to the Image_Model_Registry
|
||||
* shape, and write to WP options cache. Returns true on success, false on
|
||||
* API failure or parse error.
|
||||
* Option key for the v2 normalized model cache (air-identifier schema).
|
||||
* Bumped from v1 (prautoblogger_runware_model_cache) to force re-sync.
|
||||
*/
|
||||
private const CACHE_OPTION = 'prautoblogger_runware_model_cache_v2';
|
||||
private const CACHE_TS_OPTION = 'prautoblogger_runware_model_cache_updated_at';
|
||||
private const FAILURE_TS_OPTION = 'prautoblogger_runware_catalog_last_failure_at';
|
||||
private const COOLDOWN_SETTING = 'prautoblogger_runware_catalog_failure_cooldown_seconds';
|
||||
private const COOLDOWN_DEFAULT = 3600;
|
||||
|
||||
/**
|
||||
* Fetch, normalize, merge pricing, and cache the Runware model catalog.
|
||||
* On success: writes cache + clears failure timestamp. Returns true.
|
||||
* On failure: writes failure timestamp for cooldown. Returns false.
|
||||
*
|
||||
* Side effects: makes HTTP request to Runware API, writes WP options.
|
||||
* Error handling: logs via PRAutoBlogger_Logger, never throws, always
|
||||
* returns bool to allow fallback to cached list.
|
||||
* returns bool to allow fallback to cached/hardcoded list.
|
||||
*
|
||||
* @return bool True on successful fetch and cache update; false on API or parse error.
|
||||
* @return bool True on successful fetch and cache update; false otherwise.
|
||||
*/
|
||||
public function sync(): bool {
|
||||
try {
|
||||
@@ -49,16 +68,19 @@ class PRAutoBlogger_Runware_Model_Catalog {
|
||||
return false;
|
||||
}
|
||||
|
||||
$raw_models = $this->fetch_models_from_api( $api_key );
|
||||
$fetcher = new PRAutoBlogger_Runware_Catalog_Fetcher();
|
||||
$raw_models = $fetcher->fetch_all_text_to_image( $api_key );
|
||||
|
||||
if ( empty( $raw_models ) ) {
|
||||
PRAutoBlogger_Logger::instance()->warning(
|
||||
'Runware model catalog fetch returned empty list. Using cached/fallback models.',
|
||||
'runware-catalog'
|
||||
);
|
||||
$this->record_failure();
|
||||
return false;
|
||||
}
|
||||
|
||||
$normalized = $this->normalize_models( $raw_models );
|
||||
$normalized = $fetcher->normalize_models( $raw_models );
|
||||
$with_pricing = $this->merge_pricing( $normalized );
|
||||
|
||||
if ( empty( $with_pricing ) ) {
|
||||
@@ -66,11 +88,13 @@ class PRAutoBlogger_Runware_Model_Catalog {
|
||||
'Runware model catalog normalization resulted in empty list. Using cached/fallback models.',
|
||||
'runware-catalog'
|
||||
);
|
||||
$this->record_failure();
|
||||
return false;
|
||||
}
|
||||
|
||||
update_option( 'prautoblogger_runware_model_cache', $with_pricing, false );
|
||||
update_option( 'prautoblogger_runware_model_cache_updated_at', time(), false );
|
||||
update_option( self::CACHE_OPTION, $with_pricing, false );
|
||||
update_option( self::CACHE_TS_OPTION, time(), false );
|
||||
delete_option( self::FAILURE_TS_OPTION );
|
||||
|
||||
PRAutoBlogger_Logger::instance()->info(
|
||||
sprintf( 'Runware model catalog synced: %d models cached.', count( $with_pricing ) ),
|
||||
@@ -82,38 +106,37 @@ class PRAutoBlogger_Runware_Model_Catalog {
|
||||
sprintf( 'Runware model catalog sync failed: %s (%s)', $e->getMessage(), get_class( $e ) ),
|
||||
'runware-catalog'
|
||||
);
|
||||
$this->record_failure();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the normalized model list, with smart caching logic:
|
||||
* - If cache is fresh (< 24h), return it.
|
||||
* - If cache is stale or absent, trigger a sync.
|
||||
* - If sync fails, return the last-known-good cache.
|
||||
* - If no cache exists, return the hardcoded fallback (never empty).
|
||||
* Return the normalized model list, using smart cache + fallback logic:
|
||||
* fresh cache → cached; stale + not in cooldown → sync; stale cache fallback;
|
||||
* no cache → hardcoded fallback (never empty).
|
||||
*
|
||||
* @return array<int, array<string, mixed>> Normalized model list.
|
||||
*/
|
||||
public function get_models(): array {
|
||||
if ( ! $this->is_stale() ) {
|
||||
$cached = get_option( 'prautoblogger_runware_model_cache', array() );
|
||||
$cached = get_option( self::CACHE_OPTION, array() );
|
||||
if ( is_array( $cached ) && ! empty( $cached ) ) {
|
||||
return $cached;
|
||||
}
|
||||
}
|
||||
|
||||
if ( $this->sync() ) {
|
||||
$cached = get_option( 'prautoblogger_runware_model_cache', array() );
|
||||
if ( ! $this->is_in_failure_cooldown() && $this->sync() ) {
|
||||
$cached = get_option( self::CACHE_OPTION, array() );
|
||||
if ( is_array( $cached ) && ! empty( $cached ) ) {
|
||||
return $cached;
|
||||
}
|
||||
}
|
||||
|
||||
$cached = get_option( 'prautoblogger_runware_model_cache', array() );
|
||||
$cached = get_option( self::CACHE_OPTION, array() );
|
||||
if ( is_array( $cached ) && ! empty( $cached ) ) {
|
||||
PRAutoBlogger_Logger::instance()->info(
|
||||
'Using stale Runware model cache (live sync failed).',
|
||||
'Using stale Runware model cache (live sync failed or suppressed by cooldown).',
|
||||
'runware-catalog'
|
||||
);
|
||||
return $cached;
|
||||
@@ -131,12 +154,12 @@ class PRAutoBlogger_Runware_Model_Catalog {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the Unix timestamp of the last successful sync, or null if never synced.
|
||||
* Unix timestamp of the last successful sync, or null if never synced.
|
||||
*
|
||||
* @return int|null Unix timestamp, or null if never synced.
|
||||
* @return int|null
|
||||
*/
|
||||
public function get_last_synced_at(): ?int {
|
||||
$ts = get_option( 'prautoblogger_runware_model_cache_updated_at', null );
|
||||
$ts = get_option( self::CACHE_TS_OPTION, null );
|
||||
if ( null === $ts ) {
|
||||
return null;
|
||||
}
|
||||
@@ -145,9 +168,23 @@ class PRAutoBlogger_Runware_Model_Catalog {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the cache is stale (older than 24h) or absent.
|
||||
* Unix timestamp of the last sync failure, or null if no failure on record.
|
||||
*
|
||||
* @return bool True if cache should be refreshed; false if still fresh.
|
||||
* @return int|null
|
||||
*/
|
||||
public function get_last_failure_at(): ?int {
|
||||
$ts = get_option( self::FAILURE_TS_OPTION, null );
|
||||
if ( null === $ts ) {
|
||||
return null;
|
||||
}
|
||||
$ts = (int) $ts;
|
||||
return $ts > 0 ? $ts : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the cache is stale (older than 24h) or absent.
|
||||
*
|
||||
* @return bool True if a refresh is warranted; false if still fresh.
|
||||
*/
|
||||
public function is_stale(): bool {
|
||||
$updated_at = $this->get_last_synced_at();
|
||||
@@ -158,125 +195,53 @@ class PRAutoBlogger_Runware_Model_Catalog {
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the raw model list from Runware's /v1 endpoint via a models task.
|
||||
* Whether a sync attempt should be suppressed due to a recent failure.
|
||||
*
|
||||
* @param string $api_key Decrypted Runware API key.
|
||||
* @return array Raw model list (may be empty).
|
||||
* @throws \RuntimeException On HTTP error or malformed response.
|
||||
* The cooldown window is read from prautoblogger_runware_catalog_failure_cooldown_seconds
|
||||
* (default 3600s). This prevents admin-page-load cascades (40+ errors/day)
|
||||
* when the API endpoint or key is broken. A successful sync clears it.
|
||||
*
|
||||
* @return bool True if a sync should be suppressed; false if retry is permitted.
|
||||
*/
|
||||
private function fetch_models_from_api( string $api_key ): array {
|
||||
$body = wp_json_encode(
|
||||
array(
|
||||
array(
|
||||
'taskType' => 'models',
|
||||
'apiKey' => $api_key,
|
||||
),
|
||||
)
|
||||
);
|
||||
|
||||
$response = wp_remote_post(
|
||||
self::RUNWARE_API_URL,
|
||||
array(
|
||||
'timeout' => self::HTTP_TIMEOUT_SECONDS,
|
||||
'headers' => array( 'Content-Type' => 'application/json' ),
|
||||
'body' => $body,
|
||||
)
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
throw new \RuntimeException(
|
||||
sprintf( 'Runware models endpoint unreachable: %s', $response->get_error_message() )
|
||||
);
|
||||
public function is_in_failure_cooldown(): bool {
|
||||
$last_failure = $this->get_last_failure_at();
|
||||
if ( null === $last_failure ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$status = (int) wp_remote_retrieve_response_code( $response );
|
||||
if ( 200 !== $status ) {
|
||||
$raw = wp_remote_retrieve_body( $response );
|
||||
throw new \RuntimeException(
|
||||
sprintf( 'Runware models endpoint returned HTTP %d', $status )
|
||||
);
|
||||
$cooldown = (int) get_option( self::COOLDOWN_SETTING, self::COOLDOWN_DEFAULT );
|
||||
if ( $cooldown <= 0 ) {
|
||||
$cooldown = self::COOLDOWN_DEFAULT;
|
||||
}
|
||||
|
||||
$raw = (string) wp_remote_retrieve_body( $response );
|
||||
$decoded = json_decode( $raw, true );
|
||||
|
||||
if ( ! is_array( $decoded ) ) {
|
||||
throw new \RuntimeException( 'Runware models response is not valid JSON.' );
|
||||
}
|
||||
|
||||
if ( isset( $decoded['errors'] ) && is_array( $decoded['errors'] ) && ! empty( $decoded['errors'] ) ) {
|
||||
throw new \RuntimeException( 'Runware API returned an error.' );
|
||||
}
|
||||
|
||||
$data = $decoded['data'] ?? array();
|
||||
return is_array( $data ) ? $data : array();
|
||||
return ( time() - $last_failure ) < $cooldown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize raw Runware model objects to the PRAutoBlogger_Image_Model_Registry
|
||||
* shape: id, name, provider, cost_per_image, capabilities, description.
|
||||
*
|
||||
* Filters to taskType='imageInference' (text-to-image only), excluding
|
||||
* inpainting (imageInference + requiresImage=true), img2img, video, upscalers.
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $raw_models Raw API response.
|
||||
* @return array<int, array<string, mixed>> Normalized models.
|
||||
*/
|
||||
private function normalize_models( array $raw_models ): array {
|
||||
$normalized = array();
|
||||
|
||||
foreach ( $raw_models as $raw ) {
|
||||
if ( ! is_array( $raw ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$task_type = $raw['taskType'] ?? '';
|
||||
if ( 'imageInference' !== $task_type ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ( isset( $raw['requiresImage'] ) && true === $raw['requiresImage'] ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$model_id = (string) ( $raw['id'] ?? '' );
|
||||
if ( '' === $model_id ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$normalized[] = array(
|
||||
'id' => $model_id,
|
||||
'name' => (string) ( $raw['name'] ?? $model_id ),
|
||||
'provider' => 'runware',
|
||||
'cost_per_image' => null,
|
||||
'capabilities' => array( 'image_generation' ),
|
||||
'description' => (string) ( $raw['description'] ?? '' ),
|
||||
);
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge pricing data from PRAutoBlogger_Runware_Image_Pricing into the
|
||||
* normalized catalog. Models without pricing data get cost_per_image=null.
|
||||
* Merge pricing from PRAutoBlogger_Runware_Image_Pricing into normalized models.
|
||||
* Models without a pricing entry get cost_per_image=null.
|
||||
*
|
||||
* @param array<int, array<string, mixed>> $normalized Normalized models.
|
||||
* @return array<int, array<string, mixed>> Models with pricing merged.
|
||||
*/
|
||||
private function merge_pricing( array $normalized ): array {
|
||||
$pricing_table = PRAutoBlogger_Runware_Image_Pricing::get_model_costs();
|
||||
|
||||
foreach ( $normalized as &$model ) {
|
||||
$model_id = $model['id'] ?? '';
|
||||
if ( isset( $pricing_table[ $model_id ] ) ) {
|
||||
$model['cost_per_image'] = (float) $pricing_table[ $model_id ];
|
||||
}
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
* Record the current time as the last sync failure timestamp.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function record_failure(): void {
|
||||
update_option( self::FAILURE_TS_OPTION, time(), false );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the decrypted Runware API key from settings.
|
||||
*
|
||||
@@ -287,12 +252,10 @@ class PRAutoBlogger_Runware_Model_Catalog {
|
||||
if ( '' === $stored ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ( PRAutoBlogger_Encryption::is_encrypted( $stored ) ) {
|
||||
$decrypted = PRAutoBlogger_Encryption::decrypt( $stored );
|
||||
return '' === $decrypted ? '' : $decrypted;
|
||||
}
|
||||
|
||||
return $stored;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
* Plugin Name: PRAutoBlogger
|
||||
* Plugin URI: https://peptiderepo.com/prautoblogger
|
||||
* Description: Monitors social media for trending topics, generates SEO-friendly blog posts using AI, and publishes them on a daily schedule with full cost tracking and self-improvement metrics.
|
||||
* Version: 0.18.2
|
||||
* Version: 0.18.3
|
||||
* Requires at least: 6.0
|
||||
* Requires PHP: 7.4
|
||||
* Author: PeptideRepo
|
||||
@@ -35,13 +35,18 @@ if ( ! defined( 'ABSPATH' ) ) {
|
||||
| Defined here so every file in the plugin can reference paths, versions,
|
||||
| and limits without magic strings.
|
||||
*/
|
||||
define( 'PRAUTOBLOGGER_VERSION', '0.18.2' );
|
||||
define( 'PRAUTOBLOGGER_VERSION', '0.18.3' );
|
||||
define( 'PRAUTOBLOGGER_DB_VERSION', '1.2.0' );
|
||||
define( 'PRAUTOBLOGGER_PLUGIN_FILE', __FILE__ );
|
||||
define( 'PRAUTOBLOGGER_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
|
||||
define( 'PRAUTOBLOGGER_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
|
||||
define( 'PRAUTOBLOGGER_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
|
||||
// API and retry limits — named constants instead of magic numbers.
|
||||
// SAFETY INVARIANT: API_TIMEOUT_SECONDS × MAX_RETRIES must stay < STATUS_TTL (600s,
|
||||
// defined in PRAutoBlogger_Generation_Status_Poller). The current product
|
||||
// (180s × 3 = 540s) leaves a 60s margin. If either constant is raised, verify the
|
||||
// inequality still holds — otherwise a fully-retrying LLM call can exhaust the
|
||||
// status transient TTL within a single stage and trigger a false orphan-run abort.
|
||||
define( 'PRAUTOBLOGGER_MAX_RETRIES', 3 );
|
||||
// Pipeline v2 Phase 1 (v0.18.0) defaults. Both are SETTINGS-backed at every
|
||||
// read site (prautoblogger_per_run_cost_ceiling_usd /
|
||||
|
||||
131
tests/fixtures/runware-model-search-page1.json
vendored
Normal file
131
tests/fixtures/runware-model-search-page1.json
vendored
Normal file
@@ -0,0 +1,131 @@
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"taskType": "modelSearch",
|
||||
"taskUUID": "aabbccdd-0000-0000-0000-000000000001",
|
||||
"totalResults": 5,
|
||||
"results": [
|
||||
{
|
||||
"air": "runware:100@1",
|
||||
"name": "FLUX.1 schnell",
|
||||
"nameContent": "FLUX.1 schnell",
|
||||
"comment": "Fast 4-step text-to-image model",
|
||||
"category": "checkpoint",
|
||||
"private": false,
|
||||
"capabilities": ["io:text-to-image", "form:checkpoint"],
|
||||
"tags": [],
|
||||
"heroImage": "",
|
||||
"version": "",
|
||||
"architecture": "",
|
||||
"nsfwLevel": null,
|
||||
"downloadCount": 0,
|
||||
"inferenceCount24h": 0,
|
||||
"rating": 0,
|
||||
"ratingCount": 0,
|
||||
"thumbsUpCount": 0,
|
||||
"thumbsDownCount": 0,
|
||||
"featured": 1,
|
||||
"addedUnixTimestamp": 0,
|
||||
"updatedDateUnixTimestamp": 0,
|
||||
"source": "curated"
|
||||
},
|
||||
{
|
||||
"air": "runware:101@1",
|
||||
"name": "FLUX.1 dev",
|
||||
"nameContent": "FLUX.1 dev",
|
||||
"comment": "High fidelity 28-step text-to-image model",
|
||||
"category": "checkpoint",
|
||||
"private": false,
|
||||
"capabilities": ["io:text-to-image", "form:checkpoint"],
|
||||
"tags": [],
|
||||
"heroImage": "",
|
||||
"version": "",
|
||||
"architecture": "",
|
||||
"nsfwLevel": null,
|
||||
"downloadCount": 0,
|
||||
"inferenceCount24h": 0,
|
||||
"rating": 0,
|
||||
"ratingCount": 0,
|
||||
"thumbsUpCount": 0,
|
||||
"thumbsDownCount": 0,
|
||||
"featured": 0,
|
||||
"addedUnixTimestamp": 0,
|
||||
"updatedDateUnixTimestamp": 0,
|
||||
"source": "curated"
|
||||
},
|
||||
{
|
||||
"air": "some-text-model:llm@1",
|
||||
"name": "Some Text LLM",
|
||||
"nameContent": "Some Text LLM",
|
||||
"comment": "A text-to-text model that should be excluded",
|
||||
"category": "text",
|
||||
"private": false,
|
||||
"capabilities": ["io:text-to-text", "form:checkpoint"],
|
||||
"tags": [],
|
||||
"heroImage": "",
|
||||
"version": "",
|
||||
"architecture": "",
|
||||
"nsfwLevel": null,
|
||||
"downloadCount": 0,
|
||||
"inferenceCount24h": 0,
|
||||
"rating": 0,
|
||||
"ratingCount": 0,
|
||||
"thumbsUpCount": 0,
|
||||
"thumbsDownCount": 0,
|
||||
"featured": 0,
|
||||
"addedUnixTimestamp": 0,
|
||||
"updatedDateUnixTimestamp": 0,
|
||||
"source": "curated"
|
||||
},
|
||||
{
|
||||
"air": "runware:400@2",
|
||||
"name": "FLUX.2 klein 9B",
|
||||
"nameContent": "FLUX.2 klein 9B",
|
||||
"comment": "Compact 9B text-to-image model",
|
||||
"category": "checkpoint",
|
||||
"private": false,
|
||||
"capabilities": ["io:text-to-image", "form:checkpoint"],
|
||||
"tags": [],
|
||||
"heroImage": "",
|
||||
"version": "",
|
||||
"architecture": "",
|
||||
"nsfwLevel": null,
|
||||
"downloadCount": 0,
|
||||
"inferenceCount24h": 0,
|
||||
"rating": 0,
|
||||
"ratingCount": 0,
|
||||
"thumbsUpCount": 0,
|
||||
"thumbsDownCount": 0,
|
||||
"featured": 0,
|
||||
"addedUnixTimestamp": 0,
|
||||
"updatedDateUnixTimestamp": 0,
|
||||
"source": "curated"
|
||||
},
|
||||
{
|
||||
"air": "upscale-model:upscaler@1",
|
||||
"name": "Upscale Model",
|
||||
"nameContent": "Upscale Model",
|
||||
"comment": "Image upscaler — should be excluded from t2i list",
|
||||
"category": "checkpoint",
|
||||
"private": false,
|
||||
"capabilities": ["io:image-to-image", "op:upscale", "form:checkpoint"],
|
||||
"tags": [],
|
||||
"heroImage": "",
|
||||
"version": "",
|
||||
"architecture": "",
|
||||
"nsfwLevel": null,
|
||||
"downloadCount": 0,
|
||||
"inferenceCount24h": 0,
|
||||
"rating": 0,
|
||||
"ratingCount": 0,
|
||||
"thumbsUpCount": 0,
|
||||
"thumbsDownCount": 0,
|
||||
"featured": 0,
|
||||
"addedUnixTimestamp": 0,
|
||||
"updatedDateUnixTimestamp": 0,
|
||||
"source": "curated"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
126
tests/unit/Core/AnalysisPromptsTest.php
Normal file
126
tests/unit/Core/AnalysisPromptsTest.php
Normal file
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Analysis_Prompts.
|
||||
*
|
||||
* Regression + behavioral coverage for the GA4 self-improvement loop:
|
||||
* - SQL passed to $wpdb->get_results() must not embed phpcs:ignore comments
|
||||
* (MariaDB rejects the query if it does).
|
||||
* - get_performance_context() returns a non-empty, correctly-shaped string
|
||||
* when seeded content_scores rows are present.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class AnalysisPromptsTest extends BaseTestCase {
|
||||
|
||||
/** @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb. */
|
||||
private $wpdb;
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
$this->wpdb = $this->create_mock_wpdb();
|
||||
// Analysis prompts uses $wpdb->posts (JOIN {->posts}) and prefix.
|
||||
$this->wpdb->posts = 'wp_posts';
|
||||
$GLOBALS['wpdb'] = $this->wpdb;
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression: get_performance_context() SQL must not embed phpcs:ignore
|
||||
* inside the string literal — MariaDB rejects the query if it does,
|
||||
* causing get_performance_context() to silently return '' on every run.
|
||||
*
|
||||
* @see includes/core/class-analysis-prompts.php — fixed in v0.18.3
|
||||
*/
|
||||
public function test_get_performance_context_sql_has_no_inline_phpcs_ignore(): void {
|
||||
$captured_sql = null;
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
function ( $sql ) use ( &$captured_sql ) {
|
||||
// get_results is called WITHOUT prepare (direct string interpolation
|
||||
// of a table prefix); capture the first arg to get_results instead.
|
||||
return $sql;
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'get_results' )->willReturnCallback(
|
||||
function ( $sql ) use ( &$captured_sql ) {
|
||||
$captured_sql = $sql;
|
||||
return array();
|
||||
}
|
||||
);
|
||||
|
||||
\PRAutoBlogger_Analysis_Prompts::get_performance_context();
|
||||
|
||||
$this->assertNotNull( $captured_sql, 'get_results() was not called' );
|
||||
$this->assertStringNotContainsString(
|
||||
'// phpcs:ignore',
|
||||
(string) $captured_sql,
|
||||
'SQL passed to get_results() must not contain a phpcs:ignore comment — MariaDB rejects it as a syntax error'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Behavioral: get_performance_context() returns a non-empty, correctly-shaped
|
||||
* string when the scores table contains rows with composite_score > 0.
|
||||
*
|
||||
* The returned string must:
|
||||
* - start with the "Top performing" header line
|
||||
* - contain at least one bullet entry of the form '- "…" (score: N.N)'
|
||||
* - not be empty
|
||||
*/
|
||||
public function test_get_performance_context_returns_shaped_context_with_seeded_rows(): void {
|
||||
// Simulate two content_scores rows returned from the DB query.
|
||||
$rows = array(
|
||||
array(
|
||||
'post_id' => 100,
|
||||
'composite_score' => '9.2',
|
||||
'post_title' => 'BPC-157 and Gut Healing — What the Research Shows',
|
||||
),
|
||||
array(
|
||||
'post_id' => 101,
|
||||
'composite_score' => '7.8',
|
||||
'post_title' => 'Semaglutide Dosing Guide for Weight Loss',
|
||||
),
|
||||
);
|
||||
|
||||
$this->wpdb->method( 'get_results' )->willReturn( $rows );
|
||||
|
||||
$context = \PRAutoBlogger_Analysis_Prompts::get_performance_context();
|
||||
|
||||
$this->assertNotEmpty( $context, 'get_performance_context() returned empty string with seeded rows' );
|
||||
$this->assertStringContainsString(
|
||||
'Top performing past articles',
|
||||
$context,
|
||||
'Context block must start with the header line'
|
||||
);
|
||||
$this->assertStringContainsString(
|
||||
'BPC-157 and Gut Healing',
|
||||
$context,
|
||||
'Context block must contain the first seeded article title'
|
||||
);
|
||||
$this->assertStringContainsString(
|
||||
'score: 9.2',
|
||||
$context,
|
||||
'Context block must include formatted composite_score'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Edge case: get_performance_context() returns '' when no rows exist.
|
||||
*/
|
||||
public function test_get_performance_context_returns_empty_string_when_no_rows(): void {
|
||||
$this->wpdb->method( 'get_results' )->willReturn( array() );
|
||||
|
||||
$context = \PRAutoBlogger_Analysis_Prompts::get_performance_context();
|
||||
|
||||
$this->assertSame( '', $context, 'get_performance_context() must return empty string when scores table is empty' );
|
||||
}
|
||||
}
|
||||
226
tests/unit/Core/GenerationStatusPollerTest.php
Normal file
226
tests/unit/Core/GenerationStatusPollerTest.php
Normal file
@@ -0,0 +1,226 @@
|
||||
<?php
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Generation_Status_Poller (R2/R3 resilience).
|
||||
*
|
||||
* Covers:
|
||||
* - R2(a): update_generation_stage() renews the transient TTL on every call.
|
||||
* - R2(b): on_ajax_generation_status() detects lock-held-but-transient-gone
|
||||
* when lock age > STATUS_TTL and returns status:error with an infrastructure
|
||||
* timeout message.
|
||||
* - R3: on_ajax_generation_status() returns status:running (with started_at)
|
||||
* when the transient is absent but the lock is held within TTL.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Core
|
||||
*/
|
||||
|
||||
namespace PRAutoBlogger\Tests\Core;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
|
||||
class GenerationStatusPollerTest extends BaseTestCase {
|
||||
|
||||
/** @var \PHPUnit\Framework\MockObject\MockObject Mock $wpdb. */
|
||||
private $wpdb;
|
||||
|
||||
/** @var array Captured wp_send_json_success payloads. */
|
||||
private array $json_success = array();
|
||||
|
||||
/** @var array Captured wp_send_json_error payloads. */
|
||||
private array $json_error = array();
|
||||
|
||||
/** @var array Captured transient writes: [key, value, ttl]. */
|
||||
private array $transient_writes = array();
|
||||
|
||||
/** @var mixed Current transient value. */
|
||||
private $transient_value = false;
|
||||
|
||||
/** @var int|null Mocked lock acquired_at timestamp (null = not held). */
|
||||
private ?int $lock_acquired_at = null;
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
|
||||
$this->json_success = array();
|
||||
$this->json_error = array();
|
||||
$this->transient_writes = array();
|
||||
$this->transient_value = false;
|
||||
$this->lock_acquired_at = null;
|
||||
|
||||
$this->wpdb = $this->create_mock_wpdb();
|
||||
// Generation_Lock uses $wpdb->options in acquire/release/get_acquired_at.
|
||||
$this->wpdb->options = 'wp_options';
|
||||
$GLOBALS['wpdb'] = $this->wpdb;
|
||||
|
||||
// Stub nonce check and capability check (always pass in unit tests).
|
||||
Functions\when( 'check_ajax_referer' )->justReturn( true );
|
||||
Functions\when( 'current_user_can' )->justReturn( true );
|
||||
|
||||
// Transient stubs.
|
||||
Functions\when( 'get_transient' )->alias( function( $key ) {
|
||||
return $this->transient_value;
|
||||
} );
|
||||
Functions\when( 'set_transient' )->alias( function( $key, $value, $ttl ) {
|
||||
$this->transient_writes[] = array( $key, $value, $ttl );
|
||||
return true;
|
||||
} );
|
||||
|
||||
// wp_send_json stubs — capture payload, mark test as "sent".
|
||||
Functions\when( 'wp_send_json_success' )->alias( function( $data ) {
|
||||
$this->json_success[] = $data;
|
||||
} );
|
||||
Functions\when( 'wp_send_json_error' )->alias( function( $data ) {
|
||||
$this->json_error[] = $data;
|
||||
} );
|
||||
|
||||
// Generation_Lock::get_acquired_at() — return our test value.
|
||||
// We stub the static method via $wpdb since it does a DB query.
|
||||
$this->wpdb->method( 'prepare' )->willReturnCallback(
|
||||
function ( $sql, ...$args ) {
|
||||
return $sql . ' /* ' . implode( ',', array_map( 'strval', $args ) ) . ' */';
|
||||
}
|
||||
);
|
||||
$this->wpdb->method( 'get_var' )->willReturnCallback(
|
||||
function ( $sql ) {
|
||||
// Return the lock timestamp when querying the lock option.
|
||||
if ( false !== strpos( (string) $sql, 'prautoblogger_generation_lock' ) ) {
|
||||
return null !== $this->lock_acquired_at ? (string) $this->lock_acquired_at : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
);
|
||||
|
||||
// Run_State and Run_Context stubs — no DB tables in unit tests.
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
Functions\when( 'get_option' )->justReturn( false );
|
||||
Functions\when( 'delete_option' )->justReturn( true );
|
||||
Functions\when( 'delete_transient' )->justReturn( true );
|
||||
|
||||
// Logger stub.
|
||||
Functions\when( 'wp_date' )->returnArg();
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
\PRAutoBlogger_Run_State::flush_cache();
|
||||
unset( $GLOBALS['wpdb'] );
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// R2(a): update_generation_stage() renews transient TTL
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* update_generation_stage() must renew the transient with STATUS_TTL on
|
||||
* every call so the transient outlasts a long LLM call.
|
||||
*/
|
||||
public function test_update_generation_stage_renews_transient_ttl(): void {
|
||||
// Seed an existing running transient.
|
||||
$this->transient_value = array(
|
||||
'status' => 'running',
|
||||
'stage' => 'old stage',
|
||||
'started' => time() - 30,
|
||||
'last_updated' => time() - 30,
|
||||
);
|
||||
|
||||
$poller = new \PRAutoBlogger_Generation_Status_Poller();
|
||||
$poller->update_generation_stage( 'Analyzing sources...' );
|
||||
|
||||
$this->assertCount( 1, $this->transient_writes, 'set_transient must be called once' );
|
||||
[ $key, $value, $ttl ] = $this->transient_writes[0];
|
||||
$this->assertSame( \PRAutoBlogger_Generation_Status_Poller::STATUS_TRANSIENT, $key );
|
||||
$this->assertSame( \PRAutoBlogger_Generation_Status_Poller::STATUS_TTL, $ttl,
|
||||
'TTL must be renewed to STATUS_TTL on every stage update' );
|
||||
$this->assertSame( 'Analyzing sources...', $value['stage'] );
|
||||
}
|
||||
|
||||
/**
|
||||
* update_generation_stage() is a no-op when the transient is absent
|
||||
* (prevents spurious "running" writes after a run has completed).
|
||||
*/
|
||||
public function test_update_generation_stage_no_op_when_transient_absent(): void {
|
||||
$this->transient_value = false; // absent.
|
||||
|
||||
$poller = new \PRAutoBlogger_Generation_Status_Poller();
|
||||
$poller->update_generation_stage( 'Stage text' );
|
||||
|
||||
$this->assertEmpty( $this->transient_writes, 'set_transient must NOT be called when transient is absent' );
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// R3: transient absent, lock held within TTL → return status:running
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* R3: When the status transient has expired but the lock is held within
|
||||
* STATUS_TTL, the poller must return status:running so the Generate Now
|
||||
* button does not silently reset to idle during long background runs.
|
||||
*/
|
||||
public function test_missing_transient_but_fresh_lock_returns_running(): void {
|
||||
$this->transient_value = false; // transient gone.
|
||||
$this->lock_acquired_at = time() - 60; // lock held 60s — well within TTL.
|
||||
|
||||
// Stub _POST for the nonce.
|
||||
$_POST = array( 'nonce' => 'fake' );
|
||||
$poller = new \PRAutoBlogger_Generation_Status_Poller();
|
||||
$poller->on_ajax_generation_status();
|
||||
|
||||
$this->assertCount( 1, $this->json_success, 'wp_send_json_success must be called once' );
|
||||
$response = $this->json_success[0];
|
||||
$this->assertSame( 'running', $response['status'],
|
||||
'R3: status must be running when transient absent but lock held within TTL' );
|
||||
$this->assertArrayHasKey( 'started', $response,
|
||||
'R3: response must include started timestamp from lock' );
|
||||
$this->assertSame( $this->lock_acquired_at, $response['started'],
|
||||
'R3: started must equal the lock acquired_at timestamp' );
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// R2(b): transient absent, lock held > STATUS_TTL → abort + status:error
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* R2(b): When the status transient is absent and the lock has been held
|
||||
* longer than STATUS_TTL, the poller must mark the run failed and return
|
||||
* status:error with an "infrastructure timeout" message.
|
||||
*/
|
||||
public function test_missing_transient_with_expired_lock_marks_failed_and_returns_error(): void {
|
||||
$this->transient_value = false;
|
||||
$ttl = \PRAutoBlogger_Generation_Status_Poller::STATUS_TTL;
|
||||
$this->lock_acquired_at = time() - ( $ttl + 60 ); // Lock held TTL+60s.
|
||||
|
||||
$_POST = array( 'nonce' => 'fake' );
|
||||
$poller = new \PRAutoBlogger_Generation_Status_Poller();
|
||||
$poller->on_ajax_generation_status();
|
||||
|
||||
$this->assertCount( 1, $this->json_success, 'wp_send_json_success must be called' );
|
||||
$response = $this->json_success[0];
|
||||
$this->assertSame( 'error', $response['status'],
|
||||
'R2(b): status must be error when lock is expired-stale' );
|
||||
$this->assertStringContainsString(
|
||||
'infrastructure timeout',
|
||||
strtolower( $response['message'] ?? '' ),
|
||||
'R2(b): error message must mention infrastructure timeout'
|
||||
);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Idle path: no transient, no lock
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* When both the transient and the lock are absent, the poller must
|
||||
* return status:idle (normal rest state between runs).
|
||||
*/
|
||||
public function test_no_transient_no_lock_returns_idle(): void {
|
||||
$this->transient_value = false;
|
||||
$this->lock_acquired_at = null; // no lock.
|
||||
|
||||
$_POST = array( 'nonce' => 'fake' );
|
||||
$poller = new \PRAutoBlogger_Generation_Status_Poller();
|
||||
$poller->on_ajax_generation_status();
|
||||
|
||||
$this->assertCount( 1, $this->json_success );
|
||||
$this->assertSame( 'idle', $this->json_success[0]['status'] );
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
/**
|
||||
* Tests for PRAutoBlogger_Runware_Model_Catalog.
|
||||
*
|
||||
* Validates live sync, fallback logic, cache staleness, and pricing merge.
|
||||
* Validates: normalize_models against real modelSearch fixture; cooldown behavior
|
||||
* (failure → no retry within window → retry after); fallback served when cache empty;
|
||||
* success path clears failure timestamp; cache version key v2 is used throughout.
|
||||
*
|
||||
* @package PRAutoBlogger\Tests\Providers
|
||||
*/
|
||||
@@ -11,47 +13,267 @@ namespace PRAutoBlogger\Tests\Providers;
|
||||
|
||||
use PRAutoBlogger\Tests\BaseTestCase;
|
||||
use Brain\Monkey\Functions;
|
||||
use Brain\Monkey\Actions;
|
||||
|
||||
class RunwareModelCatalogTest extends BaseTestCase {
|
||||
|
||||
/** Shared in-memory option store reset per test. */
|
||||
private array $options = array();
|
||||
|
||||
protected function setUp(): void {
|
||||
parent::setUp();
|
||||
// Mock WP options for cache simulation.
|
||||
Functions\when( 'get_option' )->alias( function ( $key, $default = false ) {
|
||||
static $options = array();
|
||||
return $options[ $key ] ?? $default;
|
||||
} );
|
||||
Functions\when( 'update_option' )->alias( function ( $key, $value ) {
|
||||
static $options = array();
|
||||
$options[ $key ] = $value;
|
||||
return true;
|
||||
} );
|
||||
Functions\when( 'time' )->justReturn( 1704067200 ); // 2024-01-01 00:00:00
|
||||
$this->options = array();
|
||||
$this->stub_options();
|
||||
}
|
||||
|
||||
/** Sync with empty or missing API key returns false. */
|
||||
public function test_sync_no_api_key(): void {
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
private function stub_options(): void {
|
||||
Functions\when( 'get_option' )->alias(
|
||||
function ( $key, $default = false ) {
|
||||
return $this->options[ $key ] ?? $default;
|
||||
}
|
||||
);
|
||||
Functions\when( 'update_option' )->alias(
|
||||
function ( $key, $value ) {
|
||||
$this->options[ $key ] = $value;
|
||||
return true;
|
||||
}
|
||||
);
|
||||
Functions\when( 'delete_option' )->alias(
|
||||
function ( $key ) {
|
||||
unset( $this->options[ $key ] );
|
||||
return true;
|
||||
}
|
||||
);
|
||||
Functions\when( 'time' )->justReturn( 1704067200 ); // 2024-01-01 00:00:00 UTC
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the fixture as a decoded page array matching fetch_page() output.
|
||||
*
|
||||
* @return array{results: array, totalResults: int}
|
||||
*/
|
||||
private function get_fixture_page(): array {
|
||||
$fixture_path = __DIR__ . '/../../fixtures/runware-model-search-page1.json';
|
||||
$json = file_get_contents( $fixture_path );
|
||||
$decoded = json_decode( $json, true );
|
||||
$item = $decoded['data'][0];
|
||||
return array(
|
||||
'results' => $item['results'],
|
||||
'totalResults' => $item['totalResults'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a fake HTTP response array for wp_remote_post stubs.
|
||||
*
|
||||
* @param int $status HTTP status code.
|
||||
* @param string $body Response body JSON.
|
||||
* @return array
|
||||
*/
|
||||
private function make_http_response( int $status, string $body ): array {
|
||||
return array(
|
||||
'response' => array( 'code' => $status ),
|
||||
'body' => $body,
|
||||
);
|
||||
}
|
||||
|
||||
private function stub_http_helpers(): void {
|
||||
Functions\when( 'wp_remote_retrieve_response_code' )->alias(
|
||||
function ( $r ) { return (int) ( $r['response']['code'] ?? 0 ); }
|
||||
);
|
||||
Functions\when( 'wp_remote_retrieve_body' )->alias(
|
||||
function ( $r ) { return (string) ( $r['body'] ?? '' ); }
|
||||
);
|
||||
Functions\when( 'is_wp_error' )->justReturn( false );
|
||||
}
|
||||
|
||||
// ── normalize_models tests (via Fetcher) ──────────────────────────────────
|
||||
|
||||
/**
|
||||
* normalize_models filters to io:text-to-image and maps air → id,
|
||||
* comment → description. Non-t2i models are excluded.
|
||||
*
|
||||
* Uses the real modelSearch fixture (3 t2i + 1 text LLM + 1 upscaler).
|
||||
* Expects only the 3 t2i models to pass through.
|
||||
*/
|
||||
public function test_normalize_models_filters_to_text_to_image(): void {
|
||||
$fixture = $this->get_fixture_page();
|
||||
$fetcher = new \PRAutoBlogger_Runware_Catalog_Fetcher();
|
||||
$result = $fetcher->normalize_models( $fixture['results'] );
|
||||
|
||||
// Fixture has 3 t2i models (runware:100@1, runware:101@1, runware:400@2)
|
||||
// and 2 non-t2i (text LLM + upscaler).
|
||||
$this->assertCount( 3, $result, 'Should include exactly 3 io:text-to-image models' );
|
||||
|
||||
$ids = array_column( $result, 'id' );
|
||||
$this->assertContains( 'runware:100@1', $ids );
|
||||
$this->assertContains( 'runware:101@1', $ids );
|
||||
$this->assertContains( 'runware:400@2', $ids );
|
||||
$this->assertNotContains( 'some-text-model:llm@1', $ids, 'Text LLM must be excluded' );
|
||||
$this->assertNotContains( 'upscale-model:upscaler@1', $ids, 'Upscaler must be excluded' );
|
||||
}
|
||||
|
||||
/** normalize_models uses air as id, name as name, comment as description. */
|
||||
public function test_normalize_models_maps_fields_correctly(): void {
|
||||
$fixture = $this->get_fixture_page();
|
||||
$fetcher = new \PRAutoBlogger_Runware_Catalog_Fetcher();
|
||||
$result = $fetcher->normalize_models( $fixture['results'] );
|
||||
|
||||
$schnell = null;
|
||||
foreach ( $result as $m ) {
|
||||
if ( 'runware:100@1' === $m['id'] ) {
|
||||
$schnell = $m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertNotNull( $schnell );
|
||||
$this->assertSame( 'runware:100@1', $schnell['id'] );
|
||||
$this->assertSame( 'FLUX.1 schnell', $schnell['name'] );
|
||||
$this->assertSame( 'runware', $schnell['provider'] );
|
||||
$this->assertNull( $schnell['cost_per_image'], 'Pricing is null before merge_pricing runs' );
|
||||
$this->assertSame( array( 'image_generation' ), $schnell['capabilities'] );
|
||||
$this->assertSame( 'Fast 4-step text-to-image model', $schnell['description'] );
|
||||
}
|
||||
|
||||
/** normalize_models skips entries with empty air field. */
|
||||
public function test_normalize_models_skips_empty_air(): void {
|
||||
$fetcher = new \PRAutoBlogger_Runware_Catalog_Fetcher();
|
||||
$raw = array(
|
||||
array(
|
||||
'air' => '',
|
||||
'name' => 'No Air Model',
|
||||
'capabilities' => array( 'io:text-to-image' ),
|
||||
'comment' => '',
|
||||
),
|
||||
array(
|
||||
'air' => 'runware:100@1',
|
||||
'name' => 'Valid',
|
||||
'capabilities' => array( 'io:text-to-image' ),
|
||||
'comment' => 'OK',
|
||||
),
|
||||
);
|
||||
|
||||
$result = $fetcher->normalize_models( $raw );
|
||||
$this->assertCount( 1, $result );
|
||||
$this->assertSame( 'runware:100@1', $result[0]['id'] );
|
||||
}
|
||||
|
||||
/** normalize_models returns empty array for empty input. */
|
||||
public function test_normalize_models_empty_input(): void {
|
||||
$fetcher = new \PRAutoBlogger_Runware_Catalog_Fetcher();
|
||||
$this->assertSame( array(), $fetcher->normalize_models( array() ) );
|
||||
}
|
||||
|
||||
// ── Failure cooldown tests ────────────────────────────────────────────────
|
||||
|
||||
/** No failure on record → is_in_failure_cooldown returns false. */
|
||||
public function test_no_failure_cooldown_when_no_failure_recorded(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$result = $catalog->sync();
|
||||
$this->assertFalse( $catalog->is_in_failure_cooldown() );
|
||||
}
|
||||
|
||||
/** Failure recorded at t=now → cooldown active within 1h window. */
|
||||
public function test_cooldown_active_within_window(): void {
|
||||
$now = 1704067200;
|
||||
$this->options['prautoblogger_runware_catalog_last_failure_at'] = $now;
|
||||
// time() is stubbed to $now, so age = 0 < 3600 = cooldown.
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$this->assertTrue( $catalog->is_in_failure_cooldown() );
|
||||
}
|
||||
|
||||
/** Failure recorded > 1h ago → cooldown expired, retry permitted. */
|
||||
public function test_cooldown_expired_after_window(): void {
|
||||
$now = 1704067200;
|
||||
$past = $now - 3601; // More than 1h ago.
|
||||
$this->options['prautoblogger_runware_catalog_last_failure_at'] = $past;
|
||||
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$this->assertFalse( $catalog->is_in_failure_cooldown() );
|
||||
}
|
||||
|
||||
/** Custom cooldown from settings is respected. */
|
||||
public function test_cooldown_uses_setting_value(): void {
|
||||
$now = 1704067200;
|
||||
$this->options['prautoblogger_runware_catalog_last_failure_at'] = $now - 100;
|
||||
// Default 3600s would make this expired (100 < 3600), but set custom = 60s.
|
||||
// 100s > 60s so it should be expired.
|
||||
$this->options['prautoblogger_runware_catalog_failure_cooldown_seconds'] = 60;
|
||||
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$this->assertFalse( $catalog->is_in_failure_cooldown() );
|
||||
}
|
||||
|
||||
/** Sync failure sets last_failure_at and does not clear success timestamp. */
|
||||
public function test_sync_failure_records_failure_timestamp(): void {
|
||||
// Mock HTTP 401 to force sync failure.
|
||||
$this->options['prautoblogger_runware_api_key'] = 'test-api-key-plain';
|
||||
$this->stub_http_helpers();
|
||||
Functions\when( 'wp_remote_post' )->justReturn(
|
||||
$this->make_http_response( 401, '{"errors":[{"message":"Unauthorized"}]}' )
|
||||
);
|
||||
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$result = $catalog->sync();
|
||||
|
||||
$this->assertFalse( $result );
|
||||
$this->assertNotNull( $catalog->get_last_failure_at(), 'Failure timestamp should be recorded' );
|
||||
}
|
||||
|
||||
/** get_models returns fallback if no cache and sync fails. */
|
||||
public function test_get_models_fallback_on_sync_failure(): void {
|
||||
/** After failure, get_models suppresses sync within cooldown window. */
|
||||
public function test_get_models_suppresses_sync_during_cooldown(): void {
|
||||
$now = 1704067200;
|
||||
$this->options['prautoblogger_runware_api_key'] = 'test-api-key-plain';
|
||||
$this->options['prautoblogger_runware_catalog_last_failure_at'] = $now; // just failed.
|
||||
$this->options['prautoblogger_runware_model_cache_updated_at'] = $now - 90000; // stale cache.
|
||||
|
||||
$this->stub_http_helpers();
|
||||
// wp_remote_post should NOT be called during cooldown.
|
||||
Functions\expect( 'wp_remote_post' )->never();
|
||||
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$models = $catalog->get_models();
|
||||
$models = $catalog->get_models();
|
||||
|
||||
// Should fall back to hardcoded fallback list.
|
||||
$this->assertNotEmpty( $models );
|
||||
$ids = array_column( $models, 'id' );
|
||||
$this->assertContains( 'runware:100@1', $ids, 'Fallback schnell model should be present' );
|
||||
}
|
||||
|
||||
/** Successful sync clears failure timestamp. */
|
||||
public function test_successful_sync_clears_failure_timestamp(): void {
|
||||
$now = 1704067200;
|
||||
$this->options['prautoblogger_runware_api_key'] = 'test-api-key-plain';
|
||||
$this->options['prautoblogger_runware_catalog_last_failure_at'] = $now - 7200; // old failure.
|
||||
|
||||
$fixture_body = file_get_contents( __DIR__ . '/../../fixtures/runware-model-search-page1.json' );
|
||||
$this->stub_http_helpers();
|
||||
Functions\when( 'wp_remote_post' )->justReturn(
|
||||
$this->make_http_response( 200, $fixture_body )
|
||||
);
|
||||
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$result = $catalog->sync();
|
||||
|
||||
$this->assertTrue( $result, 'Sync should succeed with valid fixture response' );
|
||||
$this->assertNull( $catalog->get_last_failure_at(), 'Success should clear failure timestamp' );
|
||||
}
|
||||
|
||||
// ── Fallback list tests ───────────────────────────────────────────────────
|
||||
|
||||
/** get_models returns fallback when no cache and sync fails. */
|
||||
public function test_get_models_returns_fallback_when_no_cache(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$models = $catalog->get_models();
|
||||
|
||||
// Should have the fallback list (15 Runware models).
|
||||
$this->assertIsArray( $models );
|
||||
$this->assertGreaterThan( 0, count( $models ) );
|
||||
$this->assertNotEmpty( $models );
|
||||
|
||||
// Check at least one expected fallback model exists.
|
||||
$schnell_exists = false;
|
||||
foreach ( $models as $model ) {
|
||||
if ( 'runware:100@1' === ( $model['id'] ?? '' ) ) {
|
||||
$schnell_exists = true;
|
||||
$this->assertSame( 'FLUX.1 schnell (Runware)', $model['name'] );
|
||||
$this->assertSame( 'runware', $model['provider'] );
|
||||
break;
|
||||
}
|
||||
@@ -59,28 +281,12 @@ class RunwareModelCatalogTest extends BaseTestCase {
|
||||
$this->assertTrue( $schnell_exists, 'Fallback should include FLUX.1 schnell' );
|
||||
}
|
||||
|
||||
/** is_stale returns true if never synced. */
|
||||
public function test_is_stale_never_synced(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$this->assertTrue( $catalog->is_stale() );
|
||||
}
|
||||
|
||||
/** get_last_synced_at returns null if never synced. */
|
||||
public function test_get_last_synced_at_never(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$this->assertNull( $catalog->get_last_synced_at() );
|
||||
}
|
||||
|
||||
/** Fallback list is never empty. */
|
||||
/** Fallback list is never empty (even with no key configured). */
|
||||
public function test_get_models_never_empty(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
|
||||
// Even with no cache and failed sync, get_models should return the fallback.
|
||||
$models = $catalog->get_models();
|
||||
$this->assertIsArray( $models );
|
||||
$models = $catalog->get_models();
|
||||
$this->assertNotEmpty( $models );
|
||||
|
||||
// All models should have required fields.
|
||||
foreach ( $models as $model ) {
|
||||
$this->assertArrayHasKey( 'id', $model );
|
||||
$this->assertArrayHasKey( 'name', $model );
|
||||
@@ -89,13 +295,24 @@ class RunwareModelCatalogTest extends BaseTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
/** Fallback models have correct pricing. */
|
||||
/** All fallback models carry the image_generation capability. */
|
||||
public function test_fallback_models_have_image_generation_capability(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$models = $catalog->get_models();
|
||||
|
||||
foreach ( $models as $model ) {
|
||||
$this->assertIsArray( $model['capabilities'] );
|
||||
$this->assertContains( 'image_generation', $model['capabilities'] );
|
||||
}
|
||||
}
|
||||
|
||||
/** Fallback schnell and dev have correct pricing. */
|
||||
public function test_fallback_models_have_pricing(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$models = $catalog->get_models();
|
||||
$models = $catalog->get_models();
|
||||
|
||||
$schnell = null;
|
||||
$dev = null;
|
||||
$dev = null;
|
||||
foreach ( $models as $model ) {
|
||||
if ( 'runware:100@1' === $model['id'] ) {
|
||||
$schnell = $model;
|
||||
@@ -107,83 +324,98 @@ class RunwareModelCatalogTest extends BaseTestCase {
|
||||
|
||||
$this->assertNotNull( $schnell );
|
||||
$this->assertEqualsWithDelta( 0.0006, $schnell['cost_per_image'], 0.000001 );
|
||||
|
||||
$this->assertNotNull( $dev );
|
||||
$this->assertEqualsWithDelta( 0.02, $dev['cost_per_image'], 0.000001 );
|
||||
}
|
||||
|
||||
/** Fallback models all have 'image_generation' capability. */
|
||||
public function test_fallback_models_have_capabilities(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$models = $catalog->get_models();
|
||||
// ── Happy path (sync → cache → get_models) ───────────────────────────────
|
||||
|
||||
foreach ( $models as $model ) {
|
||||
$this->assertIsArray( $model['capabilities'] );
|
||||
$this->assertContains( 'image_generation', $model['capabilities'] );
|
||||
}
|
||||
}
|
||||
|
||||
/** Happy path: successful sync caches models and get_models returns them. */
|
||||
/** Successful sync caches models; get_models returns them from cache. */
|
||||
public function test_sync_success_caches_and_returns_models(): void {
|
||||
// The mocked API response body — models must have taskType=imageInference
|
||||
// so normalize_models() doesn't filter them out.
|
||||
$fake_body = json_encode(
|
||||
array(
|
||||
'data' => array(
|
||||
array(
|
||||
'id' => 'test-model-1',
|
||||
'name' => 'Test Model 1',
|
||||
'taskType' => 'imageInference',
|
||||
),
|
||||
array(
|
||||
'id' => 'test-model-2',
|
||||
'name' => 'Test Model 2',
|
||||
'taskType' => 'imageInference',
|
||||
),
|
||||
),
|
||||
)
|
||||
$fixture_body = file_get_contents( __DIR__ . '/../../fixtures/runware-model-search-page1.json' );
|
||||
$this->options['prautoblogger_runware_api_key'] = 'test-api-key-plain';
|
||||
|
||||
$this->stub_http_helpers();
|
||||
Functions\when( 'wp_remote_post' )->justReturn(
|
||||
$this->make_http_response( 200, $fixture_body )
|
||||
);
|
||||
|
||||
$fake_response = array(
|
||||
'response' => array( 'code' => 200 ),
|
||||
'body' => $fake_body,
|
||||
);
|
||||
|
||||
Functions\when( 'wp_remote_post' )->justReturn( $fake_response );
|
||||
// Alias the WP response-parsing helpers so they work against our array.
|
||||
Functions\when( 'wp_remote_retrieve_response_code' )->alias(
|
||||
function ( $r ) { return (int) ( $r['response']['code'] ?? 0 ); }
|
||||
);
|
||||
Functions\when( 'wp_remote_retrieve_body' )->alias(
|
||||
function ( $r ) { return (string) ( $r['body'] ?? '' ); }
|
||||
);
|
||||
Functions\when( 'is_wp_error' )->justReturn( false );
|
||||
|
||||
// Shared options store so get_option/update_option stay in sync
|
||||
// within this test. The API key must be non-empty for sync() to proceed.
|
||||
$store = array( 'prautoblogger_runware_api_key' => 'test-api-key-plain' );
|
||||
Functions\when( 'get_option' )->alias(
|
||||
function ( $key, $default = false ) use ( &$store ) {
|
||||
return $store[ $key ] ?? $default;
|
||||
}
|
||||
);
|
||||
Functions\when( 'update_option' )->alias(
|
||||
function ( $key, $value ) use ( &$store ) {
|
||||
$store[ $key ] = $value;
|
||||
return true;
|
||||
}
|
||||
);
|
||||
|
||||
// Sync should succeed: API key present, HTTP 200, 2 imageInference models.
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$result = $catalog->sync();
|
||||
$this->assertTrue( $result, 'Sync should return true on HTTP 200 with valid models' );
|
||||
$result = $catalog->sync();
|
||||
|
||||
$this->assertTrue( $result, 'Sync should return true on HTTP 200 with valid fixture' );
|
||||
|
||||
// get_models() should now return the synced list from cache.
|
||||
$models = $catalog->get_models();
|
||||
$this->assertIsArray( $models );
|
||||
$this->assertCount( 2, $models );
|
||||
$this->assertSame( 'test-model-1', $models[0]['id'] );
|
||||
$this->assertSame( 'test-model-2', $models[1]['id'] );
|
||||
// Fixture has 3 t2i models (schnell, dev, klein 9B).
|
||||
$this->assertCount( 3, $models, 'get_models should return the 3 cached t2i models' );
|
||||
|
||||
$ids = array_column( $models, 'id' );
|
||||
$this->assertContains( 'runware:100@1', $ids );
|
||||
$this->assertContains( 'runware:101@1', $ids );
|
||||
$this->assertContains( 'runware:400@2', $ids );
|
||||
}
|
||||
|
||||
/** Synced models have pricing merged from the pricing class. */
|
||||
public function test_synced_models_have_pricing_merged(): void {
|
||||
$fixture_body = file_get_contents( __DIR__ . '/../../fixtures/runware-model-search-page1.json' );
|
||||
$this->options['prautoblogger_runware_api_key'] = 'test-api-key-plain';
|
||||
|
||||
$this->stub_http_helpers();
|
||||
Functions\when( 'wp_remote_post' )->justReturn(
|
||||
$this->make_http_response( 200, $fixture_body )
|
||||
);
|
||||
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$catalog->sync();
|
||||
$models = $catalog->get_models();
|
||||
|
||||
$schnell = null;
|
||||
foreach ( $models as $m ) {
|
||||
if ( 'runware:100@1' === $m['id'] ) {
|
||||
$schnell = $m;
|
||||
}
|
||||
}
|
||||
$this->assertNotNull( $schnell );
|
||||
$this->assertEqualsWithDelta( 0.0006, (float) $schnell['cost_per_image'], 0.000001 );
|
||||
}
|
||||
|
||||
// ── Stale / absent cache tests ────────────────────────────────────────────
|
||||
|
||||
/** is_stale returns true if never synced. */
|
||||
public function test_is_stale_never_synced(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$this->assertTrue( $catalog->is_stale() );
|
||||
}
|
||||
|
||||
/** is_stale returns false for a fresh cache (synced < 24h ago). */
|
||||
public function test_is_stale_fresh_cache(): void {
|
||||
$now = 1704067200;
|
||||
$this->options['prautoblogger_runware_model_cache_updated_at'] = $now - 3600; // 1h ago.
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$this->assertFalse( $catalog->is_stale() );
|
||||
}
|
||||
|
||||
/** is_stale returns true when cache is older than 24h. */
|
||||
public function test_is_stale_old_cache(): void {
|
||||
$now = 1704067200;
|
||||
$this->options['prautoblogger_runware_model_cache_updated_at'] = $now - 90000; // > 24h ago.
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$this->assertTrue( $catalog->is_stale() );
|
||||
}
|
||||
|
||||
/** get_last_synced_at returns null if never synced. */
|
||||
public function test_get_last_synced_at_never(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$this->assertNull( $catalog->get_last_synced_at() );
|
||||
}
|
||||
|
||||
/** Sync with no API key returns false without recording a failure. */
|
||||
public function test_sync_no_api_key(): void {
|
||||
$catalog = new \PRAutoBlogger_Runware_Model_Catalog();
|
||||
$result = $catalog->sync();
|
||||
$this->assertFalse( $result );
|
||||
// No key → not a transient failure, no cooldown recorded.
|
||||
$this->assertNull( $catalog->get_last_failure_at() );
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user