prefix . 'aipt_blueprint_snapshots'; } /** * Find the existing snapshot for this exact payload, or create one. * * The content hash folds in `kind` and `generator` (not just * `payload`): it is the sha256 of the canonical payload JSON including * kind and generator, otherwise a 'definition' pin and a 'run' pin that * coincidentally serialized the same bytes could collide. The insert * races safely: a duplicate-key failure from a * concurrent identical findOrCreate() is resolved by re-reading the row * the other request just created, never surfaced as an error. * * This hash is purely internal content-addressing for this table — it * has no relationship to, and no stability contract with, Domain's * DefinitionHasher (which hashes a BlueprintDefinition for a different, * externally-visible purpose). * * @param string $kind 'definition'|'run'. * @param string $generator Generator key. * @param array $payload The snapshot payload (shape depends on kind: 'definition' or 'run'). * @param array $meta { * @type int $blueprintId Default 0. * @type int $blueprintRevision Default 0. * @type int $brandProfileId Default 0. * @type int $brandRevision Default 0. * @type int $createdBy Default current user. * } * @return array{id: int, hash: string} */ public function findOrCreate( string $kind, string $generator, array $payload, array $meta = array() ): array { global $wpdb; $table = self::table(); $hash = self::computeHash( $kind, $generator, $payload ); $existing = $this->getByHash( $hash ); if ( null !== $existing ) { return array( 'id' => (int) $existing['id'], 'hash' => $hash ); } $now = current_time( 'mysql', true ); $user = isset( $meta['createdBy'] ) ? (int) $meta['createdBy'] : (int) ( function_exists( 'get_current_user_id' ) ? get_current_user_id() : 0 ); $row = array( 'kind' => $kind, 'hash' => $hash, 'generator' => $generator, 'blueprint_id' => (int) ( $meta['blueprintId'] ?? 0 ), 'blueprint_revision' => (int) ( $meta['blueprintRevision'] ?? 0 ), 'brand_profile_id' => (int) ( $meta['brandProfileId'] ?? 0 ), 'brand_revision' => (int) ( $meta['brandRevision'] ?? 0 ), 'payload' => wp_json_encode( $payload ), 'created_by' => $user, 'created_at' => $now, 'last_used_at' => $now, ); $previous_suppress = $wpdb->suppress_errors( true ); $result = $wpdb->insert( $table, $row, array( '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%s', '%d', '%s', '%s' ) ); $wpdb->suppress_errors( $previous_suppress ); if ( false !== $result ) { return array( 'id' => (int) $wpdb->insert_id, 'hash' => $hash ); } $raced = $this->getByHash( $hash ); if ( null !== $raced ) { return array( 'id' => (int) $raced['id'], 'hash' => $hash ); } return array( 'id' => 0, 'hash' => $hash ); } /** * Read a snapshot by id. * * @param int $id Snapshot id. * @return array|null */ public function get( int $id ): ?array { global $wpdb; $table = self::table(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $id ), ARRAY_A ); return is_array( $row ) ? $this->mapRow( $row ) : null; } /** * Read a snapshot by its content hash. * * @param string $hash Content hash. * @return array|null */ public function getByHash( string $hash ): ?array { global $wpdb; if ( '' === $hash ) { return null; } $table = self::table(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE hash = %s", $hash ), ARRAY_A ); return is_array( $row ) ? $this->mapRow( $row ) : null; } /** * Mark a snapshot as used right now, so retention (snapshots with * last_used_at older than 30 days) measures from the * last time anything actually consumed it, not merely when it was * created. * * Writes only when the stored value is more than a day old: retention * counts in days, so a snapshot used again today needs no new write. * Every write is its own commit, and a run pin touches up to five * snapshots, so rewriting each one on every run made pinning wait on * five disk flushes (over a second on a slow disk) before the first * product could start. A snapshot due for pruning is always more than a * day old, so a touch that races the cleanup still saves it (see * deleteIfUnusedSince()). * * @param int $id Snapshot id. * @return void */ public function touch( int $id ): void { global $wpdb; $table = self::table(); $now = current_time( 'mysql', true ); $cutoff = gmdate( 'Y-m-d H:i:s', (int) strtotime( $now . ' UTC' ) - self::TOUCH_INTERVAL_SECONDS ); $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET last_used_at = %s WHERE id = %d AND last_used_at < %s", $now, $id, $cutoff ) ); } /** * Candidate ids for retention pruning: snapshots last used before * $older_than, excluding every protected id. The caller * (BlueprintCleanup) computes the protected set by walking live * automation run pins — this method only applies the resulting filter. * * @param string $older_than MySQL UTC datetime cutoff. * @param int[] $protected_ids Snapshot ids that must never be returned. * @param int $limit Hard cap (bounded — never an unbounded scan). * @return int[] */ public function prunable( string $older_than, array $protected_ids, int $limit ): array { global $wpdb; $table = self::table(); $limit = $limit > 0 ? $limit : 500; $exclude = ''; if ( ! empty( $protected_ids ) ) { $ids_in = implode( ',', array_map( 'intval', $protected_ids ) ); $exclude = " AND id NOT IN ({$ids_in})"; } $rows = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM {$table} WHERE last_used_at < %s{$exclude} ORDER BY last_used_at ASC LIMIT %d", $older_than, $limit ) ); return is_array( $rows ) ? array_map( 'intval', $rows ) : array(); } /** * Delete a snapshot by id. * * @param int $id Snapshot id. * @return bool */ public function delete( int $id ): bool { global $wpdb; $table = self::table(); $result = $wpdb->delete( $table, array( 'id' => $id ), array( '%d' ) ); return false !== $result && (int) $result >= 1; } /** * Delete a snapshot by id, but only if it is still unused as of * $older_than — the same cutoff the caller's prunable() read used. * * Re-checks the cutoff inside the DELETE itself rather than trusting * prunable()'s earlier read: a touch() (or a findOrCreate() that * resolves to this same content-addressed row) landing between that * read and this call advances last_used_at, and this statement then * simply matches zero rows instead of deleting a snapshot a job still * needs. * * @param int $id Snapshot id. * @param string $older_than MySQL UTC datetime cutoff. * @return bool Whether a row was actually deleted. */ public function deleteIfUnusedSince( int $id, string $older_than ): bool { global $wpdb; $table = self::table(); $result = $wpdb->query( $wpdb->prepare( "DELETE FROM {$table} WHERE id = %d AND last_used_at < %s", $id, $older_than ) ); return false !== $result && (int) $result >= 1; } /** * Content hash of (kind, generator, payload), canonicalized so key * order never affects the result. * * @param string $kind 'definition'|'run'. * @param string $generator Generator key. * @param array $payload Snapshot payload. * @return string */ private static function computeHash( string $kind, string $generator, array $payload ): string { $canonical = self::canonicalize( array( 'kind' => $kind, 'generator' => $generator, 'payload' => $payload, ) ); return hash( 'sha256', (string) wp_json_encode( $canonical ) ); } /** * Recursively sort associative array keys so two PHP arrays built in a * different key order (but otherwise identical) always encode to the * same JSON string. Sequential (list) arrays keep their order — order * is meaningful for e.g. `assignments[]`. * * @param mixed $value Any JSON-encodable value. * @return mixed */ private static function canonicalize( $value ) { if ( ! is_array( $value ) ) { return $value; } if ( self::isList( $value ) ) { return array_map( array( __CLASS__, 'canonicalize' ), $value ); } ksort( $value ); $out = array(); foreach ( $value as $key => $item ) { $out[ (string) $key ] = self::canonicalize( $item ); } return $out; } /** * PHP 7.4-compatible equivalent of PHP 8.1's array_is_list(). * * @param array $value Array to inspect. * @return bool */ private static function isList( array $value ): bool { if ( empty( $value ) ) { return true; } return array_keys( $value ) === range( 0, count( $value ) - 1 ); } /** * Map a raw database row to the canonical camelCase response shape. * * @param array $row Database row. * @return array */ private function mapRow( array $row ): array { $payload = json_decode( (string) ( $row['payload'] ?? '' ), true ); return array( 'id' => (int) ( $row['id'] ?? 0 ), 'kind' => (string) ( $row['kind'] ?? '' ), 'hash' => (string) ( $row['hash'] ?? '' ), 'generator' => (string) ( $row['generator'] ?? '' ), 'blueprintId' => (int) ( $row['blueprint_id'] ?? 0 ), 'blueprintRevision' => (int) ( $row['blueprint_revision'] ?? 0 ), 'brandProfileId' => (int) ( $row['brand_profile_id'] ?? 0 ), 'brandRevision' => (int) ( $row['brand_revision'] ?? 0 ), 'payload' => is_array( $payload ) ? $payload : array(), 'createdBy' => (int) ( $row['created_by'] ?? 0 ), 'createdAt' => (string) ( $row['created_at'] ?? '' ), 'lastUsedAt' => (string) ( $row['last_used_at'] ?? '' ), ); } }