read(); if ( null === $stored || ! empty( $stored[ self::DIRTY_FLAG_NAME ] ) ) { return $this->recalculate(); } return array( 'bytes_before' => (int) ( $stored['bytes_before'] ?? 0 ), 'bytes_after' => (int) ( $stored['bytes_after'] ?? 0 ), 'files' => (int) ( $stored['files'] ?? 0 ), ); } /** * Applies a change in totals. * * @param array{before: int, after: int, files: int} $delta Change to apply. * @return void */ public function apply( array $delta ): void { if ( 0 === $delta['before'] && 0 === $delta['after'] && 0 === $delta['files'] ) { return; } $token = $this->wait_for_lock(); if ( null === $token ) { $stored = $this->read() ?? array(); $stored[ self::DIRTY_FLAG_NAME ] = 1; $this->write( $stored ); return; } $stored = $this->read(); if ( null === $stored ) { // The rows already include this change, so a rebuild is the correct total. $this->write( $this->items->totals() ); } else { $stored['bytes_before'] = max( 0, (int) ( $stored['bytes_before'] ?? 0 ) + $delta['before'] ); $stored['bytes_after'] = max( 0, (int) ( $stored['bytes_after'] ?? 0 ) + $delta['after'] ); $stored['files'] = max( 0, (int) ( $stored['files'] ?? 0 ) + $delta['files'] ); $this->write( $stored ); } $this->lock->release( self::LOCK_NAME, $token ); } /** * Rebuilds the totals from the records table. * * @return array{bytes_before: int, bytes_after: int, files: int} */ public function recalculate(): array { $totals = $this->items->totals(); $this->write( $totals ); return $totals; } /** * Waits briefly for the totals lock. * * @return string|null Lock token. */ private function wait_for_lock(): ?string { $waited = 0; do { $token = $this->lock->acquire( self::LOCK_NAME, self::LOCK_TTL ); if ( null !== $token ) { return $token; } usleep( self::LOCK_RETRY_MS * 1000 ); $waited += self::LOCK_RETRY_MS; } while ( $waited < self::LOCK_WAIT_MS ); return null; } /** * Reads directly from the database. A long-running worker's cache may be stale. * * @return array|null */ private function read(): ?array { global $wpdb; $raw = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", self::OPTION ) ); if ( null === $raw ) { return null; } $value = maybe_unserialize( $raw ); return is_array( $value ) ? $value : null; } /** * Writes the option. * * @param array $value New value. * @return void */ private function write( array $value ): void { wp_cache_delete( self::OPTION, 'options' ); update_option( self::OPTION, $value, false ); } }