Vectorize > Edit. * * Writes are asynchronous: Vectorize accepts them with a mutationId and applies * them about a minute later, and reads in between are unreliable. The last * mutationId is kept so status() can tell when the index has caught up. */ final class VectorizeStore implements VectorStore { public const STATE_OPTION = 'aipcf_embed_store'; /** Metadata the plugin filters on. A filter only covers vectors written after its index exists. */ public const METADATA_INDEXES = [ 'site' => 'string', 'post_type' => 'string', 'object_id' => 'number', 'lang' => 'string', ]; /** The HTTP API takes 5,000; at ~10 KB per vector (6 dp) 1,000 keeps a request near 10 MB. */ private const UPSERT_BATCH = 1000; private const DELETE_BATCH = 500; /** IDs per get_by_ids request (the Workers binding allows 20; the REST API documents no limit). */ private const GET_BATCH = 20; private const MAX_ID_BYTES = 64; /** Vectorize allows 10,240 bytes of compact JSON metadata; leave headroom. */ private const MAX_METADATA_BYTES = 10000; private string $accountId; private string $token; private string $index; public function __construct(?string $index = null, ?string $accountId = null, ?string $token = null) { $this->index = $index ?? self::configuredIndex(); $this->accountId = $accountId ?? get_account_id(); $this->token = $token ?? (string) apply_filters('aipcf_vectorize_token', get_api_key()); } public function id(): string { return 'vectorize'; } public function indexName(): string { return $this->index; } /** * The index in use: the base name, plus "-g" from the second generation on * (a rebuild writes into a fresh index; a just-deleted name stays unusable for minutes). */ public static function configuredIndex(): string { $custom = trim((string) (get_plugin_settings()['vectorize_index'] ?? '')); // A custom name may be shared by several sites: never suffixed, never dropped. return $custom !== '' ? self::sanitizeIndexName($custom) : State::suffixed(self::baseIndex(), 64); } /** * The index from the settings, or aipcf- (plus the blog ID on a * multisite sub-site): lowercase letters, digits and dashes, at most 64 bytes. */ public static function baseIndex(): string { $name = trim((string) (get_plugin_settings()['vectorize_index'] ?? '')); if ($name === '') { $name = 'aipcf-' . (string) wp_parse_url(home_url(), PHP_URL_HOST); if (is_multisite() && !is_main_site()) { $name .= '-' . get_current_blog_id(); } } return self::sanitizeIndexName($name); } /** * True when the index belongs to this site alone (the default name), so * purging can drop it instead of deleting vector by vector. */ public function isSiteOwn(): bool { return trim((string) (get_plugin_settings()['vectorize_index'] ?? '')) === ''; } public static function sanitizeIndexName(string $name): string { $name = strtolower($name); $name = (string) preg_replace('/[^a-z0-9-]+/', '-', $name); $name = trim((string) preg_replace('/-+/', '-', $name), '-'); if ($name === '' || !preg_match('/^[a-z]/', $name)) { $name = 'aipcf-' . $name; } return rtrim(substr($name, 0, 64), '-'); } public function test() { $r = $this->request('GET', ''); return is_wp_error($r) ? $r : true; } public function ensureIndex(int $dims, string $metric = 'cosine') { if ($dims < 32 || $dims > 1536) { return new \WP_Error('aipcf_store_mismatch', sprintf( /* translators: %d: numbers in each vector the model makes */ __('Vectorize indexes hold vectors of 32 to 1,536 numbers, but the model makes vectors of %d. Choose another model.', 'aipcf-ai-provider-for-cloudflare'), $dims )); } $created = false; $index = $this->request('GET', '/' . rawurlencode($this->index)); if (is_wp_error($index) && $index->get_error_code() === 'aipcf_store_missing') { $index = $this->request('POST', '', [ 'name' => $this->index, 'description' => sprintf('AIPCF embeddings for %s', (string) wp_parse_url(home_url(), PHP_URL_HOST)), 'config' => ['dimensions' => $dims, 'metric' => $metric], ]); $created = !is_wp_error($index); if (is_wp_error($index) && ($index->get_error_data()['cf_code'] ?? 0) === 3002) { // Another request created it between our GET and POST. $index = $this->request('GET', '/' . rawurlencode($this->index)); } } if (is_wp_error($index)) { return $index; } $config = is_array($index['config'] ?? null) ? $index['config'] : []; if ((int) ($config['dimensions'] ?? 0) !== $dims || (string) ($config['metric'] ?? '') !== $metric) { // Rebuild starts a new index only for the site's own one; a custom name is re-embedded in place. return new \WP_Error('aipcf_store_mismatch', sprintf( $this->isSiteOwn() /* translators: 1: index name, 2: numbers in each stored vector, 3: how the index compares vectors, 4: numbers in each vector the model makes, 5: how the model's vectors are compared */ ? __('The Vectorize index %1$s holds vectors of %2$d numbers compared by %3$s, but the embedding model needs vectors of %4$d numbers compared by %5$s. Press Rebuild (under More actions) to start a new index.', 'aipcf-ai-provider-for-cloudflare') /* translators: 1: index name, 2: numbers in each stored vector, 3: how the index compares vectors, 4: numbers in each vector the model makes, 5: how the model's vectors are compared */ : __('The Vectorize index %1$s holds vectors of %2$d numbers compared by %3$s, but the embedding model needs vectors of %4$d numbers compared by %5$s. Enter a new index name, or go back to a model with the same vector size.', 'aipcf-ai-provider-for-cloudflare'), $this->index, (int) ($config['dimensions'] ?? 0), (string) ($config['metric'] ?? '?'), $dims, $metric )); } // Right after a create (especially of a recently deleted name) the index's // sub-routes can still answer "deleted" for minutes. That means "not ready // yet": return, and let the caller check status()['ready'] and call again. $notYet = static fn($r): bool => $created && is_wp_error($r) && $r->get_error_code() === 'aipcf_store_missing'; $listed = $this->metadataIndexes(); if ($notYet($listed)) { return ['created' => true]; } if (is_wp_error($listed)) { return $listed; } foreach (self::METADATA_INDEXES as $property => $type) { if (in_array($property, $listed, true)) { continue; } $r = $this->request('POST', '/' . rawurlencode($this->index) . '/metadata_index/create', ['propertyName' => $property, 'indexType' => $type]); if (is_wp_error($r) && preg_match('/already exists/i', $r->get_error_message())) { // The list read lagged behind an earlier create (reads are eventually consistent). continue; } if ($notYet($r)) { return ['created' => true]; } if (is_wp_error($r)) { return $r; } $this->rememberMutation($r); } return ['created' => $created]; } public function status() { $empty = ['exists' => false, 'ready' => false, 'dims' => 0, 'metric' => '', 'vector_count' => null, 'settled' => true, 'missing_metadata' => array_keys(self::METADATA_INDEXES)]; $index = $this->request('GET', '/' . rawurlencode($this->index)); if (is_wp_error($index)) { return $index->get_error_code() === 'aipcf_store_missing' ? $empty : $index; } $info = $this->request('GET', '/' . rawurlencode($this->index) . '/info'); if (is_wp_error($info)) { return $info; } $listed = $this->metadataIndexes(); if (is_wp_error($listed)) { return $listed; } $missing = array_values(array_diff(array_keys(self::METADATA_INDEXES), $listed)); return [ 'exists' => true, 'ready' => $missing === [], 'dims' => (int) ($index['config']['dimensions'] ?? 0), 'metric' => (string) ($index['config']['metric'] ?? ''), 'vector_count' => isset($info['vectorCount']) ? (int) $info['vectorCount'] : null, 'settled' => $this->settled($info), 'missing_metadata' => $missing, ]; } public function upsert(array $vectors) { $rows = []; $bad = []; foreach ($vectors as $v) { $id = (string) ($v['id'] ?? ''); if ($id === '' || strlen($id) > self::MAX_ID_BYTES) { $bad[] = $id; continue; } $row = [ 'id' => $id, 'values' => array_map(static fn($x): float => round((float) $x, 6), array_values((array) ($v['values'] ?? []))), ]; $metadata = self::fitMetadata(is_array($v['metadata'] ?? null) ? $v['metadata'] : []); if ($metadata === null) { $bad[] = $id; continue; } if ($metadata !== []) { $row['metadata'] = $metadata; } $rows[] = $row; } if ($bad !== []) { // Nothing is sent: one invalid vector would fail the whole request. return new \WP_Error('aipcf_store_item', sprintf( /* translators: %d: number of vectors */ _n('%d vector has an ID over 64 bytes or metadata that cannot fit in 10 KB.', '%d vectors have an ID over 64 bytes or metadata that cannot fit in 10 KB.', count($bad), 'aipcf-ai-provider-for-cloudflare'), count($bad) ), ['ids' => $bad]); } foreach (array_chunk($rows, self::UPSERT_BATCH) as $batch) { $body = implode("\n", array_map(static fn($row): string => (string) wp_json_encode($row), $batch)) . "\n"; $r = $this->request('POST', '/' . rawurlencode($this->index) . '/upsert', $body, 'application/x-ndjson', 120); if (is_wp_error($r)) { return $r; } $this->rememberMutation($r); } return true; } public function delete(array $ids) { $ids = array_values(array_filter(array_map('strval', $ids), static fn($id): bool => $id !== '')); foreach (array_chunk($ids, self::DELETE_BATCH) as $batch) { $r = $this->request('POST', '/' . rawurlencode($this->index) . '/delete_by_ids', ['ids' => $batch]); if (is_wp_error($r)) { return $r; } $this->rememberMutation($r); } return true; } public function query(array $vector, int $topK = 10, array $filter = [], bool $withMetadata = true) { // Vectorize returns at most 50 matches with metadata, 100 without. $topK = max(1, min($topK, $withMetadata ? 50 : 100)); $body = [ 'vector' => array_map('floatval', array_values($vector)), 'topK' => $topK, 'returnValues' => false, 'returnMetadata' => $withMetadata ? 'all' : 'none', ]; if ($filter !== []) { $body['filter'] = $filter; } $r = $this->request('POST', '/' . rawurlencode($this->index) . '/query', $body); if (is_wp_error($r)) { return $r; } $out = []; foreach ((array) ($r['matches'] ?? []) as $m) { if (!is_array($m) || !isset($m['id'])) { continue; } $out[] = [ 'id' => (string) $m['id'], 'score' => (float) ($m['score'] ?? 0), 'metadata' => is_array($m['metadata'] ?? null) ? $m['metadata'] : [], ]; } return $out; } public function vectors(array $ids) { $ids = array_values(array_unique(array_filter(array_map('strval', $ids), static fn($id): bool => $id !== ''))); $out = []; foreach (array_chunk($ids, self::GET_BATCH) as $batch) { $r = $this->request('POST', '/' . rawurlencode($this->index) . '/get_by_ids', ['ids' => $batch]); if (is_wp_error($r)) { return $r; } foreach ((array) $r as $v) { if (is_array($v) && isset($v['id'], $v['values']) && is_array($v['values'])) { $out[(string) $v['id']] = array_map('floatval', array_values($v['values'])); } } } return $out; } public function dropIndex() { $r = $this->request('DELETE', '/' . rawurlencode($this->index)); if (is_wp_error($r) && $r->get_error_code() !== 'aipcf_store_missing') { return $r; } $state = self::state(); unset($state[$this->index]); update_option(self::STATE_OPTION, $state, false); return true; } /** * Trims the chunk text so the compact JSON fits Vectorize's metadata limit. * Returns null when it cannot fit even without the text. * * @param array $metadata * @return array|null */ public static function fitMetadata(array $metadata): ?array { $size = static fn(array $m): int => strlen((string) wp_json_encode($m)); if ($size($metadata) <= self::MAX_METADATA_BYTES) { return $metadata; } if (!isset($metadata['text']) || !is_string($metadata['text'])) { return null; } $text = $metadata['text']; $metadata['text'] = ''; $room = self::MAX_METADATA_BYTES - $size($metadata); if ($room <= 0) { return null; } // JSON escaping can grow a byte of text into up to 6; shrink until it fits. $cut = (string) mb_strcut($text, 0, $room, 'UTF-8'); while ($cut !== '') { $metadata['text'] = $cut; if ($size($metadata) <= self::MAX_METADATA_BYTES) { return $metadata; } $cut = (string) mb_strcut($cut, 0, (int) floor(strlen($cut) * 0.9), 'UTF-8'); } $metadata['text'] = ''; return $metadata; } /** * @return list|\WP_Error */ private function metadataIndexes() { $r = $this->request('GET', '/' . rawurlencode($this->index) . '/metadata_index/list'); if (is_wp_error($r)) { return $r; } $names = []; foreach ((array) ($r['metadataIndexes'] ?? []) as $m) { if (is_array($m) && isset($m['propertyName'])) { $names[] = (string) $m['propertyName']; } } return $names; } /** * True when Vectorize has applied every write this site made to the index. * * @param array $info */ private function settled(array $info): bool { $mine = self::state()[$this->index] ?? null; if (!is_array($mine) || empty($mine['mutation'])) { return true; } if ((string) ($info['processedUpToMutation'] ?? '') === (string) $mine['mutation']) { return true; } // Another writer's later mutation can be the latest processed one; go by time then. $processedAt = strtotime((string) ($info['processedUpToDatetime'] ?? '')); return $processedAt !== false && $processedAt >= (int) ($mine['at'] ?? PHP_INT_MAX); } /** * @param array $result */ private function rememberMutation(array $result): void { if (empty($result['mutationId'])) { return; } $state = self::state(); $state[$this->index] = ['mutation' => (string) $result['mutationId'], 'at' => time()]; update_option(self::STATE_OPTION, $state, false); } /** * @return array */ private static function state(): array { $state = get_option(self::STATE_OPTION, []); return is_array($state) ? $state : []; } /** * One call to the Vectorize API; returns the decoded `result` (an empty array * when it is null) or a classified \WP_Error. * * @param array|string|null $body * @return array|\WP_Error */ private function request(string $method, string $path, $body = null, string $type = 'application/json', int $timeout = 30) { if ($this->accountId === '' || $this->token === '') { return new \WP_Error( 'aipcf_store_auth', // A token saved in the plugin earlier still wins over Connectors: then the Overview tab is the place. core_connector_is_available() && (string) (get_plugin_settings()['api_key'] ?? '') === '' ? __('The Cloudflare Account ID or API token is missing. Add your API token on Settings > Connectors and your Account ID on Settings > Connection.', 'aipcf-ai-provider-for-cloudflare') : __('The Cloudflare Account ID or API token is missing. Add your Account ID and API token on Settings > Connection.', 'aipcf-ai-provider-for-cloudflare') ); } $args = [ 'method' => $method, 'timeout' => $timeout, 'redirection' => 0, // never resend the token elsewhere 'headers' => ['Authorization' => 'Bearer ' . $this->token], ]; if ($body !== null) { $args['headers']['Content-Type'] = $type; $args['body'] = is_string($body) ? $body : (string) wp_json_encode($body); } $url = sprintf('https://api.cloudflare.com/client/v4/accounts/%s/vectorize/v2/indexes%s', rawurlencode($this->accountId), $path); $response = wp_remote_request($url, $args); if (is_wp_error($response)) { /* translators: %s: error message */ return new \WP_Error('aipcf_retry', sprintf(__('Vectorize did not answer: %s', 'aipcf-ai-provider-for-cloudflare'), $response->get_error_message())); } $status = (int) wp_remote_retrieve_response_code($response); $data = json_decode((string) wp_remote_retrieve_body($response), true); $data = is_array($data) ? $data : []; if ($status >= 200 && $status < 300) { return is_array($data['result'] ?? null) ? $data['result'] : []; } return self::errorFor($status, $data); } /** * @param array $data */ private static function errorFor(int $status, array $data): \WP_Error { $first = isset($data['errors'][0]) && is_array($data['errors'][0]) ? $data['errors'][0] : []; $code = (int) ($first['code'] ?? 0); $detail = isset($first['message']) && is_scalar($first['message']) ? (string) $first['message'] : sprintf('HTTP %d', $status); /* translators: %s: error detail from Cloudflare */ $message = sprintf(__('Vectorize returned an error: %s', 'aipcf-ai-provider-for-cloudflare'), $detail); $context = ['status' => $status, 'cf_code' => $code]; if ($status === 429 || $status >= 500) { return new \WP_Error('aipcf_retry', $message, $context); } if ($status === 401 || $status === 403) { /* translators: %s: error detail from Cloudflare */ return new \WP_Error('aipcf_store_auth', sprintf(__('Vectorize refused the Cloudflare token, which needs the Account > Vectorize > Edit permission: %s', 'aipcf-ai-provider-for-cloudflare'), $detail), $context); } // 404/3000 never created, 410/3005 deleted (the name can be reused at once), 40040 on data routes. if ($status === 404 || $status === 410 || in_array($code, [3000, 3005, 40040], true)) { return new \WP_Error('aipcf_store_missing', $message, $context); } if ($code === 40012) { return new \WP_Error('aipcf_store_mismatch', $message, $context); } if ($code === 40008 || $code === 40016) { return new \WP_Error('aipcf_store_item', $message, $context); } return new \WP_Error('aipcf_store_failed', $message, $context); } }