From e1aeed39653015b312e91efcbd41cdccd134e83c Mon Sep 17 00:00:00 2001 From: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:20:03 -0800 Subject: [PATCH] Add wp spacefast WP-CLI commands Add status, publish, build, sync-settings and disconnect commands so hosts, agencies and deploy scripts can publish without wp-admin. The manual admin actions move into shared methods that the admin handlers and the CLI both call, so wp-admin behavior is unchanged. publish --wait and build --wait block until the version is live or the build succeeds and exit non-zero on failure or timeout. With --wait, Simply Static's export tasks run inline, so a publish finishes without WP-Cron. The inline worker yields between tasks but keeps Simply Static's own limits inside a task, since fetch_urls checks should_continue before every page. --- README.md | 36 +++ bin/test-wordpress.sh | 6 + includes/class-spacefast-cli-export-job.php | 52 +++++ includes/class-spacefast-cli.php | 241 ++++++++++++++++++++ includes/class-spacefast-plugin.php | 63 +++-- readme.txt | 23 +- spacefast-wordpress.php | 8 +- tests/acceptance/wordpress.php | 95 +++++++- tests/behavior.php | 214 ++++++++++++++++- 9 files changed, 716 insertions(+), 22 deletions(-) create mode 100644 includes/class-spacefast-cli-export-job.php create mode 100644 includes/class-spacefast-cli.php diff --git a/README.md b/README.md index 3402c40..2e4c4d0 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,42 @@ Automatic publishing is on by default. Site and content changes share the same 60-second quiet window, and settings are synced immediately before the next publish or build. These defaults can be changed under **WordPress sync**. +## Command line + +After connecting a Team and Space in **Settings → Spacefast**, run these commands +from your WordPress installation: + +```bash +wp spacefast status +wp spacefast status --format=json +wp spacefast publish --wait --timeout=600 +wp spacefast build --wait +wp spacefast sync-settings +wp spacefast disconnect --yes +``` + +`publish` starts a full Simply Static export in Static WordPress mode. With +`--wait`, the free Simply Static worker runs its queued tasks inline, including +Spacefast delivery, without WP-Cron or loopback AJAX. It waits for the requested +version to become live (or an unchanged export). `build` starts a production +repository build in Headless CMS mode; `--wait` waits for the requested build to +succeed, including a queued successor if another build was already running. +Without `--wait`, both commands return after requesting background delivery. + +The default wait limit is 600 seconds. `publish --timeout=` accepts a positive +integer and sets that limit; it is checked between tasks and HTTP requests, so an +in-flight step may finish after the deadline. Failure or timeout exits non-zero. +Timeout leaves queued work available to the normal background worker. Paused or +canceled exports fail the wait. Custom Simply Static workers must support the +inline adapter; unsupported workers report an error before starting a wait. + +`status` reports local connection, mode, Team, Space, live URL, version/build +receipts, delivery state, and whether changes remain pending. JSON output is a +single object and never includes OAuth credentials. Status does not refresh the +remote state. `sync-settings` honors the WordPress sync preferences for title, +description, search visibility, and the headless source. `disconnect` prompts +unless `--yes` is supplied. Use WP-CLI's `--url=` to select a multisite site. + ## Operate and remove The settings page leads with the authoritative live/publishing state, live URL, diff --git a/bin/test-wordpress.sh b/bin/test-wordpress.sh index 9298e71..bfcc740 100755 --- a/bin/test-wordpress.sh +++ b/bin/test-wordpress.sh @@ -18,3 +18,9 @@ docker compose --project-name "${project_name}" --file "${compose_file}" run --r wp plugin activate spacefast-wordpress docker compose --project-name "${project_name}" --file "${compose_file}" run --rm wpcli \ wp eval-file wp-content/plugins/spacefast-wordpress/tests/acceptance/wordpress.php +docker compose --project-name "${project_name}" --file "${compose_file}" run --rm wpcli \ + wp config set DISABLE_WP_CRON true --raw +docker compose --project-name "${project_name}" --file "${compose_file}" run --rm wpcli \ + wp plugin install simply-static --version=3.8.0 --activate +docker compose --project-name "${project_name}" --file "${compose_file}" run --rm wpcli \ + wp eval-file wp-content/plugins/spacefast-wordpress/tests/acceptance/wordpress.php cli diff --git a/includes/class-spacefast-cli-export-job.php b/includes/class-spacefast-cli-export-job.php new file mode 100644 index 0000000..b320f37 --- /dev/null +++ b/includes/class-spacefast-cli-export-job.php @@ -0,0 +1,52 @@ +set_current_site_id( get_current_blog_id() ); + if ( $this->is_paused() || $this->is_cancelled() ) { + throw new RuntimeException( 'Simply Static export was paused or canceled.' ); + } + if ( $this->is_processing() ) return false; + $options = \Simply_Static\Options::reinstance(); + $this->set_options( $options ); + \Simply_Static\Plugin::instance()->set_options( $options ); + if ( ! $this->is_queued() ) return false; + // The worker persists each step and releases its own lock. Yield between + // tasks so the caller can enforce its deadline and back off API polling. + // Tasks such as fetch_urls also ask should_continue before every page, + // so keep Simply Static's own time and memory limits while a task runs + // and stop only once it returns; a blanket false would fetch no pages. + $this->task_finished = false; + $yield = fn( $continue ): bool => (bool) $continue && ! $this->task_finished; + add_filter( 'wp_archive_creation_job_should_continue', $yield ); + try { + $this->handle(); + } finally { + remove_filter( 'wp_archive_creation_job_should_continue', $yield ); + } + return true; + } + + /** @param mixed $item Queued task name. */ + protected function task( $item ) { + try { + return parent::task( $item ); + } finally { + $this->task_finished = true; + } + } +} diff --git a/includes/class-spacefast-cli.php b/includes/class-spacefast-cli.php new file mode 100644 index 0000000..460ace0 --- /dev/null +++ b/includes/class-spacefast-cli.php @@ -0,0 +1,241 @@ +] + * : Output format. + * --- + * default: table + * options: + * - table + * - json + * --- + */ + public function status( array $args, array $assoc_args ): void { + $format = $assoc_args['format'] ?? 'table'; + if ( ! in_array( $format, array( 'table', 'json' ), true ) ) { + WP_CLI::error( 'Format must be table or json.' ); + } + $settings = Spacefast_Settings::get(); + $state = Spacefast_Sync_State::get(); + // Explicit allowlist: never serialize the settings option (it holds tokens). + $status = array( + 'connection' => Spacefast_Settings::configured() ? 'connected' : ( Spacefast_Settings::selected() ? 'unverified' : 'disconnected' ), + 'mode' => Spacefast_Settings::mode(), + 'team_id' => $settings['team_id'], + 'team' => $settings['team_name'], + 'space_id' => $settings['space_id'], + 'space' => $settings['space_name'], + 'last_version_id' => $state['last_version_id'], + 'last_build_id' => $state['last_build_id'], + 'live_url' => $settings['live_url'], + 'state' => $state['last_status'], + 'pending' => (int) $state['desired'] > (int) $state['delivered'], + ); + if ( 'json' === $format ) { + WP_CLI::line( wp_json_encode( $status ) ); + return; + } + $rows = array(); + foreach ( $status as $field => $value ) { + $rows[] = array( 'field' => $field, 'value' => is_bool( $value ) ? ( $value ? 'yes' : 'no' ) : $value ); + } + \WP_CLI\Utils\format_items( 'table', $rows, array( 'field', 'value' ) ); + } + + /** + * Start a full Simply Static export and deliver it to Spacefast. + * + * ## OPTIONS + * + * [--wait] + * : Run export tasks inline and wait for the version to become live. + * + * [--timeout=] + * : Maximum wait in seconds, checked between tasks and HTTP requests. + * --- + * default: 600 + * --- + */ + public function publish( array $args, array $assoc_args ): void { + $timeout = $this->timeout( $assoc_args ); + $wait = isset( $assoc_args['wait'] ); + $job = null; + if ( $wait && Spacefast_Plugin::simply_static_available() ) { + $job = \Simply_Static\Plugin::instance()->get_archive_creation_job(); + if ( ! $job instanceof Spacefast_CLI_Export_Job ) { + WP_CLI::error( 'This Simply Static worker does not support inline export. Update Simply Static or publish without --wait.' ); + } + Spacefast_CLI_Export_Job::$inline = true; + } + $error = null; + // Simply Static fires this only after accepting a new export. Clear + // leftover Pro/404 scope flags without altering an already active export. + $full_export = static function (): void { + delete_option( 'simply-static-use-single' ); + delete_option( 'simply-static-use-build' ); + delete_option( 'simply-static-404-only' ); + }; + add_action( 'ss_before_static_export', $full_export, PHP_INT_MAX ); + try { + $deadline = microtime( true ) + $timeout; + $result = Spacefast_Plugin::do_manual_static_publish(); + if ( ! $result['ok'] ) throw new RuntimeException( $result['message'] ); + if ( $wait ) $this->wait( (int) $result['generation'], $deadline, $job ); + } catch ( Throwable $failure ) { + $error = $failure->getMessage(); + } finally { + remove_action( 'ss_before_static_export', $full_export, PHP_INT_MAX ); + if ( $job instanceof Spacefast_CLI_Export_Job ) { + Spacefast_CLI_Export_Job::$inline = false; + // On timeout, leave a durable background job that can resume normally. + if ( $job->is_queued() ) $job->dispatch(); + } + } + if ( null !== $error ) WP_CLI::error( $error ); + WP_CLI::success( $wait ? 'Publish is live (or already up to date).' : $result['message'] ); + } + + /** + * Trigger the headless production build now. + * + * ## OPTIONS + * + * [--wait] + * : Wait up to 600 seconds for the requested build to succeed. + */ + public function build( array $args, array $assoc_args ): void { + try { + $deadline = microtime( true ) + 600; + $result = Spacefast_Plugin::do_manual_build(); + if ( ! $result['ok'] ) throw new RuntimeException( $result['message'] ); + if ( isset( $assoc_args['wait'] ) ) $this->wait( (int) $result['generation'], $deadline ); + } catch ( Throwable $error ) { + WP_CLI::error( $error->getMessage() ); + } + WP_CLI::success( isset( $assoc_args['wait'] ) ? 'Build succeeded.' : $result['message'] ); + } + + /** + * Push the WordPress settings enabled under WordPress sync. + * + * @subcommand sync-settings + */ + public function sync_settings( array $args, array $assoc_args ): void { + try { + $result = Spacefast_Plugin::do_manual_settings_sync(); + if ( ! $result['ok'] ) throw new RuntimeException( $result['message'] ); + } catch ( Throwable $error ) { + WP_CLI::error( $error->getMessage() ); + } + WP_CLI::success( 'WordPress settings synced to the Space.' ); + } + + /** + * Revoke refresh access and remove the local connection and pending work. + * + * ## OPTIONS + * + * [--yes] + * : Skip the confirmation prompt. + */ + public function disconnect( array $args, array $assoc_args ): void { + WP_CLI::confirm( 'Disconnect this WordPress site from Spacefast?', $assoc_args ); + try { + Spacefast_Plugin::do_disconnect(); + } catch ( Throwable $error ) { + WP_CLI::error( $error->getMessage() ); + } + WP_CLI::success( 'Spacefast disconnected.' ); + } + + private function timeout( array $assoc_args ): int { + $value = $assoc_args['timeout'] ?? '600'; + $timeout = filter_var( $value, FILTER_VALIDATE_INT, array( 'options' => array( 'min_range' => 1 ) ) ); + if ( false === $timeout ) WP_CLI::error( 'Timeout must be a positive integer in seconds.' ); + return $timeout; + } + + private function wait( int $generation, float $deadline, ?Spacefast_CLI_Export_Job $job = null ): void { + $delay = 1; + while ( true ) { + // A long-running CLI request must see updates from other workers. + wp_cache_delete( Spacefast_Sync_State::OPTION, 'options' ); + wp_cache_delete( Spacefast_Settings::OPTION, 'options' ); + $state = Spacefast_Sync_State::get(); + if ( 'blocked' === $state['last_status'] ) { + throw new RuntimeException( $state['last_message'] ?: 'Delivery failed.' ); + } + $completed = (int) $state['delivered'] >= $generation + && ( in_array( $state['last_status'], array( 'live', 'unchanged' ), true ) + || ( null === $job && 'pending' === $state['last_status'] ) ); + if ( $completed && ( null === $job || ! $job->is_queued() ) ) return; + if ( microtime( true ) >= $deadline ) { + throw new RuntimeException( 'Timed out waiting for Spacefast. Delivery may continue in the background; check wp spacefast status.' ); + } + if ( ! Spacefast_Settings::selected() ) throw new RuntimeException( 'Spacefast was disconnected while waiting.' ); + if ( + '' !== $state['last_version_id'] + && ( 'ready' === $state['last_status'] + || ( null !== $job && 'pending' === $state['last_status'] && (int) $state['delivered'] >= $generation ) ) + ) { + $version = ( new Spacefast_Client() )->get_static_version( $state['last_version_id'] ); + if ( ! $version['ok'] && ! $version['retryable'] ) throw new RuntimeException( $version['message'] ); + if ( $version['ok'] ) { + $status = $version['data']['status'] ?? ''; + if ( in_array( $status, array( 'failed', 'canceled', 'expired' ), true ) ) { + throw new RuntimeException( 'Spacefast could not activate the version.' ); + } + if ( 'ready' === $status && true === ( $version['data']['isCurrentProduction'] ?? false ) ) { + Spacefast_Sync_State::mutate( + static function ( array $current ) use ( $state ): array { + if ( $current['last_version_id'] === $state['last_version_id'] && 'ready' === $current['last_status'] ) $current['last_status'] = 'live'; + return $current; + } + ); + Spacefast_Settings::merge( array( 'verified_at' => time() ) ); + $completed = (int) $state['delivered'] >= $generation; + if ( $completed && ( null === $job || ! $job->is_queued() ) ) return; + } + } + } + $advanced = false; + if ( null !== $job ) { + $advanced = $job->run_step(); + if ( ! $job->is_queued() && ! $job->is_processing() && ! $completed ) { + $after = Spacefast_Sync_State::get(); + if ( in_array( $after['last_status'], array( 'exporting', 'uploading', 'finalizing' ), true ) ) { + throw new RuntimeException( 'Simply Static stopped before delivery completed. Check its export log.' ); + } + } + } + if ( ! $advanced && ! $completed && (int) $state['next_at'] <= time() ) Spacefast_Plugin::deliver(); + $publish = get_option( Spacefast_Static_Publisher::OPTION, array() ); + if ( $advanced && 'finalizing' !== ( $publish['phase'] ?? '' ) && (int) ( $publish['retry_at'] ?? 0 ) <= time() ) { + $delay = 1; + continue; + } + usleep( (int) ( min( $delay, max( 0, $deadline - microtime( true ) ) ) * 1000000 ) ); + $delay = min( 15, $delay * 2 ); + } + } +} + +// Installed before init constructs Simply Static's worker. Ordinary CLI exports +// keep background dispatch; only `spacefast publish --wait` enables inline work. +add_filter( + 'ss_archive_creation_job_class', + static function ( string $class ): string { + if ( 'Simply_Static\\Archive_Creation_Job' !== ltrim( $class, '\\' ) ) return $class; + require_once __DIR__ . '/class-spacefast-cli-export-job.php'; + return Spacefast_CLI_Export_Job::class; + } +); +WP_CLI::add_command( 'spacefast', Spacefast_CLI::class ); diff --git a/includes/class-spacefast-plugin.php b/includes/class-spacefast-plugin.php index c1d35a8..900d042 100644 --- a/includes/class-spacefast-plugin.php +++ b/includes/class-spacefast-plugin.php @@ -348,12 +348,16 @@ public static function change_space(): void { public static function disconnect(): void { self::assert_admin( 'spacefast_wordpress_disconnect' ); - ( new Spacefast_OAuth() )->revoke(); - Spacefast_Settings::disconnect(); + self::do_disconnect(); self::notice( 'success', __( 'Spacefast disconnected and its refresh access was revoked.', 'spacefast-wordpress' ) ); self::redirect(); } + public static function do_disconnect(): void { + ( new Spacefast_OAuth() )->revoke(); + Spacefast_Settings::disconnect(); + } + public static function test_connection(): void { self::assert_admin( 'spacefast_wordpress_test' ); $result = ( new Spacefast_Client() )->health(); @@ -370,30 +374,54 @@ public static function test_connection(): void { public static function manual_build(): void { self::assert_admin( 'spacefast_wordpress_build' ); + $result = self::do_manual_build(); + if ( ! $result['ok'] ) self::notice( 'error', $result['message'] ); + self::redirect(); + } + + /** @return array{ok:bool,message:string,generation?:int} */ + public static function do_manual_build(): array { if ( Spacefast_Settings::MODE_HEADLESS !== Spacefast_Settings::mode() ) { - self::notice( 'error', __( 'Switch to Headless CMS to trigger repository builds.', 'spacefast-wordpress' ) ); - self::redirect(); + return array( 'ok' => false, 'message' => __( 'Switch to Headless CMS to trigger repository builds.', 'spacefast-wordpress' ) ); + } + if ( ! Spacefast_Settings::selected() ) { + return array( 'ok' => false, 'message' => __( 'Connect Spacefast and choose a Space first.', 'spacefast-wordpress' ) ); } self::record_change( 'manual', true ); + $generation = (int) Spacefast_Sync_State::get()['desired']; wp_clear_scheduled_hook( Spacefast_Sync_State::HOOK ); self::deliver(); - self::redirect(); + $state = Spacefast_Sync_State::get(); + return array( + 'ok' => ! in_array( $state['last_status'], array( 'blocked', 'retrying' ), true ), + 'message' => (string) $state['last_message'] ?: __( 'Build requested.', 'spacefast-wordpress' ), + 'generation' => $generation, + ); } public static function manual_static_publish(): void { self::assert_admin( 'spacefast_wordpress_publish' ); + $result = self::do_manual_static_publish(); + self::notice( $result['ok'] ? 'success' : 'error', $result['message'] ); + self::redirect(); + } + + /** @return array{ok:bool,message:string,generation?:int} */ + public static function do_manual_static_publish(): array { if ( Spacefast_Settings::MODE_STATIC !== Spacefast_Settings::mode() ) { - self::notice( 'error', __( 'Switch to Static WordPress to publish an export.', 'spacefast-wordpress' ) ); - self::redirect(); + return array( 'ok' => false, 'message' => __( 'Switch to Static WordPress to publish an export.', 'spacefast-wordpress' ) ); + } + if ( ! Spacefast_Settings::selected() ) { + return array( 'ok' => false, 'message' => __( 'Connect Spacefast and choose a Space first.', 'spacefast-wordpress' ) ); } if ( ! self::simply_static_available() ) { - self::notice( 'error', __( 'Install and activate Simply Static before publishing.', 'spacefast-wordpress' ) ); - self::redirect(); + return array( 'ok' => false, 'message' => __( 'Install and activate Simply Static before publishing.', 'spacefast-wordpress' ) ); } $before = Spacefast_Sync_State::get(); $was_active = self::static_delivery_active( $before ); $previous_attempt = (int) $before['last_attempt_at']; self::record_change( 'manual', true ); + $generation = (int) Spacefast_Sync_State::get()['desired']; wp_clear_scheduled_hook( Spacefast_Sync_State::HOOK ); self::deliver(); $state = Spacefast_Sync_State::get(); @@ -405,11 +433,7 @@ public static function manual_static_publish(): void { ? __( 'A publish is already running. Your latest changes will publish next.', 'spacefast-wordpress' ) : ( (string) $state['last_message'] ?: __( 'The publish could not start. The current live version is safe.', 'spacefast-wordpress' ) ) ); - self::notice( - $active ? 'success' : 'error', - $message - ); - self::redirect(); + return array( 'ok' => $active, 'message' => $message, 'generation' => $generation ); } public static function save_settings(): void { @@ -435,8 +459,7 @@ public static function save_settings(): void { public static function manual_settings_sync(): void { self::assert_admin( 'spacefast_wordpress_sync_settings' ); - self::mark_settings_pending(); - $result = self::sync_space_settings(); + $result = self::do_manual_settings_sync(); self::notice( $result['ok'] ? 'success' : 'error', $result['ok'] @@ -446,6 +469,12 @@ public static function manual_settings_sync(): void { self::redirect(); } + /** @return array{ok:bool,retryable:bool,code:string,message:string,data:array} */ + public static function do_manual_settings_sync(): array { + self::mark_settings_pending(); + return self::sync_space_settings(); + } + public static function wordpress_setting_changed(): void { $settings = Spacefast_Settings::get(); if ( empty( $settings['automatic_sync'] ) || ! Spacefast_Settings::selected() ) return; @@ -617,7 +646,7 @@ public static function user_changed(): void { private static function record_change( string $reason, bool $force = false ): void { if ( - self::$change_recorded + ( self::$change_recorded && ! $force ) || ! Spacefast_Settings::selected() || ( ! $force && empty( Spacefast_Settings::get()['automatic_sync'] ) ) ) { diff --git a/readme.txt b/readme.txt index a4ceb22..d759c2b 100644 --- a/readme.txt +++ b/readme.txt @@ -3,7 +3,7 @@ Contributors: spacefast Tags: static site, headless cms, simply static, deployment Requires at least: 6.5 Requires PHP: 8.1 -Stable tag: 0.5.8 +Stable tag: 0.6.0 License: GPLv2 or later Publish a Simply Static export to Spacefast, or rebuild a headless site when WordPress content changes. @@ -25,12 +25,33 @@ Both modes include a manual action in Settings > Spacefast. Headless repository 4. Back in WordPress, create a Space with the suggested name or choose an existing one. 5. Wait for the first version to publish. The plugin shows the live URL when it is ready. +== Command line == + +Connect a Team and Space under Settings > Spacefast first, then use WP-CLI: + +* `wp spacefast status [--format=table|json]` reports local connection and delivery state without credentials. +* `wp spacefast publish [--wait] [--timeout=600]` starts a full Simply Static export in Static WordPress mode. +* `wp spacefast build [--wait]` requests a production repository build in Headless CMS mode. +* `wp spacefast sync-settings` pushes the settings enabled under WordPress sync. +* `wp spacefast disconnect [--yes]` revokes refresh access and clears the local connection. + +With --wait, export tasks run inline using free Simply Static, without WP-Cron. +Publish waits for a live version or an unchanged export; build waits for success. +Both wait up to 600 seconds by default and exit non-zero on failure or timeout. +Publish accepts a positive integer timeout, checked between tasks and HTTP requests. +Timed-out work may continue in the background. Status reports saved state without +contacting Spacefast. Use --url= to select a site on multisite. + == Security == OAuth access is limited to the Team you authorize and the mode you choose. WordPress syncs only the selected Space and waits for a real first publish or build before showing the connection as complete. Tokens are stored in non-autoloaded options and are never displayed. == Changelog == += 0.6.0 = +* Add wp spacefast status, publish, build, sync-settings, and disconnect commands. +* Share manual delivery actions with wp-admin and support bounded CLI waits with inline Simply Static processing. + = 0.5.8 = * Retry transient upload and upload-refresh failures in place, with exponential backoff for about four minutes, instead of restarting the whole export as a new version. * Once every file has uploaded, ask Spacefast which files it still lacks, upload any it names, and let that check trigger activation instead of depending on the upload-completion signal alone. diff --git a/spacefast-wordpress.php b/spacefast-wordpress.php index 8b775fd..23921bb 100644 --- a/spacefast-wordpress.php +++ b/spacefast-wordpress.php @@ -3,7 +3,7 @@ * Plugin Name: Spacefast * Plugin URI: https://spacefast.com/ * Description: Publishes static WordPress exports or rebuilds a headless Spacefast site. - * Version: 0.5.8 + * Version: 0.6.0 * Update URI: https://github.com/spacefast/wordpress * Requires at least: 6.5 * Requires PHP: 8.1 @@ -14,7 +14,7 @@ defined( 'ABSPATH' ) || exit; -define( 'SPACEFAST_WORDPRESS_VERSION', '0.5.8' ); +define( 'SPACEFAST_WORDPRESS_VERSION', '0.6.0' ); define( 'SPACEFAST_WORDPRESS_FILE', __FILE__ ); require_once __DIR__ . '/includes/class-spacefast-settings.php'; @@ -25,6 +25,10 @@ require_once __DIR__ . '/includes/class-spacefast-static-publisher.php'; require_once __DIR__ . '/includes/class-spacefast-plugin.php'; +if ( defined( 'WP_CLI' ) && WP_CLI ) { + require_once __DIR__ . '/includes/class-spacefast-cli.php'; +} + register_activation_hook( __FILE__, array( 'Spacefast_Plugin', 'activate' ) ); register_deactivation_hook( __FILE__, array( 'Spacefast_Plugin', 'deactivate' ) ); diff --git a/tests/acceptance/wordpress.php b/tests/acceptance/wordpress.php index 4572378..d1d8589 100644 --- a/tests/acceptance/wordpress.php +++ b/tests/acceptance/wordpress.php @@ -10,6 +10,11 @@ function spacefast_accept( bool $condition, string $message ): void { } } +if ( 'cli' === ( $args[0] ?? '' ) ) { + spacefast_accept_cli(); + return; +} + global $wp_version; spacefast_accept( str_starts_with( $wp_version, '6.5.' ), 'Acceptance is not running WordPress 6.5.' ); spacefast_accept( is_plugin_active( 'spacefast-wordpress/spacefast-wordpress.php' ), 'Plugin is not active.' ); @@ -113,8 +118,96 @@ function spacefast_accept( bool $condition, string $message ): void { ); $plugin = get_plugin_data( WP_PLUGIN_DIR . '/spacefast-wordpress/spacefast-wordpress.php', false, false ); -spacefast_accept( '0.5.8' === $plugin['Version'], 'Unexpected plugin version.' ); +spacefast_accept( '0.6.0' === $plugin['Version'], 'Unexpected plugin version.' ); spacefast_accept( 'https://github.com/spacefast/wordpress' === $plugin['UpdateURI'], 'Update URI is missing.' ); Spacefast_Settings::disconnect(); fwrite( STDOUT, "Spacefast WordPress container acceptance: PASS\n" ); + +/** Run real WP-CLI dispatch and Simply Static with an injected Spacefast transport. */ +function spacefast_accept_cli(): void { + spacefast_accept( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON, 'CLI acceptance must run without WP-Cron.' ); + spacefast_accept( Spacefast_Plugin::simply_static_available(), 'Simply Static is not installed.' ); + $run = static fn( string $command ) => WP_CLI::runcommand( + $command, + array( 'launch' => false, 'return' => 'all', 'exit_error' => false ) + ); + $status = $run( 'spacefast status --format=json' ); + spacefast_accept( 0 === $status->return_code, 'Disconnected status failed.' ); + spacefast_accept( 'disconnected' === json_decode( $status->stdout, true )['connection'], 'Disconnected status is not JSON.' ); + $invalid = $run( 'spacefast publish --wait --timeout=0' ); + spacefast_accept( 0 !== $invalid->return_code, 'Invalid timeout must exit non-zero.' ); + + Spacefast_Settings::merge( + array( + 'mode' => Spacefast_Settings::MODE_STATIC, + 'client_id' => 'acceptance-client', + 'access_token' => 'acceptance-access', + 'refresh_token' => 'acceptance-refresh', + 'expires_at' => time() + 900, + 'team_id' => 'team_acceptance', + 'team_name' => 'Acceptance Team', + 'space_id' => 'spc_acceptance', + 'space_name' => 'Acceptance Space', + 'live_url' => 'https://acceptance.example.test', + 'scope' => 'spaces:read spaces:write spaces:publish builds:trigger offline_access', + ) + ); + Spacefast_Sync_State::save( Spacefast_Sync_State::defaults() ); + $requests = array(); + $failed = false; + $transport = static function ( $preempt, array $args, string $url ) use ( &$requests, &$failed ) { + if ( ! str_starts_with( $url, Spacefast_Settings::api_url() . '/' ) ) return $preempt; + $requests[] = array( 'url' => $url, 'method' => $args['method'], 'body' => $args['body'] ?? '' ); + $data = array(); + $code = 200; + if ( str_ends_with( $url, '/versions' ) && 'POST' === $args['method'] ) { + $body = json_decode( $args['body'], true ); + spacefast_accept( 'snapshot' === $body['publishMode'], 'CLI did not request a full snapshot.' ); + spacefast_accept( count( $body['files'] ) > 0, 'Simply Static exported no files.' ); + // Model a server which already has the declared bytes. This exercises + // manifest creation and activation without an external upload service. + $data = array( 'versionId' => 'ver_acceptance', 'upload' => array( 'targets' => array() ) ); + $code = 201; + } elseif ( str_ends_with( $url, '/uploads/resume' ) ) { + $data = array( 'upload' => array( 'targets' => array() ) ); + } elseif ( str_ends_with( $url, '/versions/ver_acceptance' ) ) { + $data = array( 'status' => $failed ? 'failed' : 'ready', 'isCurrentProduction' => ! $failed ); + } elseif ( str_ends_with( $url, '/builds/wordpress' ) && 'POST' === $args['method'] ) { + $data = array( 'build' => array( 'id' => 'bld_acceptance' ) ); + } elseif ( str_ends_with( $url, '/v1/builds/bld_acceptance' ) ) { + $data = array( 'status' => $failed ? 'failed' : 'succeeded' ); + } elseif ( str_ends_with( $url, '/spc_acceptance' ) ) { + $data = array( 'config' => array(), 'settingsDigest' => 'acceptance-digest' ); + } + return array( 'headers' => array(), 'response' => array( 'code' => $code ), 'body' => wp_json_encode( array( 'data' => $data ) ) ); + }; + add_filter( 'pre_http_request', $transport, 10, 3 ); + try { + $publish = $run( 'spacefast publish --wait --timeout=120' ); + spacefast_accept( 0 === $publish->return_code, 'Inline publish failed: ' . $publish->stderr ); + $status = $run( 'spacefast status --format=json' ); + $receipt = json_decode( $status->stdout, true, 512, JSON_THROW_ON_ERROR ); + spacefast_accept( 'live' === $receipt['state'] && 'ver_acceptance' === $receipt['last_version_id'], 'CLI status did not record the live version.' ); + spacefast_accept( ! str_contains( $status->stdout, 'acceptance-access' ) && ! str_contains( $status->stdout, 'acceptance-refresh' ), 'Status leaked credentials.' ); + spacefast_accept( ! \Simply_Static\Plugin::instance()->get_archive_creation_job()->is_queued(), 'Inline export left cleanup queued.' ); + $table = $run( 'spacefast status' ); + spacefast_accept( 0 === $table->return_code && str_contains( $table->stdout, 'ver_acceptance' ), 'Table status is missing the version.' ); + $sync = $run( 'spacefast sync-settings' ); + spacefast_accept( 0 === $sync->return_code && ! Spacefast_Sync_State::get()['settings_pending'], 'CLI settings sync failed.' ); + + Spacefast_Settings::merge( array( 'mode' => Spacefast_Settings::MODE_HEADLESS ) ); + $build = $run( 'spacefast build --wait' ); + spacefast_accept( 0 === $build->return_code && 'live' === Spacefast_Sync_State::get()['last_status'], 'CLI build wait failed.' ); + $failed = true; + $build = $run( 'spacefast build --wait' ); + spacefast_accept( 0 !== $build->return_code, 'Failed build must exit non-zero.' ); + $disconnect = $run( 'spacefast disconnect --yes' ); + spacefast_accept( 0 === $disconnect->return_code && ! Spacefast_Settings::authorized(), 'CLI disconnect failed.' ); + spacefast_accept( count( $requests ) > 0, 'CLI commands did not use the injected transport.' ); + } finally { + remove_filter( 'pre_http_request', $transport, 10 ); + Spacefast_Settings::disconnect(); + } + fwrite( STDOUT, "Spacefast WP-CLI container acceptance: PASS\n" ); +} diff --git a/tests/behavior.php b/tests/behavior.php index 468f448..d62d90d 100644 --- a/tests/behavior.php +++ b/tests/behavior.php @@ -45,6 +45,12 @@ function add_action( string $hook, $callback, int $priority = 10, int $accepted_ function add_filter( string $hook, $callback, int $priority = 10, int $accepted_args = 1 ): void { $GLOBALS['spacefast_hooks'][ $hook ] = array( $callback, $priority, $accepted_args ); } +function remove_filter( string $hook, $callback, int $priority = 10 ): void { + unset( $GLOBALS['spacefast_hooks'][ $hook ] ); +} +function remove_action( string $hook, $callback, int $priority = 10 ): void { + remove_filter( $hook, $callback, $priority ); +} function wp_parse_url( string $value ) { return parse_url( $value ); } @@ -147,6 +153,9 @@ function add_query_arg( array $args, string $url ): string { function home_url(): string { return 'https://wp.example.test'; } +function get_current_blog_id(): int { + return 1; +} function is_wp_error( $value ): bool { return $value instanceof Spacefast_Test_Wp_Error; } @@ -1041,20 +1050,36 @@ static function ( string $url, string $method, array $headers, string $file ) us check( 4 === $fallback_static_ack['delivered'], 'static completion falls back to the desired generation when the exporter start hook is absent' ); check( 'live' === $fallback_static_ack['last_status'], 'a missing exporter start hook cannot create a publish loop' ); +Spacefast_Settings::disconnect(); +Spacefast_Sync_State::save( Spacefast_Sync_State::defaults() ); +check( ! Spacefast_Plugin::do_manual_build()['ok'], 'manual build rejects a disconnected site' ); +check( ! Spacefast_Plugin::do_manual_settings_sync()['ok'], 'manual settings sync rejects a disconnected site' ); +Spacefast_Settings::merge( array_merge( $connection, array( 'mode' => Spacefast_Settings::MODE_STATIC ) ) ); +check( ! Spacefast_Plugin::do_manual_build()['ok'], 'manual build rejects static mode' ); +check( ! Spacefast_Plugin::do_manual_static_publish()['ok'], 'manual publish requires Simply Static' ); + eval( 'namespace Simply_Static { class Task {} class Options { private static $instance; public static function instance() { return self::$instance ??= new self(); } + public static function reinstance() { self::$instance = null; return self::instance(); } public function set($key, $value) { return $this; } public function save() { return true; } } class Plugin { public static $runs = 0; + public static $job; + public static $start; private static $instance; public static function instance() { return self::$instance ??= new self(); } - public function run_static_export() { self::$runs++; return true; } + public function run_static_export() { + self::$runs++; + return is_callable(self::$start) ? call_user_func(self::$start) : true; + } + public function get_archive_creation_job() { return self::$job; } + public function set_options($options) {} } }' ); @@ -1281,4 +1306,191 @@ static function ( string $url, array $args ) use ( $retry_target ): array { rmdir( $custom_archive ); Spacefast_Static_Publisher::reset(); +// Exercise CLI failures as exceptions; the real WP-CLI maps error() to exit 1. +final class WP_CLI { + public static array $lines = array(); + public static array $commands = array(); + public static array $confirmation = array(); + public static function add_command( string $name, $command ): void { self::$commands[ $name ] = $command; } + public static function line( string $line ): void { self::$lines[] = $line; } + public static function success( string $line ): void { self::$lines[] = $line; } + public static function error( string $line ): void { throw new RuntimeException( $line ); } + public static function confirm( string $line, array $args ): void { self::$confirmation = $args; } +} +require_once dirname( __DIR__ ) . '/includes/class-spacefast-cli.php'; +check( Spacefast_CLI::class === WP_CLI::$commands['spacefast'], 'registers the spacefast command' ); +$cli = new Spacefast_CLI(); +$cli_error = static function ( callable $command, string $expected ): void { + try { + $command(); + } catch ( RuntimeException $error ) { + check( str_contains( $error->getMessage(), $expected ), 'unexpected CLI error: ' . $error->getMessage() ); + return; + } + throw new RuntimeException( 'Expected CLI error: ' . $expected ); +}; +Spacefast_Settings::merge( $connection ); +Spacefast_Sync_State::save( Spacefast_Sync_State::defaults() ); +$cli->status( array(), array( 'format' => 'json' ) ); +$json = end( WP_CLI::$lines ); +$status = json_decode( $json, true, 512, JSON_THROW_ON_ERROR ); +check( 'idle' === $status['state'] && false === $status['pending'], 'status JSON includes typed local delivery state' ); +foreach ( array( 'access_token', 'refresh_token', 'client_id', $connection['access_token'], $connection['refresh_token'] ) as $secret ) { + check( ! str_contains( $json, $secret ), 'status excludes credentials' ); +} +$cli_error( static fn() => $cli->status( array(), array( 'format' => 'yaml' ) ), 'Format must' ); +foreach ( array( '0', '-1', 'no', '1.5' ) as $timeout ) { + $cli_error( static fn() => $cli->publish( array(), array( 'timeout' => $timeout ) ), 'positive integer' ); +} +$cli_error( static fn() => $cli->publish( array(), array() ), 'Static WordPress' ); + +$build_requests = 0; +$build_status = 'succeeded'; +$GLOBALS['spacefast_remote_handler'] = static function ( string $url, array $args ) use ( &$build_requests, &$build_status ): array { + if ( 'POST' === $args['method'] ) { + $build_requests++; + return response( 201, array( 'build' => array( 'id' => 'bld_cli' ) ) ); + } + if ( str_contains( $url, '/v1/builds/' ) ) return response( 200, array( 'status' => $build_status ) ); + return response( 200, array( 'ready' => true ) ); +}; +$cli->build( array(), array() ); +check( 1 === $build_requests && 'building' === Spacefast_Sync_State::get()['last_status'], 'manual build starts immediately' ); +$cli->build( array(), array( 'wait' => true ) ); +check( 2 === $build_requests && 'live' === Spacefast_Sync_State::get()['last_status'], 'wait includes the requested successor of an active build' ); +$build_status = 'failed'; +$cli_error( static fn() => $cli->build( array(), array( 'wait' => true ) ), 'did not finish successfully' ); +$GLOBALS['spacefast_remote_handler'] = static fn(): array => response( 403 ); +$cli_error( static fn() => $cli->build( array(), array() ), 'no longer authorized' ); + +$patch = array(); +$GLOBALS['spacefast_remote_handler'] = static function ( string $url, array $args ) use ( &$patch ): array { + if ( 'PATCH' === $args['method'] ) $patch = json_decode( $args['body'], true ); + return response( 200, array( 'config' => array( 'keep' => true ), 'settingsDigest' => 'digest-cli' ) ); +}; +Spacefast_Settings::merge( array( 'scope' => 'spaces:write offline_access', 'sync_title' => true, 'sync_visibility' => true ) ); +$cli->sync_settings( array(), array() ); +check( 'Demo WordPress' === $patch['title'] && 'Demo description' === $patch['config']['meta']['description'], 'extracted sync sends site title and description' ); +check( isset( $patch['noindex'] ) && true === $patch['config']['keep'] && 'digest-cli' === $patch['baseSettingsDigest'], 'extracted sync preserves unrelated settings and digest' ); +check( ! Spacefast_Sync_State::get()['settings_pending'], 'extracted sync acknowledges settings' ); + +// A small queue double checks the adapter uses the worker lifecycle, not AJAX. +eval( 'namespace Simply_Static { + class Archive_Creation_Job { + public $queue = 0; + public $processing = false; + public $paused = false; + public $canceled = false; + public $steps = 0; + public $dispatches = 0; + public $perform; + public function set_current_site_id($site_id) {} + public function set_options($options) {} + public function dispatch() { $this->dispatches++; return array(); } + public function is_queued() { return $this->queue > 0; } + public function is_processing() { return $this->processing; } + public function is_paused() { return $this->paused; } + public function is_cancelled() { return $this->canceled; } + public $pages = 0; + public $pages_per_task = 0; + public $tasks_per_handle = 1; + public function should_continue() { + $filter = $GLOBALS["spacefast_hooks"]["wp_archive_creation_job_should_continue"][0] ?? null; + return $filter ? $filter(true) : true; + } + protected function task($item) { + // Like Simply Static fetch_urls: ask should_continue before every page. + for ($page = 0; $page < $this->pages_per_task && $this->should_continue(); $page++) $this->pages++; + return false; + } + protected function handle() { + // Like Simply Static: run tasks, checking should_continue between them. + for ($run = 0; $run < $this->tasks_per_handle && $this->is_queued(); $run++) { + $this->steps++; + $this->queue--; + $this->task("fetch_urls"); + if (is_callable($this->perform)) call_user_func($this->perform); + if (!$this->should_continue()) break; + } + if ($this->is_queued()) $this->dispatch(); + } + } +}' ); +$worker_filter = $GLOBALS['spacefast_hooks']['ss_archive_creation_job_class'][0]; +check( 'Custom_Worker' === $worker_filter( 'Custom_Worker' ), 'does not replace a custom exporter worker' ); +$worker_class = $worker_filter( '\\Simply_Static\\Archive_Creation_Job' ); +$job = new $worker_class(); +\Simply_Static\Plugin::$job = $job; +$job->queue = 1; +$job->processing = true; +check( ! $job->run_step() && 0 === $job->steps, 'inline worker respects an existing worker lock' ); +$job->processing = false; +$job->paused = true; +$cli_error( static fn() => $job->run_step(), 'paused or canceled' ); +$job->paused = false; +$job->canceled = true; +$cli_error( static fn() => $job->run_step(), 'paused or canceled' ); +$job->canceled = false; +$job->queue = 2; +$job->pages_per_task = 3; +$job->tasks_per_handle = 2; +check( $job->run_step() && 3 === $job->pages && 1 === $job->steps && 1 === $job->queue, 'inline step lets a task process its pages, then yields before the next task' ); +$job->queue = 0; +$job->pages = 0; +$job->pages_per_task = 0; +$job->tasks_per_handle = 1; +$job->steps = 0; +$job->dispatches = 0; + +Spacefast_Settings::merge( $static_connection ); +Spacefast_Sync_State::save( Spacefast_Sync_State::defaults() ); +\Simply_Static\Plugin::$start = static function () use ( $job ): bool { + call_user_func( $GLOBALS['spacefast_hooks']['ss_before_static_export'][0] ); + $job->queue = 2; + $job->dispatch(); + Spacefast_Plugin::static_export_started(); + return true; +}; +$job->perform = static function (): void { Spacefast_Plugin::static_publish_completed( 'ver_cli', 'live' ); }; +update_option( 'simply-static-use-single', 42 ); +update_option( 'simply-static-use-build', 42 ); +update_option( 'simply-static-404-only', true ); +$cli->publish( array(), array( 'wait' => true, 'timeout' => '5' ) ); +check( ! get_option( 'simply-static-use-single' ) && ! get_option( 'simply-static-use-build' ) && ! get_option( 'simply-static-404-only' ), 'CLI starts a full export despite previous partial scope' ); +check( 2 === $job->steps && 0 === $job->dispatches, 'publish wait drains tasks and cleanup inline without async dispatch' ); +check( 'ver_cli' === Spacefast_Sync_State::get()['last_version_id'], 'publish wait saves the live version' ); +check( ! Spacefast_CLI_Export_Job::$inline, 'publish restores ordinary background dispatch' ); +$cli->publish( array(), array() ); +check( 1 === $job->dispatches && 2 === $job->queue, 'publish without wait leaves background work queued' ); + +Spacefast_Sync_State::save( Spacefast_Sync_State::defaults() ); +$job->perform = static function (): void { Spacefast_Plugin::static_publish_failed( 'Export failed in test' ); }; +$cli_error( static fn() => $cli->publish( array(), array( 'wait' => true ) ), 'Export failed in test' ); +check( ! Spacefast_CLI_Export_Job::$inline, 'failure restores ordinary background dispatch' ); +Spacefast_Sync_State::save( Spacefast_Sync_State::defaults() ); +$job->processing = true; +$cli_error( static fn() => $cli->publish( array(), array( 'wait' => true, 'timeout' => '1' ) ), 'Timed out' ); +check( $job->is_queued() && ! Spacefast_CLI_Export_Job::$inline, 'timeout preserves queued work and restores dispatch' ); +$job->processing = false; + +$wait = new ReflectionMethod( Spacefast_CLI::class, 'wait' ); +Spacefast_Sync_State::save( array_merge( Spacefast_Sync_State::defaults(), array( 'desired' => 1, 'delivered' => 1, 'last_status' => 'ready', 'last_version_id' => 'ver_ready' ) ) ); +$GLOBALS['spacefast_remote_handler'] = static fn(): array => response( 200, array( 'status' => 'ready', 'isCurrentProduction' => false ) ); +$cli_error( static fn() => $wait->invoke( $cli, 1, microtime( true ) + 0.01 ), 'Timed out' ); +$GLOBALS['spacefast_remote_handler'] = static fn(): array => response( 200, array( 'status' => 'ready', 'isCurrentProduction' => true ) ); +$wait->invoke( $cli, 1, microtime( true ) + 1 ); +check( 'live' === Spacefast_Sync_State::get()['last_status'], 'ready version waits for production activation' ); + +$revoked = false; +$GLOBALS['spacefast_remote_handler'] = static function ( string $url ) use ( &$revoked ): array { + $revoked = str_ends_with( $url, '/oauth2/revoke' ); + return response( 200 ); +}; +$cli->disconnect( array(), array( 'yes' => true ) ); +check( array( 'yes' => true ) === WP_CLI::$confirmation, 'disconnect forwards confirmation options' ); +check( $revoked && ! Spacefast_Settings::authorized(), 'disconnect revokes refresh access and clears credentials' ); +check( false === wp_next_scheduled( Spacefast_Sync_State::HOOK ), 'disconnect clears scheduled work' ); +$cli->status( array(), array( 'format' => 'json' ) ); +check( 'disconnected' === json_decode( end( WP_CLI::$lines ), true )['connection'], 'disconnected status remains valid JSON' ); + fwrite( STDOUT, "Spacefast WordPress behavior tests: PASS\n" );