P0 security: - PRV_Gateway_Client: remove response body from RuntimeException (HTTP status only) - PRV_Capture_Writer: allowlist-only write (prompt/response text, never headers/auth) - Mandatory capture order: can_afford → probe → persist_result → update_row_cost → write_meta → capture_io - capture_io last and wrapped in swallowing try/catch New tables (SCHEMA_VERSION 3): - prv_call_meta: cost/metadata per call, kept indefinitely - prv_call_io: rendered prompt + raw response, pruned on retention window (default 90d) New classes: - PRV_Call_Meta_Table, PRV_Call_Io_Table: table schema + dbDelta - PRV_Capture_Writer: metadata + I/O write; security allowlist enforced - PRV_Prune_Cron: daily prv_daily_prune cron deletes aged prv_call_io rows only - PRV_Cost_Rollup_Query: MTD summary, model breakdown, drill-down, projection - PRV_Call_Log_Query: paginated + filtered call-log query + per-call I/O fetch - PRV_Costs_Page + PRV_Costs_Renderer: Costs admin sub-page (cap progress, bento, model table, drill-down) - PRV_Call_Log_Page + PRV_Call_Log_Table_Renderer: Call Log admin sub-page (filter bar, paginated table, WCAG AA pagination) - PRV_Call_Drawer_Renderer: non-modal complementary drawer (5 states: Normal/Pruned/Legacy/Failed/Loading) - PRV_Call_Drawer_Script: inline JS for drawer (300-line split from renderer) - PRV_Call_Detail_Ajax: wp_ajax_prv_call_detail AJAX handler - PRV_Admin_Page_Css: CSS provider (300-line split from PRV_Admin_Page) - PRV_Probe_Run_Executor: inner probe loop (300-line split from PRV_Probe_Runner) Updated: - PRV_Probe_Result: tokens_in/tokens_out params + getters - Both providers: report tokens_in/tokens_out from usage.prompt_tokens/completion_tokens - PRV_Probe_Runner: slimmed to lock+UUID+delegation; injects PRV_Capture_Writer - PRV_Config: get_io_retention_days(); PRV_IO_RETENTION_DEFAULT_DAYS constant - PRV_Upgrader/Activator/Deactivator/Plugin: register new tables, cron, pages, AJAX - Settings: retention days field + save in controller - uninstall.php: DROP both new tables, clear prv_daily_prune cron - Subnav 4-tab strip (Dashboard | Costs | Call Log | Settings) on all pages - ARCHITECTURE.md, CHANGELOG.md, CONTEXT.md, CONVENTIONS.md updated Tests: - test-capture-writer.php: write_meta, write_io, P0 security (401 record has no key/Bearer/sk-or-) - test-cost-audit.php: MTD reconciliation, projection, prune, forced capture_io exception, table drops Agent-Session: peptiderepo-geomonitor-v0.3.0-cost-audit
200 lines
6.9 KiB
PHP
200 lines
6.9 KiB
PHP
<?php
|
|
/**
|
|
* Cloudflare AI Gateway HTTP client shared by all providers.
|
|
*
|
|
* @package PrVision
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
/**
|
|
* Cloudflare AI Gateway HTTP client — shared by all providers.
|
|
*
|
|
* Builds the gateway URL, injects the Authorization header, applies
|
|
* exponential-backoff retry, and delegates cURL auth injection (for
|
|
* hosts that strip the Authorization header) — mirroring the approach
|
|
* used in PRAutoBlogger's OpenRouter provider.
|
|
*
|
|
* Gateway URL shape:
|
|
* https://gateway.ai.cloudflare.com/v1/{account_id}/{gateway_id}/openrouter
|
|
*
|
|
* Required WP-config constants (documented in README.md):
|
|
* PRV_CF_ACCOUNT_ID — Cloudflare account ID
|
|
* PRV_CF_GATEWAY_ID — AI Gateway name (e.g. "peptiderepo-prod")
|
|
* PRV_OPENROUTER_API_KEY — OpenRouter API key (sk-or-…)
|
|
*
|
|
* Who triggers: PRV_Perplexity_Provider, PRV_OpenRouter_Provider.
|
|
* Dependencies: wp_remote_post(), add_action(), curl_setopt().
|
|
*
|
|
* @see class-prv-perplexity-provider.php — Uses post_to_gateway().
|
|
* @see class-prv-openrouter-provider.php — Uses post_to_gateway().
|
|
* @see ARCHITECTURE.md — §External API integrations.
|
|
* @package PrVision
|
|
*/
|
|
class PRV_Gateway_Client {
|
|
|
|
/**
|
|
* HTTP status code from the most recent request (set on permanent error).
|
|
*
|
|
* @var int
|
|
*/
|
|
private int $last_http_status = 200;
|
|
|
|
/**
|
|
* Base URL for the Cloudflare AI Gateway (without trailing slash).
|
|
*/
|
|
private const GATEWAY_BASE = 'https://gateway.ai.cloudflare.com/v1';
|
|
|
|
/**
|
|
* Fallback to direct OpenRouter when the gateway is not configured.
|
|
*/
|
|
private const OPENROUTER_BASE = 'https://openrouter.ai/api/v1';
|
|
|
|
/**
|
|
* Send a chat-completion POST request through the gateway (or direct).
|
|
*
|
|
* Retries with exponential backoff on transient failures (5xx, timeout).
|
|
* Throws on permanent failure after exhausting retries.
|
|
*
|
|
* Side effects: HTTP request; logs errors to PHP error log.
|
|
*
|
|
* @param string $provider_slug Gateway provider path segment (e.g. "openrouter", "perplexity").
|
|
* @param array<string, mixed> $body JSON request body.
|
|
* @param string $api_key Bearer token.
|
|
* @param string $endpoint Path appended after the provider base (default "/chat/completions").
|
|
*
|
|
* @return array<string, mixed> Decoded JSON response body.
|
|
*
|
|
* @throws \RuntimeException On permanent HTTP failure or parse error.
|
|
* Exception message carries HTTP status code only;
|
|
* the response body is never included (P0: prevents
|
|
* secret-key leakage via 401 error responses).
|
|
*/
|
|
public function post_to_gateway( string $provider_slug, array $body, string $api_key, string $endpoint = '/chat/completions' ): array {
|
|
$base_url = $this->build_base_url( $provider_slug );
|
|
$url = $base_url . $endpoint;
|
|
$base_host = (string) wp_parse_url( $base_url, PHP_URL_HOST );
|
|
|
|
$headers = array(
|
|
'Authorization' => 'Bearer ' . $api_key,
|
|
'Content-Type' => 'application/json',
|
|
'HTTP-Referer' => home_url(),
|
|
'X-Title' => 'PR Vision',
|
|
);
|
|
|
|
// Belt-and-suspenders cURL injection — some hosts strip Authorization.
|
|
$curl_filter = $this->register_curl_auth_filter( $headers, $base_host );
|
|
|
|
$last_error = '';
|
|
|
|
try {
|
|
for ( $attempt = 1; $attempt <= PRV_MAX_RETRIES; $attempt++ ) {
|
|
$response = wp_remote_post(
|
|
$url,
|
|
array(
|
|
'timeout' => PRV_API_TIMEOUT_SECONDS,
|
|
'headers' => $headers,
|
|
'body' => wp_json_encode( $body ),
|
|
)
|
|
);
|
|
|
|
if ( is_wp_error( $response ) ) {
|
|
$last_error = $response->get_error_message();
|
|
if ( $attempt < PRV_MAX_RETRIES ) {
|
|
sleep( PRV_RETRY_BASE_DELAY_SECONDS * (int) pow( 2, $attempt - 1 ) );
|
|
}
|
|
continue;
|
|
}
|
|
|
|
$status = wp_remote_retrieve_response_code( $response );
|
|
$raw_body = wp_remote_retrieve_body( $response );
|
|
|
|
if ( $status >= 500 || 429 === $status ) {
|
|
$last_error = sprintf( 'HTTP %d', $status );
|
|
if ( $attempt < PRV_MAX_RETRIES ) {
|
|
$retry_after = wp_remote_retrieve_header( $response, 'retry-after' );
|
|
$delay = $retry_after ? min( (int) $retry_after, 60 ) : PRV_RETRY_BASE_DELAY_SECONDS * (int) pow( 2, $attempt - 1 );
|
|
sleep( $delay );
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if ( $status >= 400 ) {
|
|
$this->last_http_status = $status;
|
|
// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- exception message, not HTML output; body intentionally omitted (P0: prevents key-leak via 401 body)
|
|
throw new \RuntimeException( sprintf( 'PR Vision gateway HTTP %d', $status ) );
|
|
}
|
|
|
|
$data = json_decode( $raw_body, true );
|
|
if ( ! is_array( $data ) ) {
|
|
throw new \RuntimeException( 'PR Vision: invalid JSON response from gateway.' );
|
|
}
|
|
|
|
return $data;
|
|
}
|
|
} finally {
|
|
remove_action( 'http_api_curl', $curl_filter, 99 );
|
|
}
|
|
|
|
// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- exception message, not HTML output
|
|
throw new \RuntimeException( sprintf( 'PR Vision: gateway failed after %d attempts. Last: %s', PRV_MAX_RETRIES, $last_error ) );
|
|
}
|
|
|
|
/**
|
|
* Get the HTTP status code from the last failed request.
|
|
*
|
|
* Allows callers to record the HTTP status code in error records without
|
|
* parsing the exception message. Returns 200 when no failure has occurred.
|
|
*
|
|
* @return int HTTP status code.
|
|
*/
|
|
public function get_last_http_status(): int {
|
|
return $this->last_http_status;
|
|
}
|
|
|
|
/**
|
|
* Build the API base URL (gateway or direct fallback).
|
|
*
|
|
* @param string $provider_slug Path segment after gateway_id (e.g. "openrouter").
|
|
*
|
|
* @return string Base URL without trailing slash.
|
|
*/
|
|
public function build_base_url( string $provider_slug ): string {
|
|
if ( defined( 'PRV_CF_ACCOUNT_ID' ) && defined( 'PRV_CF_GATEWAY_ID' )
|
|
&& '' !== PRV_CF_ACCOUNT_ID && '' !== PRV_CF_GATEWAY_ID ) {
|
|
return sprintf(
|
|
'%s/%s/%s/%s',
|
|
self::GATEWAY_BASE,
|
|
PRV_CF_ACCOUNT_ID,
|
|
PRV_CF_GATEWAY_ID,
|
|
$provider_slug
|
|
);
|
|
}
|
|
return self::OPENROUTER_BASE;
|
|
}
|
|
|
|
/**
|
|
* Register cURL auth injection filter (mirrors PRAutoBlogger pattern).
|
|
*
|
|
* @param array<string, string> $headers Request headers including Authorization.
|
|
* @param string $base_host Upstream host — limits leakage scope.
|
|
*
|
|
* @return callable The registered filter (caller MUST remove_action after request).
|
|
*/
|
|
private function register_curl_auth_filter( array $headers, string $base_host ): callable {
|
|
$filter = function ( $handle, $parsed_args, $url ) use ( $headers, $base_host ): void {
|
|
if ( '' === $base_host || false === strpos( (string) $url, $base_host ) ) {
|
|
return;
|
|
}
|
|
$curl_headers = array();
|
|
foreach ( $headers as $name => $value ) {
|
|
$curl_headers[] = $name . ': ' . $value;
|
|
}
|
|
// phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt
|
|
curl_setopt( $handle, CURLOPT_HTTPHEADER, $curl_headers );
|
|
};
|
|
add_action( 'http_api_curl', $filter, 99, 3 );
|
|
return $filter;
|
|
}
|
|
}
|