← Back
Editing: class-mutation.php
<?php /** Atomic native ledger writes, including writes inside an existing transaction. */ namespace Directorist\Order; defined( 'ABSPATH' ) || exit; class Mutation { private const TRANSACTION_SYNTAX = <<<'REGEX' (?(DEFINE) (?<savepoint_verb> SAVEPOINT | RELEASE (?&space) SAVEPOINT | ROLLBACK (?&space) (?: WORK (?&space) )? TO (?: (?&space) SAVEPOINT )? ) (?<name_byte> [a-z0-9_$\x80-\xff] ) (?<word_end> (?! (?&name_byte) ) ) (?<space> (?&trivia)++ ) (?<padding> (?&trivia)*+ ) (?<statement_end> (?&padding) ;? (?&padding) \z ) (?<trivia> [\x09-\x0d\x20]++ | /\* (?! ! | M! ) (?: [^*]++ | \*(?!/) )*+ \*/ | \x23 [^\n]*+ | -- (?= [\x00-\x20\x7f] ) [^\n]*+ ) ) REGEX; private const SAVEPOINT_PREFIX = '~\A (?&padding) (?&savepoint_verb) (?&word_end)' . self::TRANSACTION_SYNTAX . '~ix'; // Match complete savepoint names and distinguish ROLLBACK TO from a full rollback. private const TRANSACTION_BOUNDARY = <<<'REGEX' ~ \A (?&padding) (?: (?<savepoint_command> (?&savepoint_verb) ) (?&word_end) (?&padding) (?<name> `(?: [^`]++ | `` )*+ ` | "(?: [^"]++ | "" )*+ " | (?&name_byte)++ ) (?&statement_end) | (?<transaction> START (?&space) TRANSACTION | BEGIN | COMMIT | ROLLBACK (?! (?&space) (?: WORK (?&space) )? TO (?&word_end) ) ) (?&word_end) ) REGEX . self::TRANSACTION_SYNTAX . '~ix'; private static $active = false; private static $depth = 0; private static $sequence = 0; private static $checked = false; private static $boundary; private static $pending = []; private static $committed = []; private static $savepoints = []; public static function register_hooks() { // wpdb exposes a filter before execution, so check its result at the next // query or at shutdown for MCP and gateways that own their transactions. add_filter( 'query', [ __CLASS__, 'observe_transaction' ], PHP_INT_MAX ); add_action( 'shutdown', [ __CLASS__, 'dispatch_committed' ] ); } public static function observe_transaction( $sql ) { // Let wpdb handle canceled queries after settling the previous statement. if ( ! self::confirm_boundary( true ) || ! $sql || ! is_string( $sql ) ) { return $sql; } $parsed_sql = self::sql_for_boundary_parsing( $sql ); if ( ! preg_match( self::TRANSACTION_BOUNDARY, $parsed_sql, $match, PREG_UNMATCHED_AS_NULL ) ) { return $sql; } $depth = self::query_depth(); if ( null === $match['name'] ) { self::$boundary = [ $sql, strtoupper( $match['transaction'] ), null, $depth ]; return $sql; } $name = $match['name']; if ( '`' === $name[0] || '"' === $name[0] ) { $quote = $name[0]; $name = str_replace( $quote . $quote, $quote, substr( $name, 1, -1 ) ); } self::$boundary = [ $sql, strtoupper( $match['savepoint_command'] ), self::resolve_savepoint_key( $name ), $depth ]; return $sql; } private static function sql_for_boundary_parsing( string $sql ): string { global $wpdb; if ( ! preg_match( self::SAVEPOINT_PREFIX, $sql ) || ! preg_match( '/[\x80-\xff]/', $sql ) ) { return $sql; } $charset = self::check_result( $wpdb->get_var( 'SELECT @@character_set_client' ) ); if ( ! is_string( $charset ) || ! preg_match( '/\A[a-z0-9_]+\z/', $charset ) ) { self::check_result( false ); } if ( in_array( $charset, [ 'utf8', 'utf8mb3', 'utf8mb4' ], true ) ) { return $sql; } // Decode before reading quotes or identifiers. The observer keeps the // original SQL bytes so it can match the statement wpdb actually ran. $decode_query = $wpdb->prepare( 'SELECT HEX(CONVERT(CONVERT(UNHEX(%s) USING ' . $charset . ') USING utf8mb4))', bin2hex( $sql ) ); return hex2bin( self::check_result( $wpdb->get_var( $decode_query ) ) ); } private static function resolve_savepoint_key( string $name ): string { global $wpdb; $multibyte = '/[\x80-\xff]/'; $ascii = ! preg_match( $multibyte, $name ); $key = 'savepoint:' . ( $ascii ? strtr( $name, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz' ) : $name ); if ( isset( self::$savepoints[ $key ] ) || ! self::$savepoints ) { return $key; } $candidates = array_keys( self::$savepoints ); if ( $ascii ) { $candidates = array_values( preg_grep( $multibyte, $candidates ) ); if ( ! $candidates ) { return $key; } } // MySQL compares savepoint names using its system collation. A suffix keeps // trailing spaces significant in SQL comparisons using that collation. $names = array_map( static function ( string $candidate ): string { return bin2hex( $candidate . '.' ); }, array_merge( [ $key ], $candidates ) ); $comparisons = implode( ', ', array_fill( 0, count( $names ), 'CONVERT(UNHEX(%s) USING utf8) COLLATE utf8_general_ci' ) ); $position = (int) self::check_result( $wpdb->get_var( $wpdb->prepare( 'SELECT FIELD(' . $comparisons . ')', $names ) ) ); return $candidates[ $position - 1 ] ?? $key; } private static function query_depth(): int { global $wpdb; $depth = 0; foreach ( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS ) as $frame ) { if ( 'query' === $frame['function'] && $wpdb === ( $frame['object'] ?? null ) ) { ++$depth; } } return $depth; } private static function confirm_boundary( bool $before_query = false ): bool { global $wpdb; if ( ! self::$boundary ) { return true; } [ $sql, $command, $savepoint, $depth ] = self::$boundary; // wpdb can issue a nested charset validation query before it runs the // statement. At a new query's filter, exclude that query's own frame. if ( $depth && self::query_depth() - (int) $before_query >= $depth ) { return false; } self::$boundary = null; if ( $sql !== $wpdb->last_query || '' !== $wpdb->last_error || true !== $wpdb->result ) { return true; } if ( null !== $savepoint ) { self::confirm_savepoint( $command, $savepoint ); return true; } self::$savepoints = []; self::$active = 'COMMIT' !== $command && 'ROLLBACK' !== $command; if ( self::$active ) { return true; } if ( 'COMMIT' === $command ) { // The same key may legitimately be queued in two separate transactions. self::$committed = array_merge( self::$committed, array_values( self::$pending ) ); } self::$pending = []; return true; } private static function confirm_savepoint( string $command, string $savepoint ) { if ( 'SAVEPOINT' === $command ) { // Replacing a savepoint moves it to the end of the current transaction. unset( self::$savepoints[ $savepoint ] ); self::$savepoints[ $savepoint ] = self::$pending; return; } if ( 0 === strpos( $command, 'RELEASE' ) ) { unset( self::$savepoints[ $savepoint ] ); return; } if ( isset( self::$savepoints[ $savepoint ] ) ) { $index = array_search( $savepoint, array_keys( self::$savepoints ), true ); self::$pending = self::$savepoints[ $savepoint ]; self::$savepoints = array_slice( self::$savepoints, 0, $index + 1, true ); } } public static function in_transaction(): bool { self::confirm_boundary(); return self::$active || self::$depth > 0; } public static function after_commit( int $activity_id, callable $callback ) { self::defer_until_commit( 'order_activity:' . $activity_id, static function () use ( $activity_id, $callback ) { global $wpdb; // A savepoint rollback or lost connection can remove the activity. $exists = self::check_result( $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$wpdb->prefix}directorist_order_activities WHERE id = %d", $activity_id ) ) ); if ( (int) $exists === $activity_id ) { $callback(); } } ); } /** Queue one callback per key in the current transaction. */ public static function defer_until_commit( string $key, callable $callback ) { self::confirm_boundary(); self::$pending[ $key ] = $callback; } public static function dispatch_committed() { if ( self::in_transaction() || ! self::$committed ) { return; } $callbacks = self::$committed; self::$committed = []; foreach ( $callbacks as $callback ) { try { $callback(); } catch ( \Throwable $error ) { // A notification failure must not make a committed write look like it rolled back. error_log( 'Directorist could not dispatch a committed order notification.' ); } } } public static function run( callable $callback ) { global $wpdb; if ( 0 === self::$depth ) { // Keep the existing MCP coordinator first in the lock order. do_action( 'directorist_mcp_before_native_order_write' ); } $savepoint = 'directorist_ledger_' . ++self::$sequence; $owns = ! self::in_transaction(); $saved = false; ++self::$depth; try { self::check_storage(); if ( $owns ) { self::query( 'START TRANSACTION' ); } // InnoDB retains this mutex until the actual transaction ends, including // transactions owned by gateways. No named gateway lock is replaced on // MySQL versions that support only one advisory lock per connection. $mutex = self::check_result( $wpdb->get_var( "SELECT id FROM {$wpdb->prefix}directorist_order_locks WHERE id = 1 FOR UPDATE" ) ); if ( '1' !== (string) $mutex ) { throw new \RuntimeException( __( 'The order database upgrade is required.', 'directorist' ), 503 ); } // Acquire before the savepoint so a nested rollback keeps the mutex. if ( ! $owns ) { self::query( "SAVEPOINT {$savepoint}" ); $saved = true; } $result = $callback(); self::query( $owns ? 'COMMIT' : "RELEASE SAVEPOINT {$savepoint}" ); } catch ( \Throwable $error ) { if ( $owns ) { $wpdb->query( 'ROLLBACK' ); } elseif ( $saved ) { $wpdb->query( "ROLLBACK TO SAVEPOINT {$savepoint}" ); $wpdb->query( "RELEASE SAVEPOINT {$savepoint}" ); } wp_cache_delete( 'alloptions', 'options' ); wp_cache_delete( 'notoptions', 'options' ); throw $error; } finally { --self::$depth; } self::dispatch_committed(); return $result; } /** Persist schema version options, accepting only verified no-op saves. */ public static function save_option( string $name, $value ) { global $wpdb; update_option( $name, $value, false ); // update_option() also returns false for unchanged values. Inspect the SQL // error immediately, then verify the persisted value with a fresh read. self::check_result( null ); wp_cache_delete( $name, 'options' ); wp_cache_delete( 'alloptions', 'options' ); wp_cache_delete( 'notoptions', 'options' ); $stored = self::check_result( get_option( $name, null ) ); if ( $stored !== $value ) { throw new \RuntimeException( __( 'The order activity migration checkpoint could not be saved.', 'directorist' ), 500 ); } } public static function check_result( $result ) { global $wpdb; if ( false === $result || '' !== $wpdb->last_error ) { throw new \RuntimeException( __( 'The order update could not be saved.', 'directorist' ), 500 ); } return $result; } /** Current persisted rows, independent of a caller's repeatable-read snapshot. */ public static function locked_row( \Directorist\Utils\Database\Query\Builder $query ): ?\stdClass { global $wpdb; return self::check_result( $wpdb->get_row( $query->limit( 1 )->to_sql() . ' FOR UPDATE' ) ); } public static function locked_rows( \Directorist\Utils\Database\Query\Builder $query ): array { global $wpdb; return self::check_result( $wpdb->get_results( $query->to_sql() . ' FOR UPDATE' ) ); } private static function query( $sql ) { global $wpdb; self::check_result( $wpdb->query( $sql ) ); } private static function check_storage() { global $wpdb; if ( self::$checked ) { return; } foreach ( [ 'directorist_orders', 'directorist_payments', 'directorist_refunds', 'directorist_order_activities', 'directorist_order_locks' ] as $name ) { $engine = self::check_result( $wpdb->get_var( $wpdb->prepare( 'SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s', $wpdb->prefix . $name ) ) ); if ( 'INNODB' !== strtoupper( (string) $engine ) ) { throw new \RuntimeException( __( 'Order activities require the order database upgrade and InnoDB storage.', 'directorist' ), 503 ); } } self::$checked = true; } }
Save File
Cancel