prefix . 'brverify_jobs'; } /** * Logs table name. */ public function logs_table(): string { global $wpdb; return $wpdb->prefix . 'brverify_logs'; } /** * Artifacts table name. */ public function artifacts_table(): string { global $wpdb; return $wpdb->prefix . 'brverify_artifacts'; } /** * Whether the jobs table exists. */ public function tables_exist(): bool { global $wpdb; $name = $this->table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $found = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $name ) ); return $found === $name; } /** * Count jobs by optional status. * * @param string|null $status Status filter. */ public function count( ?string $status = null ): int { global $wpdb; $table = $this->table(); if ( null === $status ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE status = %s', $table, $status ) ); } /** * Insert a pending job. * * @param string $type Job type. * @param array $config Config payload. * @return int Insert id. */ public function create( string $type, array $config = array() ): int { global $wpdb; $now = current_time( 'mysql' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->insert( $this->table(), array( 'type' => $type, 'status' => Job_States::STATUS_PENDING, 'phase' => Job_States::PHASE_INIT, 'progress_pct' => 0, 'config_json' => wp_json_encode( $config ), 'cursor_json' => wp_json_encode( array() ), 'created_at' => $now, 'updated_at' => $now, ), array( '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s' ) ); return (int) $wpdb->insert_id; } /** * Fetch one job by id. * * @param int $id Job id. * @return array|null */ public function get( int $id ): ?array { global $wpdb; $table = $this->table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $id ), ARRAY_A ); return is_array( $row ) ? $this->hydrate( $row ) : null; } /** * List recent jobs. * * @param int $limit Max rows. * @return list> */ public function list_recent( int $limit = 20 ): array { global $wpdb; $table = $this->table(); $limit = max( 1, min( 100, $limit ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i ORDER BY id DESC LIMIT %d', $table, $limit ), ARRAY_A ); if ( ! is_array( $rows ) ) { return array(); } return array_map( array( $this, 'hydrate' ), $rows ); } /** * Claim a specific job or the next pending/stale running job. * * @param string $locked_by Locker identity. * @param int|null $job_id Optional specific job. * @return array|null */ public function claim( string $locked_by, ?int $job_id = null ): ?array { global $wpdb; $table = $this->table(); $now = current_time( 'mysql' ); $stale_cut = gmdate( 'Y-m-d H:i:s', time() - self::STALE_SECONDS - (int) round( (float) get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ); // Use site-local comparable cutoff via current_time math. $stale_local = gmdate( 'Y-m-d H:i:s', current_time( 'timestamp' ) - self::STALE_SECONDS ); if ( null !== $job_id ) { $job = $this->get( $job_id ); if ( null === $job ) { return null; } $status = (string) $job['status']; if ( ! in_array( $status, array( Job_States::STATUS_PENDING, Job_States::STATUS_RUNNING ), true ) ) { return null; } $candidates = array( $job ); } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE status IN (%s, %s) AND ( locked_at IS NULL OR heartbeat_at IS NULL OR heartbeat_at < %s ) ORDER BY id ASC LIMIT 5', $table, Job_States::STATUS_PENDING, Job_States::STATUS_RUNNING, $stale_local ), ARRAY_A ); $candidates = is_array( $rows ) ? $rows : array(); } foreach ( $candidates as $raw ) { $row = is_array( $raw ) && isset( $raw['cursor'] ) ? $raw : $this->hydrate( $raw ); $id = (int) $row['id']; $was_pending = Job_States::STATUS_PENDING === (string) $row['status']; $data = array( 'status' => Job_States::STATUS_RUNNING, 'locked_at' => $now, 'locked_by' => $locked_by, 'heartbeat_at' => $now, 'updated_at' => $now, 'attempts' => (int) $row['attempts'] + ( $was_pending ? 0 : 1 ), ); $formats = array( '%s', '%s', '%s', '%s', '%s', '%d' ); if ( $was_pending || empty( $row['started_at'] ) ) { $data['started_at'] = $now; $formats[] = '%s'; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $updated = $wpdb->update( $table, $data, array( 'id' => $id, 'status' => (string) $row['status'], ), $formats, array( '%d', '%s' ) ); if ( $updated ) { return $this->get( $id ); } } return null; } /** * Persist tick result fields. * * @param int $id Job id. * @param array $fields status, phase, progress_pct, cursor, result, error_message. */ public function update_progress( int $id, array $fields ): void { global $wpdb; $data = array( 'updated_at' => current_time( 'mysql' ) ); $formats = array( '%s' ); if ( isset( $fields['status'] ) ) { $data['status'] = (string) $fields['status']; $formats[] = '%s'; } if ( isset( $fields['phase'] ) ) { $data['phase'] = (string) $fields['phase']; $formats[] = '%s'; } if ( isset( $fields['progress_pct'] ) ) { $data['progress_pct'] = max( 0, min( 100, (int) $fields['progress_pct'] ) ); $formats[] = '%d'; } if ( isset( $fields['cursor'] ) && is_array( $fields['cursor'] ) ) { $data['cursor_json'] = self::encode_guarded( $fields['cursor'], 'cursor' ); $formats[] = '%s'; } if ( isset( $fields['result'] ) && is_array( $fields['result'] ) ) { $data['result_json'] = self::encode_guarded( $fields['result'], 'result' ); $formats[] = '%s'; } if ( array_key_exists( 'error_message', $fields ) ) { $data['error_message'] = null === $fields['error_message'] ? null : (string) $fields['error_message']; $formats[] = '%s'; } if ( ! empty( $fields['heartbeat'] ) ) { $data['heartbeat_at'] = current_time( 'mysql' ); $formats[] = '%s'; } if ( ! empty( $fields['finished'] ) ) { $data['finished_at'] = current_time( 'mysql' ); $data['locked_at'] = null; $data['locked_by'] = null; $formats[] = '%s'; $formats[] = '%s'; $formats[] = '%s'; } if ( isset( $data['error_message'] ) && is_string( $data['error_message'] ) && strlen( $data['error_message'] ) > 4000 ) { $data['error_message'] = substr( $data['error_message'], 0, 4000 ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $ok = $wpdb->update( $this->table(), $data, array( 'id' => $id ), $formats, array( '%d' ) ); if ( false === $ok ) { $db_error = (string) $wpdb->last_error; throw new Job_State_Exception( esc_html( sprintf( /* translators: %s: database error */ __( 'Could not save job progress to the database: %s', '007aj-backup-restore-verifier' ), '' !== $db_error ? $db_error : __( 'unknown database error', '007aj-backup-restore-verifier' ) ) ) ); } } /** * Encode job state JSON with a hard size limit. * * Large working state (file lists, indexes, checksums) belongs in protected * working files; the job row only carries small progress data. Exceeding the * limit is a programming error and fails the job with a clear message instead * of hitting the database packet limit. * * @param array $value Value. * @param string $what Label. * @throws Job_State_Exception When the encoded value is too large. */ public static function encode_guarded( array $value, string $what ): string { $json = wp_json_encode( $value ); if ( ! is_string( $json ) ) { throw new Job_State_Exception( esc_html( sprintf( /* translators: %s: cursor or result */ __( 'Job %s could not be encoded as JSON.', '007aj-backup-restore-verifier' ), $what ) ) ); } if ( strlen( $json ) > self::MAX_STATE_BYTES ) { $keys = array(); foreach ( $value as $k => $v ) { $len = strlen( (string) wp_json_encode( $v ) ); if ( $len > 2048 ) { $keys[] = $k . ' (' . size_format( $len ) . ')'; } } throw new Job_State_Exception( esc_html( sprintf( /* translators: 1: cursor or result, 2: size, 3: limit, 4: key list */ __( 'Job %1$s is too large to store (%2$s, limit %3$s). Largest keys: %4$s', '007aj-backup-restore-verifier' ), $what, size_format( strlen( $json ) ), size_format( self::MAX_STATE_BYTES ), implode( ', ', $keys ) ) ) ); } return $json; } /** * Heartbeat only. * * @param int $id Job id. */ public function heartbeat( int $id ): void { global $wpdb; $now = current_time( 'mysql' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->update( $this->table(), array( 'heartbeat_at' => $now, 'updated_at' => $now, ), array( 'id' => $id ), array( '%s', '%s' ), array( '%d' ) ); } /** * Insert an artifact row. * * @param int $job_id Job id. * @param array $data path, bytes, sha256, adapter, remote_ref, part_index, meta. * @return int Insert id. */ public function add_artifact( int $job_id, array $data ): int { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->insert( $this->artifacts_table(), array( 'job_id' => $job_id, 'path' => (string) ( $data['path'] ?? '' ), 'part_index' => (int) ( $data['part_index'] ?? 0 ), 'bytes' => (int) ( $data['bytes'] ?? 0 ), 'sha256' => isset( $data['sha256'] ) ? (string) $data['sha256'] : null, 'adapter' => (string) ( $data['adapter'] ?? 'local' ), 'remote_ref' => isset( $data['remote_ref'] ) ? (string) $data['remote_ref'] : null, 'meta_json' => isset( $data['meta'] ) ? wp_json_encode( $data['meta'] ) : null, 'created_at' => current_time( 'mysql' ), ), array( '%d', '%s', '%d', '%d', '%s', '%s', '%s', '%s', '%s' ) ); return (int) $wpdb->insert_id; } /** * Merge keys into an artifact's meta_json (used to enrich pre-update metadata). * * @param int $id Artifact id. * @param array $patch Keys to merge. */ public function update_artifact_meta( int $id, array $patch ): bool { global $wpdb; $art = $this->get_artifact( $id ); if ( null === $art ) { return false; } $meta = array(); if ( isset( $art['meta_json'] ) && is_string( $art['meta_json'] ) && '' !== $art['meta_json'] ) { $decoded = json_decode( $art['meta_json'], true ); $meta = is_array( $decoded ) ? $decoded : array(); } $meta = array_merge( $meta, $patch ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $updated = $wpdb->update( $this->artifacts_table(), array( 'meta_json' => wp_json_encode( $meta ) ), array( 'id' => $id ), array( '%s' ), array( '%d' ) ); return false !== $updated; } /** * Artifacts for a job. * * @param int $job_id Job id. * @return list> */ public function artifacts_for_job( int $job_id ): array { global $wpdb; $table = $this->artifacts_table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE job_id = %d ORDER BY part_index ASC, id ASC', $table, $job_id ), ARRAY_A ); return is_array( $rows ) ? $rows : array(); } /** * Get artifact by id. * * @param int $id Artifact id. * @return array|null */ public function get_artifact( int $id ): ?array { global $wpdb; $table = $this->artifacts_table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $id ), ARRAY_A ); return is_array( $row ) ? $row : null; } /** * List recent local artifacts. * * @param int $limit Max. * @return list> */ public function list_artifacts( int $limit = 20 ): array { global $wpdb; $table = $this->artifacts_table(); $limit = max( 1, min( 100, $limit ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i ORDER BY id DESC LIMIT %d', $table, $limit ), ARRAY_A ); return is_array( $rows ) ? $rows : array(); } /** * List local artifacts oldest-first (for retention prune). * * @param int $limit Max rows. * @return list> */ public function list_artifacts_oldest_first( int $limit = 500 ): array { global $wpdb; $table = $this->artifacts_table(); $limit = max( 1, min( 1000, $limit ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i ORDER BY id ASC LIMIT %d', $table, $limit ), ARRAY_A ); return is_array( $rows ) ? $rows : array(); } /** * Count artifacts. */ public function count_artifacts(): int { global $wpdb; $table = $this->artifacts_table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); } /** * Delete an artifact row by id. * * @param int $id Artifact id. */ public function delete_artifact( int $id ): bool { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $deleted = $wpdb->delete( $this->artifacts_table(), array( 'id' => $id ), array( '%d' ) ); return false !== $deleted && $deleted > 0; } /** * Whether another backup/restore is already active. */ public function has_active_heavy_job( ?int $except_id = null ): bool { global $wpdb; $table = $this->table(); $sql = "SELECT id FROM {$table} WHERE type IN (%s, %s) AND status IN (%s, %s)"; $args = array( Job_States::TYPE_BACKUP, Job_States::TYPE_RESTORE, Job_States::STATUS_PENDING, Job_States::STATUS_RUNNING, ); if ( null !== $except_id ) { $sql .= ' AND id != %d'; $args[] = $except_id; } $sql .= ' LIMIT 1'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared $found = $wpdb->get_var( $wpdb->prepare( $sql, $args ) ); return null !== $found && '' !== $found; } /** * Decode JSON columns onto the row. * * @param array $row Raw row. * @return array */ private function hydrate( array $row ): array { $row['id'] = (int) $row['id']; $row['progress_pct'] = (int) ( $row['progress_pct'] ?? 0 ); $row['attempts'] = (int) ( $row['attempts'] ?? 0 ); $row['cursor'] = $this->decode_json( $row['cursor_json'] ?? null ); $row['config'] = $this->decode_json( $row['config_json'] ?? null ); $row['result'] = $this->decode_json( $row['result_json'] ?? null ); return $row; } /** * @param mixed $json JSON string or null. * @return array */ private function decode_json( $json ): array { if ( ! is_string( $json ) || '' === $json ) { return array(); } $decoded = json_decode( $json, true ); return is_array( $decoded ) ? $decoded : array(); } }