From 40f2590f862f4db6b0c827908ded2d107b139667 Mon Sep 17 00:00:00 2001 From: Gabriel de Tassigny Date: Wed, 2 Dec 2026 15:39:36 +0100 Subject: [PATCH 1/4] Fix sync loop flagging PDFs and other files without dimensions Files without width and height (PDF, audio, documents) got the error 'Sync loop detected: the "delivery" sync state could not be saved.' when uploaded in the admin. Preparing their sync asks for the attachment URL, and the admin URL filter called back into Media::cloudinary_id(), which prepared the sync again until the loop guard tripped. Answer that nested call with the local URL instead. On upgrade from 3.3.9, clear the delivery loop errors it flagged so those files sync. Adds PHPUnit regression tests and an e2e test that uploads a PDF through the Media Library. Fixes #1397 --- php/class-media.php | 6 + php/class-sync.php | 60 +++- tests/e2e/cloudinary-document-sync.spec.js | 200 +++++++++++ tests/e2e/fixtures/test-document.pdf | Bin 0 -> 193 bytes .../test-media-cloudinary-id-reentry.php | 323 ++++++++++++++++++ 5 files changed, 580 insertions(+), 9 deletions(-) create mode 100644 tests/e2e/cloudinary-document-sync.spec.js create mode 100644 tests/e2e/fixtures/test-document.pdf create mode 100644 tests/phpunit/tests/test-media-cloudinary-id-reentry.php diff --git a/php/class-media.php b/php/class-media.php index 74924df24..96f961220 100644 --- a/php/class-media.php +++ b/php/class-media.php @@ -1788,6 +1788,12 @@ public function cloudinary_id( $attachment_id ) { } if ( ! $this->sync->is_synced( $attachment_id ) && ! defined( 'REST_REQUEST' ) ) { + // Preparing the sync can ask for this attachment's URL, e.g. the "delivery" sync type for a file without + // dimensions (PDF, audio, documents), and the attachment URL filter calls back into this method. + // Answer that nested call with the local URL instead of preparing the sync again, which would loop. + // The real ID replaces this placeholder below. + $cloudinary_ids[ $attachment_id ] = false; + $sync_type = $this->sync->maybe_prepare_sync( $attachment_id ); // Check sync type allows for continued rendering. i.e meta update, breakpoints etc, will still allow the URL to work, // Where is type "file" will not since it's still being uploaded. diff --git a/php/class-sync.php b/php/class-sync.php index 2db1f2277..fe1496da9 100644 --- a/php/class-sync.php +++ b/php/class-sync.php @@ -137,6 +137,56 @@ public function __construct( Plugin $plugin ) { // Register Settings. add_filter( 'cloudinary_admin_pages', array( $this, 'settings' ) ); + + add_action( 'cloudinary_version_upgrade', array( $this, 'clear_delivery_loop_errors' ) ); + } + + /** + * Get the sync error saved when a sync type keeps recursing without advancing. + * + * @param string $type The sync type that would not advance. + * + * @return string + */ + public static function get_loop_error_message( $type ) { + return sprintf( + /* translators: %s is the sync type that would not advance. */ + __( 'Sync loop detected: the "%s" sync state could not be saved.', 'cloudinary' ), + $type + ); + } + + /** + * Clear the sync loop errors that 3.3.9 flagged on the "delivery" sync type, so those attachments are retried. + * + * In 3.3.9, files without dimensions (PDF, audio, documents) got this error on upload, from a loop between + * preparing their sync and getting their URL. Now that the loop is fixed, they can sync without anyone clearing the + * error by hand. Only this exact error is cleared, and only when upgrading from 3.3.9: other sync errors, and + * genuine loops flagged later, stay visible. + * + * @param string $old_version The version upgrading from. + */ + public function clear_delivery_loop_errors( $old_version ) { + if ( version_compare( $old_version, '3.3.9', '<' ) || version_compare( $old_version, '3.3.10', '>=' ) ) { + return; + } + + // The message is saved in the language of the request that flagged it, e.g. the uploading user's language, so + // clear it in every installed language, as well as in English. + $messages = array( + 'Sync loop detected: the "delivery" sync state could not be saved.', + self::get_loop_error_message( 'delivery' ), + ); + foreach ( get_available_languages() as $locale ) { + if ( switch_to_locale( $locale ) ) { + $messages[] = self::get_loop_error_message( 'delivery' ); + restore_previous_locale(); + } + } + + foreach ( array_unique( $messages ) as $message ) { + delete_metadata( 'post', 0, self::META_KEYS['sync_error'], $message, true ); + } } /** @@ -947,15 +997,7 @@ public function validate_sync_type( $type, $attachment_id ) { */ $limit = apply_filters( 'cloudinary_sync_type_retry_limit', 50, $type, $attachment_id ); if ( $depth[ $key ] > $limit ) { - update_post_meta( - $attachment_id, - self::META_KEYS['sync_error'], - sprintf( - /* translators: %s is the sync type that would not advance. */ - __( 'Sync loop detected: the "%s" sync state could not be saved.', 'cloudinary' ), - $type - ) - ); + update_post_meta( $attachment_id, self::META_KEYS['sync_error'], self::get_loop_error_message( $type ) ); return null; } diff --git a/tests/e2e/cloudinary-document-sync.spec.js b/tests/e2e/cloudinary-document-sync.spec.js new file mode 100644 index 000000000..900d6a81c --- /dev/null +++ b/tests/e2e/cloudinary-document-sync.spec.js @@ -0,0 +1,200 @@ +/** + * External dependencies + */ +const fs = require( 'fs' ); +const path = require( 'path' ); +const { test, expect } = require( './fixtures' ); + +/** + * Internal dependencies + */ +const { ensureCloudinaryConnected } = require( './utils/connection' ); +const { phpJson, saveSettings } = require( './utils/settings' ); +const { wpCli, wpEvalFile } = require( './utils/wizard' ); + +const FIXTURE_PATH = path.join( __dirname, 'fixtures', 'test-document.pdf' ); + +/** + * Settings pinned for the spec, restored in afterAll. + * + * @type {Record} + */ +const SETTINGS = { + auto_sync: 'on', + offload: 'dual_full', +}; + +/** @type {Record|null} */ +let previousSettings = null; + +/** + * Attachment IDs the spec creates, removed in afterAll with their + * Cloudinary assets. + * + * @type {number[]} + */ +let attachmentIds = []; + +/** + * Get the sync state of an attachment. + * + * @param {number} attachmentId The attachment ID. + * @return {{ error: string, publicId: string, synced: boolean, url: string }} The sync state. + */ +function getSyncState( attachmentId ) { + return JSON.parse( + wpEvalFile( ` + $id = ${ Number( attachmentId ) }; + $plugin = get_plugin_instance(); + $media = $plugin->get_component( 'media' ); + echo wp_json_encode( + array( + 'error' => (string) get_post_meta( $id, Sync::META_KEYS['sync_error'], true ), + 'publicId' => $media->has_public_id( $id ) ? $media->get_public_id( $id ) : '', + 'synced' => $plugin->get_component( 'sync' )->is_synced( $id, true ), + 'url' => (string) $media->cloudinary_url( $id ), + ) + ); + ` ) + ); +} + +/** + * Find an attachment by the name of its file. + * + * @param {string} filename The file name. + * @return {number} The attachment ID, or 0 if there is none. + */ +function findAttachmentByFilename( filename ) { + return Number( + wpEvalFile( ` + $ids = get_posts( + array( + 'post_type' => 'attachment', + 'post_status' => 'inherit', + 'fields' => 'ids', + 'meta_query' => array( + array( + 'key' => '_wp_attached_file', + 'value' => '/' . ${ phpJson( filename ) }, + 'compare' => 'LIKE', + ), + ), + ) + ); + echo $ids ? (int) $ids[0] : 0; + ` ) + ); +} + +// @serial: needs real credentials in `cloudinary_connect` to sync assets, +// while every analytics spec overwrites that option with fake ones. +test.describe( 'Cloudinary document sync', { tag: '@serial' }, () => { + test.beforeAll( () => { + ensureCloudinaryConnected(); + previousSettings = saveSettings( SETTINGS ); + } ); + + test.afterAll( () => { + try { + if ( previousSettings ) { + saveSettings( previousSettings ); + previousSettings = null; + } + } finally { + const ids = attachmentIds; + attachmentIds = []; + + // Remove the assets directly, so a failed test does not leave + // them in the Cloudinary account. + if ( ids.length ) { + try { + wpEvalFile( ` + $plugin = get_plugin_instance(); + $media = $plugin->get_component( 'media' ); + $api = $plugin->get_component( 'connect' )->api; + foreach ( ${ phpJson( ids ) } as $id ) { + if ( $media->has_public_id( $id ) ) { + $api->destroy( $media->get_resource_type( $id ), array( 'public_id' => $media->get_public_id( $id ) ) ); + } + } + ` ); + } catch ( e ) { + console.warn( + 'Cleanup of the Cloudinary assets failed:', + e.message + ); + } + } + + for ( const id of ids ) { + try { + wpCli( [ 'post', 'delete', String( id ), '--force' ] ); + } catch ( e ) { + console.warn( + `Cleanup of post ${ id } failed:`, + e.message + ); + } + } + } + } ); + + // Uploads through the browser on purpose. A REST upload (`/wp/v2/media`, + // as the other specs use) skips the sync preparation that runs while the + // file is uploaded, and the plugin's admin URL filters, so it can't catch + // a sync loop between the two. + test( 'a PDF uploaded through the Media Library syncs to Cloudinary', async ( { + admin, + page, + } ) => { + // A fresh file name, so no asset from an earlier run applies. + const filename = `document-sync-${ Date.now() }.pdf`; + + await admin.visitAdminPage( 'media-new.php' ); + const input = page.locator( '#plupload-upload-ui input[type="file"]' ); + await expect( input ).toBeAttached(); + + const upload = page.waitForResponse( + ( response ) => + response.url().includes( '/wp-admin/async-upload.php' ) && + 'POST' === response.request().method() + ); + await input.setInputFiles( { + name: filename, + mimeType: 'application/pdf', + buffer: fs.readFileSync( FIXTURE_PATH ), + } ); + expect( ( await upload ).ok(), 'the upload should succeed' ).toBe( + true + ); + + const attachmentId = findAttachmentByFilename( filename ); + expect( + attachmentId, + 'the PDF should be in the Media Library' + ).toBeGreaterThan( 0 ); + attachmentIds.push( attachmentId ); + + // The upload request itself prepares the sync, which is where the + // sync loop flagged the file. + expect( + getSyncState( attachmentId ).error, + 'the upload should not flag a sync error' + ).toBe( '' ); + + // Run the push sync for only this attachment, which is what the + // auto-sync queue does, so other media in the test site is not touched. + wpEvalFile( ` + get_plugin_instance()->get_component( 'sync' )->managers['push']->process_assets( ${ Number( attachmentId ) } ); + ` ); + + const state = getSyncState( attachmentId ); + expect( state.error, 'the sync should not flag an error' ).toBe( '' ); + expect( state.publicId, 'the PDF should get a public ID' ).toBeTruthy(); + expect( state.synced, 'the PDF should be fully synced' ).toBe( true ); + expect( state.url, 'the PDF should have a Cloudinary URL' ).toContain( + 'res.cloudinary.com' + ); + } ); +} ); diff --git a/tests/e2e/fixtures/test-document.pdf b/tests/e2e/fixtures/test-document.pdf new file mode 100644 index 0000000000000000000000000000000000000000..61debf6b49e6ed496174e731c928cfe70dac67da GIT binary patch literal 193 zcmY!laB^a}0F$^lf&c&j literal 0 HcmV?d00001 diff --git a/tests/phpunit/tests/test-media-cloudinary-id-reentry.php b/tests/phpunit/tests/test-media-cloudinary-id-reentry.php new file mode 100644 index 000000000..c6eb9be8d --- /dev/null +++ b/tests/phpunit/tests/test-media-cloudinary-id-reentry.php @@ -0,0 +1,323 @@ +>endobj\n2 0 obj<>endobj\n3 0 obj<>endobj\ntrailer<>\n%%EOF\n"; + + /** + * The sync types live on the Sync component, which outlives any one test. Rebuild them once the hooks are + * restored, so a test's cloudinary_sync_base_struct filter doesn't leak into later tests. + * + * @return void + */ + public function tear_down() { + parent::tear_down(); + + \Cloudinary\get_plugin_instance()->get_component( 'sync' )->register_assets(); + } + + /** + * Get the Media component. + * + * @return \Cloudinary\Media + */ + protected function get_media() { + return \Cloudinary\get_plugin_instance()->get_component( 'media' ); + } + + /** + * Fake a connected site, so the sync types are registered and the components are wired, without reaching the + * network. Same setup as Test_Sync_Loop_Guard::get_sync(). + * + * @return Sync + */ + protected function get_sync() { + $plugin = \Cloudinary\get_plugin_instance(); + $connect = $plugin->get_component( 'connect' ); + + $plugin->settings->set_param( 'connected', true ); + set_transient( Connect::META_KEYS['usage'], array( 'placeholder' => true ), HOUR_IN_SECONDS ); + $plugin->settings->set_value( 'cloudinary_url', 'cloudinary://123456789012345:abcdefghijklmnopqrstuvwxyzABCDEF@test-cloud' ); + $connect->setup(); + + do_action( 'cloudinary_connected', $plugin ); + + $plugin->get_component( 'media' )->setup(); + $plugin->get_component( 'sync' )->setup(); + $plugin->get_component( 'delivery' )->setup(); + + $sync = $plugin->get_component( 'sync' ); + $sync->register_assets(); + + return $sync; + } + + /** + * Create an attachment from a file with the given contents. + * + * @param string $filename The file name. + * @param string $contents The file contents. + * + * @return int + */ + protected function create_attachment( $filename, $contents ) { + $path = trailingslashit( get_temp_dir() ) . wp_unique_filename( get_temp_dir(), $filename ); + file_put_contents( $path, $contents ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents + + $attachment_id = self::factory()->attachment->create_upload_object( $path ); + wp_delete_file( $path ); + + return $attachment_id; + } + + /** + * Get a sync type's saved signature for an attachment. + * + * @param Sync $sync The Sync component. + * @param int $attachment_id The attachment ID. + * @param string $type The sync type. + * + * @return mixed + */ + protected function get_signature_item( $sync, $attachment_id, $type ) { + $signature = $sync->get_signature( $attachment_id, false ); + + return isset( $signature[ $type ] ) ? $signature[ $type ] : null; + } + + /** + * Get the Cloudinary ID of an unsynced PDF with the admin's attachment URL filter in place, as when it's uploaded + * through the Media Library or first shown on an admin screen. Preparing its sync must save the "delivery" + * signature instead of looping until the guard flags it. + * + * @return void + */ + public function test_preparing_the_sync_of_a_pdf_does_not_loop() { + $sync = $this->get_sync(); + $media = $this->get_media(); + $media->add_live_url_filters(); + + $attachment_id = $this->create_attachment( 'sample.pdf', self::PDF ); + $this->assertEmpty( wp_get_attachment_metadata( $attachment_id )['width'] ?? null, 'The PDF must have no width, so create_delivery() falls back to its URL.' ); + + // Each call to create_delivery() is one round of the loop. + $rounds = 0; + add_filter( + 'cloudinary_sync_type_retry_limit', + function ( $limit, $type, $id ) use ( $attachment_id, &$rounds ) { + if ( 'delivery' === $type && $attachment_id === $id ) { + ++$rounds; + } + + return $limit; + }, + 10, + 3 + ); + + $media->cloudinary_id( $attachment_id ); + + $this->assertEmpty( get_post_meta( $attachment_id, Sync::META_KEYS['sync_error'], true ), 'The PDF must not be flagged with a sync loop error.' ); + $this->assertNotNull( $this->get_signature_item( $sync, $attachment_id, 'delivery' ), 'The "delivery" signature must be saved.' ); + $this->assertLessThanOrEqual( 2, $rounds, 'The "delivery" sync type must not be prepared again from within itself.' ); + } + + /** + * Within its own sync preparation, the attachment URL must be the local one. + * + * @return void + */ + public function test_the_nested_attachment_url_is_the_local_one() { + $this->get_sync(); + $media = $this->get_media(); + $media->add_live_url_filters(); + + $attachment_id = $this->create_attachment( 'sample.pdf', self::PDF ); + + $nested_urls = array(); + add_filter( + 'wp_get_attachment_url', + function ( $url, $id ) use ( $attachment_id, &$nested_urls ) { + if ( $attachment_id === $id ) { + $nested_urls[] = $url; + } + + return $url; + }, + 11, + 2 + ); + + $media->cloudinary_id( $attachment_id ); + + // Only read the local URL now: getting it runs other wp_get_attachment_url filters, which would prepare the + // "delivery" sync type before cloudinary_id() does. + $local_url = $media->local_url( $attachment_id ); + + $this->assertNotEmpty( $nested_urls, 'create_delivery() should have asked for the attachment URL.' ); + foreach ( $nested_urls as $url ) { + $this->assertSame( $local_url, $url ); + } + } + + /** + * The guard only answers the nested call. Once its sync is prepared, the outer call returns the attachment's real + * Cloudinary ID, and later calls get it too, not the placeholder. + * + * @return void + */ + public function test_the_outer_call_still_gets_the_cloudinary_id() { + // cloudinary_id() returns the real ID once the sync is prepared, unless a sync type required to render the + // URL is still pending. For a new PDF, the upload ("file") is next, so make no type required for this test. + add_filter( + 'cloudinary_sync_base_struct', + function ( $struct ) { + foreach ( $struct as $type => $structure ) { + $struct[ $type ]['required'] = false; + } + + return $struct; + } + ); + $this->get_sync(); + $media = $this->get_media(); + $media->add_live_url_filters(); + + $attachment_id = $this->create_attachment( 'sample.pdf', self::PDF ); + $media->update_post_meta( $attachment_id, Sync::META_KEYS['public_id'], 'sample' ); + + // Count the "delivery" sync type runs, to check this call is the one that prepares the sync. + $rounds = 0; + add_filter( + 'cloudinary_sync_type_retry_limit', + function ( $limit, $type, $id ) use ( $attachment_id, &$rounds ) { + if ( 'delivery' === $type && $attachment_id === $id ) { + ++$rounds; + } + + return $limit; + }, + 10, + 3 + ); + + $cloudinary_id = $media->cloudinary_id( $attachment_id ); + + $this->assertGreaterThan( 0, $rounds, 'The call should have prepared the sync, setting the placeholder.' ); + $this->assertEmpty( get_post_meta( $attachment_id, Sync::META_KEYS['sync_error'], true ) ); + $this->assertNotEmpty( $cloudinary_id, 'The outer call must return the real Cloudinary ID, not the placeholder.' ); + $this->assertSame( $cloudinary_id, $media->cloudinary_id( $attachment_id ), 'Later calls must get the real Cloudinary ID too.' ); + } + + /** + * Create an attachment flagged with a sync error. + * + * @param string $error The sync error. + * + * @return int + */ + protected function create_errored_attachment( $error ) { + $attachment_id = self::factory()->attachment->create_object( + array( + 'file' => 'errored.pdf', + 'post_mime_type' => 'application/pdf', + ) + ); + update_post_meta( $attachment_id, Sync::META_KEYS['sync_error'], $error ); + + return $attachment_id; + } + + /** + * Upgrading from 3.3.9 clears the "delivery" sync loop error, in English and in the current language, so the + * affected attachments are synced again. Every other sync error is kept. + * + * @return void + */ + public function test_upgrade_from_3_3_9_clears_only_the_delivery_loop_error() { + $sync = $this->get_sync(); + $english = 'Sync loop detected: the "delivery" sync state could not be saved.'; + + // Pretend the site is in another language, so the translated message differs from the English one. + add_filter( + 'gettext', + function ( $translation, $text, $domain ) { + if ( 'cloudinary' === $domain && 'Sync loop detected: the "%s" sync state could not be saved.' === $text ) { + return 'Boucle de synchronisation : l’état "%s" n’a pas pu être enregistré.'; + } + + return $translation; + }, + 10, + 3 + ); + $this->assertNotSame( $english, Sync::get_loop_error_message( 'delivery' ) ); + + $english_loop = $this->create_errored_attachment( $english ); + $translated_loop = $this->create_errored_attachment( Sync::get_loop_error_message( 'delivery' ) ); + $other_loop = $this->create_errored_attachment( Sync::get_loop_error_message( 'file' ) ); + $other_error = $this->create_errored_attachment( 'Invalid file type' ); + + $sync->clear_delivery_loop_errors( '3.3.9' ); + + $this->assertEmpty( get_post_meta( $english_loop, Sync::META_KEYS['sync_error'], true ) ); + $this->assertEmpty( get_post_meta( $translated_loop, Sync::META_KEYS['sync_error'], true ) ); + $this->assertSame( Sync::get_loop_error_message( 'file' ), get_post_meta( $other_loop, Sync::META_KEYS['sync_error'], true ) ); + $this->assertSame( 'Invalid file type', get_post_meta( $other_error, Sync::META_KEYS['sync_error'], true ) ); + } + + /** + * Only 3.3.9 flagged these errors by mistake. After an upgrade from any other version, a "delivery" sync loop error + * is a genuine one, and must stay visible. + * + * @return void + */ + public function test_upgrade_from_other_versions_keeps_the_delivery_loop_error() { + $sync = $this->get_sync(); + $attachment_id = $this->create_errored_attachment( Sync::get_loop_error_message( 'delivery' ) ); + + foreach ( array( '3.3.8', '3.3.10', '3.4.0' ) as $old_version ) { + $sync->clear_delivery_loop_errors( $old_version ); + + $this->assertSame( + Sync::get_loop_error_message( 'delivery' ), + get_post_meta( $attachment_id, Sync::META_KEYS['sync_error'], true ), + "Upgrading from $old_version must keep the error." + ); + } + } + + /** + * The cleanup runs on the plugin's version upgrade. + * + * @return void + */ + public function test_cleanup_is_hooked_to_the_version_upgrade() { + $sync = \Cloudinary\get_plugin_instance()->get_component( 'sync' ); + + $this->assertNotFalse( has_action( 'cloudinary_version_upgrade', array( $sync, 'clear_delivery_loop_errors' ) ) ); + } +} From 0c81d8e7d87350484a271239b325a0413af1c089 Mon Sep 17 00:00:00 2001 From: Gabriel de Tassigny Date: Thu, 3 Dec 2026 09:58:53 +0100 Subject: [PATCH 2/4] Cover every kind of synced asset in the upload sync e2e test The sync loop hit every file without dimensions, not just PDFs: SVG, documents, spreadsheets, CSV, archives and audio. Upload one of each through the Media Library, with SVG support on, plus an image and a video to check files with dimensions still sync. Together they cover Cloudinary's image, video and raw resource types. All files go up in one batch, and their state is read in one call, so the test only takes about 15 seconds longer than the PDF-only one. Wait for the auto-sync queue to push the files instead of syncing them from the test, which raced with the queue and flagged files with "Asset in sync loop." once several were uploaded. --- tests/e2e/cloudinary-document-sync.spec.js | 200 ---------------- tests/e2e/cloudinary-upload-sync.spec.js | 256 +++++++++++++++++++++ tests/e2e/fixtures/test-archive.zip | Bin 0 -> 135 bytes tests/e2e/fixtures/test-audio.mp3 | Bin 0 -> 16680 bytes tests/e2e/fixtures/test-data.csv | 3 + tests/e2e/fixtures/test-document.docx | Bin 0 -> 912 bytes tests/e2e/fixtures/test-sheet.xlsx | Bin 0 -> 888 bytes 7 files changed, 259 insertions(+), 200 deletions(-) delete mode 100644 tests/e2e/cloudinary-document-sync.spec.js create mode 100644 tests/e2e/cloudinary-upload-sync.spec.js create mode 100644 tests/e2e/fixtures/test-archive.zip create mode 100644 tests/e2e/fixtures/test-audio.mp3 create mode 100644 tests/e2e/fixtures/test-data.csv create mode 100644 tests/e2e/fixtures/test-document.docx create mode 100644 tests/e2e/fixtures/test-sheet.xlsx diff --git a/tests/e2e/cloudinary-document-sync.spec.js b/tests/e2e/cloudinary-document-sync.spec.js deleted file mode 100644 index 900d6a81c..000000000 --- a/tests/e2e/cloudinary-document-sync.spec.js +++ /dev/null @@ -1,200 +0,0 @@ -/** - * External dependencies - */ -const fs = require( 'fs' ); -const path = require( 'path' ); -const { test, expect } = require( './fixtures' ); - -/** - * Internal dependencies - */ -const { ensureCloudinaryConnected } = require( './utils/connection' ); -const { phpJson, saveSettings } = require( './utils/settings' ); -const { wpCli, wpEvalFile } = require( './utils/wizard' ); - -const FIXTURE_PATH = path.join( __dirname, 'fixtures', 'test-document.pdf' ); - -/** - * Settings pinned for the spec, restored in afterAll. - * - * @type {Record} - */ -const SETTINGS = { - auto_sync: 'on', - offload: 'dual_full', -}; - -/** @type {Record|null} */ -let previousSettings = null; - -/** - * Attachment IDs the spec creates, removed in afterAll with their - * Cloudinary assets. - * - * @type {number[]} - */ -let attachmentIds = []; - -/** - * Get the sync state of an attachment. - * - * @param {number} attachmentId The attachment ID. - * @return {{ error: string, publicId: string, synced: boolean, url: string }} The sync state. - */ -function getSyncState( attachmentId ) { - return JSON.parse( - wpEvalFile( ` - $id = ${ Number( attachmentId ) }; - $plugin = get_plugin_instance(); - $media = $plugin->get_component( 'media' ); - echo wp_json_encode( - array( - 'error' => (string) get_post_meta( $id, Sync::META_KEYS['sync_error'], true ), - 'publicId' => $media->has_public_id( $id ) ? $media->get_public_id( $id ) : '', - 'synced' => $plugin->get_component( 'sync' )->is_synced( $id, true ), - 'url' => (string) $media->cloudinary_url( $id ), - ) - ); - ` ) - ); -} - -/** - * Find an attachment by the name of its file. - * - * @param {string} filename The file name. - * @return {number} The attachment ID, or 0 if there is none. - */ -function findAttachmentByFilename( filename ) { - return Number( - wpEvalFile( ` - $ids = get_posts( - array( - 'post_type' => 'attachment', - 'post_status' => 'inherit', - 'fields' => 'ids', - 'meta_query' => array( - array( - 'key' => '_wp_attached_file', - 'value' => '/' . ${ phpJson( filename ) }, - 'compare' => 'LIKE', - ), - ), - ) - ); - echo $ids ? (int) $ids[0] : 0; - ` ) - ); -} - -// @serial: needs real credentials in `cloudinary_connect` to sync assets, -// while every analytics spec overwrites that option with fake ones. -test.describe( 'Cloudinary document sync', { tag: '@serial' }, () => { - test.beforeAll( () => { - ensureCloudinaryConnected(); - previousSettings = saveSettings( SETTINGS ); - } ); - - test.afterAll( () => { - try { - if ( previousSettings ) { - saveSettings( previousSettings ); - previousSettings = null; - } - } finally { - const ids = attachmentIds; - attachmentIds = []; - - // Remove the assets directly, so a failed test does not leave - // them in the Cloudinary account. - if ( ids.length ) { - try { - wpEvalFile( ` - $plugin = get_plugin_instance(); - $media = $plugin->get_component( 'media' ); - $api = $plugin->get_component( 'connect' )->api; - foreach ( ${ phpJson( ids ) } as $id ) { - if ( $media->has_public_id( $id ) ) { - $api->destroy( $media->get_resource_type( $id ), array( 'public_id' => $media->get_public_id( $id ) ) ); - } - } - ` ); - } catch ( e ) { - console.warn( - 'Cleanup of the Cloudinary assets failed:', - e.message - ); - } - } - - for ( const id of ids ) { - try { - wpCli( [ 'post', 'delete', String( id ), '--force' ] ); - } catch ( e ) { - console.warn( - `Cleanup of post ${ id } failed:`, - e.message - ); - } - } - } - } ); - - // Uploads through the browser on purpose. A REST upload (`/wp/v2/media`, - // as the other specs use) skips the sync preparation that runs while the - // file is uploaded, and the plugin's admin URL filters, so it can't catch - // a sync loop between the two. - test( 'a PDF uploaded through the Media Library syncs to Cloudinary', async ( { - admin, - page, - } ) => { - // A fresh file name, so no asset from an earlier run applies. - const filename = `document-sync-${ Date.now() }.pdf`; - - await admin.visitAdminPage( 'media-new.php' ); - const input = page.locator( '#plupload-upload-ui input[type="file"]' ); - await expect( input ).toBeAttached(); - - const upload = page.waitForResponse( - ( response ) => - response.url().includes( '/wp-admin/async-upload.php' ) && - 'POST' === response.request().method() - ); - await input.setInputFiles( { - name: filename, - mimeType: 'application/pdf', - buffer: fs.readFileSync( FIXTURE_PATH ), - } ); - expect( ( await upload ).ok(), 'the upload should succeed' ).toBe( - true - ); - - const attachmentId = findAttachmentByFilename( filename ); - expect( - attachmentId, - 'the PDF should be in the Media Library' - ).toBeGreaterThan( 0 ); - attachmentIds.push( attachmentId ); - - // The upload request itself prepares the sync, which is where the - // sync loop flagged the file. - expect( - getSyncState( attachmentId ).error, - 'the upload should not flag a sync error' - ).toBe( '' ); - - // Run the push sync for only this attachment, which is what the - // auto-sync queue does, so other media in the test site is not touched. - wpEvalFile( ` - get_plugin_instance()->get_component( 'sync' )->managers['push']->process_assets( ${ Number( attachmentId ) } ); - ` ); - - const state = getSyncState( attachmentId ); - expect( state.error, 'the sync should not flag an error' ).toBe( '' ); - expect( state.publicId, 'the PDF should get a public ID' ).toBeTruthy(); - expect( state.synced, 'the PDF should be fully synced' ).toBe( true ); - expect( state.url, 'the PDF should have a Cloudinary URL' ).toContain( - 'res.cloudinary.com' - ); - } ); -} ); diff --git a/tests/e2e/cloudinary-upload-sync.spec.js b/tests/e2e/cloudinary-upload-sync.spec.js new file mode 100644 index 000000000..fd05d5724 --- /dev/null +++ b/tests/e2e/cloudinary-upload-sync.spec.js @@ -0,0 +1,256 @@ +/** + * External dependencies + */ +const fs = require( 'fs' ); +const path = require( 'path' ); +const { test, expect } = require( './fixtures' ); + +/** + * Internal dependencies + */ +const { ensureCloudinaryConnected } = require( './utils/connection' ); +const { phpJson, saveSettings } = require( './utils/settings' ); +const { wpCli, wpEvalFile } = require( './utils/wizard' ); + +const FIXTURES_DIR = path.join( __dirname, 'fixtures' ); + +/** + * The files to upload, one per kind of asset the plugin syncs. + * + * Most have no width and height, which is what sent files into a sync loop on + * upload. The image and the video check that files with dimensions still sync. + * Between them they cover Cloudinary's image, video and raw resource types. + * + * @type {string[]} + */ +const FILES = [ + 'test-document.pdf', + 'svg-valid.svg', + 'test-document.docx', + 'test-sheet.xlsx', + 'test-data.csv', + 'test-archive.zip', + 'test-audio.mp3', + 'test-image.jpg', + 'test-video.mp4', +]; + +/** + * Settings pinned for the spec, restored in afterAll. + * + * @type {Record} + */ +const SETTINGS = { + auto_sync: 'on', + offload: 'dual_full', + svg_support: 'on', +}; + +/** @type {Record|null} */ +let previousSettings = null; + +/** + * Attachment IDs the spec creates, removed in afterAll with their + * Cloudinary assets. + * + * @type {number[]} + */ +let attachmentIds = []; + +/** + * Get the sync state of the attachments with the given file names. + * + * Reads them all in one call, as each call boots WordPress. + * + * @param {string[]} filenames The file names. + * @return {Record} The sync state by file name, or null when there is no such attachment. + */ +function getSyncStates( filenames ) { + return JSON.parse( + wpEvalFile( ` + $plugin = get_plugin_instance(); + $media = $plugin->get_component( 'media' ); + $sync = $plugin->get_component( 'sync' ); + $states = array(); + foreach ( ${ phpJson( filenames ) } as $filename ) { + $ids = get_posts( + array( + 'post_type' => 'attachment', + 'post_status' => 'inherit', + 'fields' => 'ids', + 'meta_query' => array( + array( + 'key' => '_wp_attached_file', + 'value' => '/' . $filename, + 'compare' => 'LIKE', + ), + ), + ) + ); + $id = $ids ? (int) $ids[0] : 0; + $states[ $filename ] = $id ? array( + 'id' => $id, + 'error' => (string) get_post_meta( $id, Sync::META_KEYS['sync_error'], true ), + 'publicId' => $media->has_public_id( $id ) ? $media->get_public_id( $id ) : '', + 'synced' => $sync->is_synced( $id, true ), + 'url' => (string) $media->cloudinary_url( $id ), + ) : null; + } + echo wp_json_encode( $states ); + ` ) + ); +} + +// @serial: needs real credentials in `cloudinary_connect` to sync assets, +// while every analytics spec overwrites that option with fake ones. +test.describe( 'Cloudinary upload sync', { tag: '@serial' }, () => { + test.beforeAll( () => { + ensureCloudinaryConnected(); + previousSettings = saveSettings( SETTINGS ); + } ); + + test.afterAll( () => { + try { + if ( previousSettings ) { + saveSettings( previousSettings ); + previousSettings = null; + } + } finally { + const ids = attachmentIds; + attachmentIds = []; + + // Remove the assets directly, so a failed test does not leave + // them in the Cloudinary account. + if ( ids.length ) { + try { + wpEvalFile( ` + $plugin = get_plugin_instance(); + $media = $plugin->get_component( 'media' ); + $api = $plugin->get_component( 'connect' )->api; + foreach ( ${ phpJson( ids ) } as $id ) { + if ( $media->has_public_id( $id ) ) { + $api->destroy( $media->get_resource_type( $id ), array( 'public_id' => $media->get_public_id( $id ) ) ); + } + } + ` ); + } catch ( e ) { + console.warn( + 'Cleanup of the Cloudinary assets failed:', + e.message + ); + } + } + + for ( const id of ids ) { + try { + wpCli( [ 'post', 'delete', String( id ), '--force' ] ); + } catch ( e ) { + console.warn( + `Cleanup of post ${ id } failed:`, + e.message + ); + } + } + } + } ); + + // Uploads through the browser on purpose. A REST upload (`/wp/v2/media`, + // as the other specs use) skips the sync preparation that runs while the + // file is uploaded, and the plugin's admin URL filters, so it can't catch + // a sync loop between the two. + test( 'files uploaded through the Media Library sync to Cloudinary', async ( { + admin, + page, + } ) => { + // Fresh file names, so no asset from an earlier run applies. + const stamp = Date.now(); + const filenames = FILES.map( ( file ) => { + const { name, ext } = path.parse( file ); + return `upload-sync-${ name }-${ stamp }${ ext }`; + } ); + + await admin.visitAdminPage( 'media-new.php' ); + const input = page.locator( '#plupload-upload-ui input[type="file"]' ); + await expect( input ).toBeAttached(); + + // The uploader sends one request per file. + const responses = []; + const uploaded = new Promise( ( resolve ) => { + page.on( 'response', ( response ) => { + if ( + response.url().includes( '/wp-admin/async-upload.php' ) && + 'POST' === response.request().method() + ) { + responses.push( response ); + if ( responses.length === filenames.length ) { + resolve(); + } + } + } ); + } ); + await input.setInputFiles( + FILES.map( ( file, i ) => ( { + name: filenames[ i ], + mimeType: 'application/octet-stream', + buffer: fs.readFileSync( path.join( FIXTURES_DIR, file ) ), + } ) ) + ); + await uploaded; + for ( const response of responses ) { + expect( response.ok(), 'the upload should succeed' ).toBe( true ); + } + + let states = getSyncStates( filenames ); + for ( const filename of filenames ) { + if ( states[ filename ] ) { + attachmentIds.push( states[ filename ].id ); + } + } + + // Let the auto-sync queue push the files, as it does on a live site. + // Syncing them from the test as well would race with the queue. + await expect + .poll( + () => { + states = getSyncStates( filenames ); + return filenames.filter( + ( filename ) => + states[ filename ] && + ! states[ filename ].synced && + ! states[ filename ].error + ); + }, + { + message: 'every file should finish syncing', + timeout: 90000, + intervals: [ 1000 ], + } + ) + .toEqual( [] ); + + for ( const filename of filenames ) { + const state = states[ filename ]; + expect + .soft( state, `${ filename } should be in the Media Library` ) + .toBeTruthy(); + expect + .soft( + state?.error, + `${ filename } should not have a sync error` + ) + .toBe( '' ); + expect + .soft( state?.publicId, `${ filename } should get a public ID` ) + .toBeTruthy(); + expect + .soft( state?.synced, `${ filename } should be fully synced` ) + .toBe( true ); + expect + .soft( + state?.url, + `${ filename } should have a Cloudinary URL` + ) + .toContain( 'res.cloudinary.com' ); + } + } ); +} ); diff --git a/tests/e2e/fixtures/test-archive.zip b/tests/e2e/fixtures/test-archive.zip new file mode 100644 index 0000000000000000000000000000000000000000..f8e1809eec3bade647805b3a0f6a9342749cd56e GIT binary patch literal 135 zcmWIWW@Zs#0D&I2=GgG5_vZ-$*&xgX#6_uzDY>b7B^4!(MadbNWvL3u`FSO&c_n&W l0p5&EBFwn80(FBy10#q+7!=^m$_5f)1VRfSZ3*Hq007@O8MOca literal 0 HcmV?d00001 diff --git a/tests/e2e/fixtures/test-audio.mp3 b/tests/e2e/fixtures/test-audio.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..5aea47576bf44272c2af7845d6dab6d7e8e5f410 GIT binary patch literal 16680 zcmeIzK@9*P48>5yA_%`6MsU%?n}Vjz&*q-JT-U$|)Q$7W1ZwvYDBedPf$9e0e14EX zaRYHY3lb=9AdY820>ur)@hnK7xPdsH1ql>45XZA1f#L?@corm3+&~=9f&_{ih~rt1 zKyd?cJPQ&iZXk|lK?21M#PKXhptylJo&^aMHxS3OAc5ir;&>J$P~1Qq&w>Ps8;Ijs KkU((*al8lAuXQm1 literal 0 HcmV?d00001 diff --git a/tests/e2e/fixtures/test-data.csv b/tests/e2e/fixtures/test-data.csv new file mode 100644 index 000000000..bed40b0fc --- /dev/null +++ b/tests/e2e/fixtures/test-data.csv @@ -0,0 +1,3 @@ +name,value +alpha,1 +beta,2 diff --git a/tests/e2e/fixtures/test-document.docx b/tests/e2e/fixtures/test-document.docx new file mode 100644 index 0000000000000000000000000000000000000000..532842ff1c23f23ad3ac456e10b67865d90c8790 GIT binary patch literal 912 zcmWIWW@Zs#U|`^2=y7X~J?SsC;Wd!Aj*)>u7)VDu=jWBA=9R>UR2HNb$Ldw&=F|r4 z^*d}JaIcc_VW_q8U8Z@?r(cL*K8tJQ0A#eitX<>-EaI*npgg{R%g=1%_9Bok0xF9 z_Bd(Hy!26(_qTAbVy}SE$_F3b2*rmtT@e=+d-A?v^1HQqljpjA%2mlxd%7b6?$7rrL3FGzW$sCgS-9TuZiy-N(Z2X&CW)b!VSPM(E^4I zH;|4mO3f+O*8`Eg=dJk;8St<@m>cYJFEfg*C1A21$4YH2_6{NQ-V8afLyNboGczl& zx!vAxe>(U32IHNHKF6%td_$QX)%P0t8C&ol|H|ia>X4>kbvuuk&xMbn)rTUVY?`bl zETq}t&9iLI;dz%-)VC;w+AYwYe9>LINOSQr#}nNbJj_e?F8z3y;a}pUIKz&;Sq(hi z2kLX|``jKKJiXd=di|UqULuh$y)zHqb$7kGI#yInBmd>`?mwKU9;-ceX7XI1ht31B zAP|@57p3T@e1{YST))q2+OR!D{Fq7WyB_un%nCiZ!ZQ>buHB1U z!EK)Z@4U~yKXpGUj^7iw?4$8>VWuUsNlLnm>i+wBzm3y1v$xz5Yw!(xL0_!IrQJ6MY*C!lIOP=c`y(53{SUpC+^IE@ ze^d6{g-T&5rL50ah=+z9>rH(8KIYHr75V|*j7%cTxRWr@LtxMVj5e$Z8r=Z&c!p?a pU}#{J0UCi6>*yNM!x5qJD^Mdws0MhmvVoK^1K~~}eUJ&n0|1KQSziDE literal 0 HcmV?d00001 diff --git a/tests/e2e/fixtures/test-sheet.xlsx b/tests/e2e/fixtures/test-sheet.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..ba33ce278b005a6a5319d395bfa03ac0de28e672 GIT binary patch literal 888 zcmWIWW@Zs#U|`^2=y7X~O;5|*{1M1o#>l`R45Xu-^Ycnl^Gf1FDhpDJWA!R>b807? z^*d}J(DL4<^=Y=K_0t9cuS?AK?hgXw5;mH5ivBXzX%WwPzJEv|~KCR#KIJ>52 z?~4YPju+jR+Mg&)H{>;Hnw8*C8GXGxh;{zO=UV#K71wPN`PpaR{2a6IysJ>uqcTQu49)(eR}%|D>}Jxp(MkJ~ps&HYW&N*Zb`zRF2uVQbbGB>eHu-#KsRZ?*uG5Mqlw-n0=I zG8(`T;s(<3MX5Q(`g$O;_xwh_CIbPs2X~ieW#D zdi5H%u0C9!^JZJ4Ag;*KFV8Q^PRh^E2F1H+k2l{T10L4zbCf>K+qJ=gL-pl4^#q`_=W0wzl@#oyW zC1=Vf-psLG-5m0|%JGU~Am6PMUVCP?Pmy_LcDiGi7+0Wh;8||D+uvF&eR%Huo3Uv7 zkNU6i0p5&EBFwlGE6~kg&;X1YtVtK$0Q9(oXlGz(U{nGcffTdo8qtFaq45t;BU-=( Tc(byB6fgtfb|Af)3B&^coPSq< literal 0 HcmV?d00001 From 7a6a99414765044a03e892e75506ab05698eb0b8 Mon Sep 17 00:00:00 2001 From: Gabriel de Tassigny Date: Thu, 3 Dec 2026 10:42:21 +0100 Subject: [PATCH 3/4] Read the local URL directly when creating the delivery relation For a file without dimensions, Delivery::create_delivery() got the local path from wp_get_attachment_url(). In the admin, the plugin filters that URL, which is how preparing the sync called back into itself. If the attachment already had a Cloudinary ID in the request, it also stored the Cloudinary URL as the local path. Use Media::local_url() instead, as get_sized() already does for images. The guard in Media::cloudinary_id() stays, for any other way a sync preparation can reach it. Each guard now has its own PHPUnit test. Also: - Give the upload sync e2e test a 150s timeout, above its 90s sync poll, so a slow sync fails with the file that didn't sync rather than a generic test timeout. - Drop the duplicate placeholder in cloudinary_id(), add the @uses tag to the upgrade cleanup, and fix a test comment. --- php/class-delivery.php | 4 +- php/class-media.php | 5 +- php/class-sync.php | 2 + tests/e2e/cloudinary-upload-sync.spec.js | 3 + .../test-media-cloudinary-id-reentry.php | 93 ++++++++++++++++++- 5 files changed, 98 insertions(+), 9 deletions(-) diff --git a/php/class-delivery.php b/php/class-delivery.php index 3e1a7f0f9..7b8fa3ae0 100644 --- a/php/class-delivery.php +++ b/php/class-delivery.php @@ -452,7 +452,9 @@ public function create_delivery( $attachment_id ) { } if ( empty( $sized_url ) ) { - $sized_url = Utils::get_path_from_url( wp_get_attachment_url( $attachment_id ), true ); + // The local URL, as get_sized() uses for images. The attachment URL filter could return the Cloudinary URL, + // or prepare this sync again from within itself. + $sized_url = Utils::get_path_from_url( $this->media->local_url( $attachment_id ), true ); } // Write the preserved values with the new relation itself. Restoring them afterwards would go through a deferred save that runs on shutdown, overwriting transformations the relation has just migrated out of post meta. self::create_size_relation( $attachment_id, $sized_url, $wh, $base, $preserve ); diff --git a/php/class-media.php b/php/class-media.php index 96f961220..011fd7f30 100644 --- a/php/class-media.php +++ b/php/class-media.php @@ -1798,10 +1798,7 @@ public function cloudinary_id( $attachment_id ) { // Check sync type allows for continued rendering. i.e meta update, breakpoints etc, will still allow the URL to work, // Where is type "file" will not since it's still being uploaded. if ( $this->sync->is_required( $sync_type, $attachment_id ) ) { - // Cache ID to prevent multiple lookups. - $cloudinary_ids[ $attachment_id ] = false; - - return false; // Return and render local URLs. + return false; // Return and render local URLs. The placeholder above stays cached, to prevent multiple lookups. } } diff --git a/php/class-sync.php b/php/class-sync.php index fe1496da9..20db24971 100644 --- a/php/class-sync.php +++ b/php/class-sync.php @@ -165,6 +165,8 @@ public static function get_loop_error_message( $type ) { * genuine loops flagged later, stay visible. * * @param string $old_version The version upgrading from. + * + * @uses action:cloudinary_version_upgrade */ public function clear_delivery_loop_errors( $old_version ) { if ( version_compare( $old_version, '3.3.9', '<' ) || version_compare( $old_version, '3.3.10', '>=' ) ) { diff --git a/tests/e2e/cloudinary-upload-sync.spec.js b/tests/e2e/cloudinary-upload-sync.spec.js index fd05d5724..b42504c70 100644 --- a/tests/e2e/cloudinary-upload-sync.spec.js +++ b/tests/e2e/cloudinary-upload-sync.spec.js @@ -162,6 +162,9 @@ test.describe( 'Cloudinary upload sync', { tag: '@serial' }, () => { admin, page, } ) => { + // Above the default 60s: the sync poll alone may take up to 90s. + test.setTimeout( 150_000 ); + // Fresh file names, so no asset from an earlier run applies. const stamp = Date.now(); const filenames = FILES.map( ( file ) => { diff --git a/tests/phpunit/tests/test-media-cloudinary-id-reentry.php b/tests/phpunit/tests/test-media-cloudinary-id-reentry.php index c6eb9be8d..d8eeb9226 100644 --- a/tests/phpunit/tests/test-media-cloudinary-id-reentry.php +++ b/tests/phpunit/tests/test-media-cloudinary-id-reentry.php @@ -3,20 +3,26 @@ * Tests for the re-entry guard in Cloudinary\Media::cloudinary_id(), and the cleanup of the errors left by that loop. * * For an attachment that isn't synced yet, cloudinary_id() prepares its sync, which runs the "delivery" sync type. - * For a file without dimensions (PDF, audio, documents), Delivery::create_delivery() has no sized URL and asks for - * wp_get_attachment_url() instead. In the admin, that goes through Media::attachment_url(), which calls + * For a file without dimensions (PDF, SVG, documents, audio), Delivery::create_delivery() has no sized URL and asked + * for wp_get_attachment_url() instead. In the admin, that goes through Media::attachment_url(), which calls * cloudinary_id() again for the same attachment. The "delivery" signature is only saved once create_delivery() * returns, so every nested call prepared the sync again, until the loop guard in Sync::validate_sync_type() flagged * the attachment with a sync error and it was never synced. See GitHub issue #1397. * + * Two guards now prevent it, each tested on its own: create_delivery() reads the local URL directly, and + * cloudinary_id() answers a nested call for an attachment whose sync it is preparing with a placeholder. + * * @package Cloudinary */ use Cloudinary\Connect; +use Cloudinary\Relate\Relationship; use Cloudinary\Sync; +use Cloudinary\Utils; /** - * Covers Media::cloudinary_id() for attachments without dimensions, and Sync::clear_delivery_loop_errors(). + * Covers Media::cloudinary_id() and Delivery::create_delivery() for attachments without dimensions, and + * Sync::clear_delivery_loop_errors(). */ class Test_Media_Cloudinary_Id_Reentry extends WP_UnitTestCase { @@ -123,7 +129,7 @@ public function test_preparing_the_sync_of_a_pdf_does_not_loop() { $attachment_id = $this->create_attachment( 'sample.pdf', self::PDF ); $this->assertEmpty( wp_get_attachment_metadata( $attachment_id )['width'] ?? null, 'The PDF must have no width, so create_delivery() falls back to its URL.' ); - // Each call to create_delivery() is one round of the loop. + // Each check of the "delivery" sync type is one round of the loop. $rounds = 0; add_filter( 'cloudinary_sync_type_retry_limit', @@ -232,6 +238,85 @@ function ( $limit, $type, $id ) use ( $attachment_id, &$rounds ) { $this->assertSame( $cloudinary_id, $media->cloudinary_id( $attachment_id ), 'Later calls must get the real Cloudinary ID too.' ); } + /** + * A call to cloudinary_id() for an attachment whose sync it is already preparing must not prepare it again, however + * the call is reached. + * + * @return void + */ + public function test_a_nested_call_does_not_prepare_the_sync_again() { + $this->get_sync(); + $media = $this->get_media(); + + $attachment_id = $this->create_attachment( 'sample.pdf', self::PDF ); + + // Call cloudinary_id() from within the sync preparation, and track how deep the preparations nest. Stop at 3, + // so the test ends even without the guard. + $depth = 0; + $max_depth = 0; + $nested = array(); + add_filter( + 'cloudinary_sync_type_retry_limit', + function ( $limit, $type, $id ) use ( $media, $attachment_id, &$depth, &$max_depth, &$nested ) { + if ( $attachment_id === $id && $depth < 3 ) { + ++$depth; + $max_depth = max( $max_depth, $depth ); + $nested[] = $media->cloudinary_id( $id ); + --$depth; + } + + return $limit; + }, + 10, + 3 + ); + + $media->cloudinary_id( $attachment_id ); + + $this->assertNotEmpty( $nested, 'The sync preparation should have made the nested call.' ); + $this->assertSame( 1, $max_depth, 'The nested call must not prepare the sync again.' ); + foreach ( $nested as $cloudinary_id ) { + $this->assertFalse( $cloudinary_id, 'The nested call must get the placeholder, so the local URL is used.' ); + } + } + + /** + * The "delivery" sync type must save the local path of a file without dimensions, even when the attachment URL + * filter returns its Cloudinary URL. + * + * @return void + */ + public function test_delivery_saves_the_local_path_of_a_file_without_dimensions() { + // Let cloudinary_id() return the real ID, as in test_the_outer_call_still_gets_the_cloudinary_id(). + add_filter( + 'cloudinary_sync_base_struct', + function ( $struct ) { + foreach ( $struct as $type => $structure ) { + $struct[ $type ]['required'] = false; + } + + return $struct; + } + ); + $this->get_sync(); + $media = $this->get_media(); + $delivery = \Cloudinary\get_plugin_instance()->get_component( 'delivery' ); + $media->add_live_url_filters(); + // Match an admin request: this frontend-only filter is registered because tests don't run in the admin. + remove_filter( 'wp_get_attachment_url', array( $delivery, 'ensure_relation' ) ); + + $attachment_id = $this->create_attachment( 'sample.pdf', self::PDF ); + $media->update_post_meta( $attachment_id, Sync::META_KEYS['public_id'], 'sample' ); + $this->assertNotEmpty( $media->cloudinary_id( $attachment_id ) ); + $this->assertStringContainsString( 'res.cloudinary.com', wp_get_attachment_url( $attachment_id ), 'The attachment URL should now be the Cloudinary one.' ); + + $delivery->create_delivery( $attachment_id ); + + $sized_url = Relationship::get_relationship( $attachment_id )->sized_url; + $this->assertStringNotContainsString( 'cloudinary.com', $sized_url ); + $this->assertSame( Utils::get_path_from_url( $media->local_url( $attachment_id ), true ), $sized_url ); + } + /** * Create an attachment flagged with a sync error. * From 8b7393003e7f53ea4dacecb4eaf838d15e5b3d57 Mon Sep 17 00:00:00 2001 From: Gabriel de Tassigny Date: Thu, 3 Dec 2026 15:20:07 +0100 Subject: [PATCH 4/4] Run the loop error cleanup once, for any release without the fix The cleanup only ran on upgrades from 3.3.9, which assumed the next release would contain the fix. A release without it, such as 3.4.0 in uat, has the same loop, so sites upgrading from it kept their errors. Run it on the first upgrade to a version with the fix instead: the version upgraded from is then the last one without it, so clear the errors when it is 3.3.9 or later. Record that it ran, so later upgrades keep genuine loop errors visible, including on sites that installed a version with the fix. Drop the switch through every installed language: the plugin ships no translations, and each switch reloads every text domain. Clear the English message and the current locale's. Set a public ID in the nested attachment URL test, so a Cloudinary URL could show up and the test fails without the fixes, and remove the frontend-only filter that PHPUnit registers. --- php/class-sync.php | 28 +++---- .../test-media-cloudinary-id-reentry.php | 75 +++++++++++++------ 2 files changed, 69 insertions(+), 34 deletions(-) diff --git a/php/class-sync.php b/php/class-sync.php index 20db24971..6b35c96ad 100644 --- a/php/class-sync.php +++ b/php/class-sync.php @@ -113,6 +113,7 @@ class Sync implements Setup, Assets { 'version' => '_cloudinary_version', 'raw_url' => '_cloudinary_url', 'db_version' => '_cloudinary_db_version', + 'loop_errors_cleared' => '_cloudinary_delivery_loop_errors_cleared', 'debug' => '_cloudinary_debug', ); @@ -159,33 +160,34 @@ public static function get_loop_error_message( $type ) { /** * Clear the sync loop errors that 3.3.9 flagged on the "delivery" sync type, so those attachments are retried. * - * In 3.3.9, files without dimensions (PDF, audio, documents) got this error on upload, from a loop between + * From 3.3.9, files without dimensions (PDF, SVG, documents, audio) got this error on upload, from a loop between * preparing their sync and getting their URL. Now that the loop is fixed, they can sync without anyone clearing the - * error by hand. Only this exact error is cleared, and only when upgrading from 3.3.9: other sync errors, and - * genuine loops flagged later, stay visible. + * error by hand. Only this exact error is cleared. + * + * Runs once, on the first upgrade to a version with the fix. The version upgraded from is then the last one without + * it, so the errors are cleared when it is 3.3.9 or later, whatever release that is. Loops flagged after the fix, + * which are genuine, stay visible. * * @param string $old_version The version upgrading from. * * @uses action:cloudinary_version_upgrade */ public function clear_delivery_loop_errors( $old_version ) { - if ( version_compare( $old_version, '3.3.9', '<' ) || version_compare( $old_version, '3.3.10', '>=' ) ) { + if ( get_option( self::META_KEYS['loop_errors_cleared'] ) ) { + return; + } + update_option( self::META_KEYS['loop_errors_cleared'], true, false ); + + if ( version_compare( $old_version, '3.3.9', '<' ) ) { return; } - // The message is saved in the language of the request that flagged it, e.g. the uploading user's language, so - // clear it in every installed language, as well as in English. + // The plugin ships no translations, so the message is in English. Clear the current locale's too, in case a + // site translates it. $messages = array( 'Sync loop detected: the "delivery" sync state could not be saved.', self::get_loop_error_message( 'delivery' ), ); - foreach ( get_available_languages() as $locale ) { - if ( switch_to_locale( $locale ) ) { - $messages[] = self::get_loop_error_message( 'delivery' ); - restore_previous_locale(); - } - } - foreach ( array_unique( $messages ) as $message ) { delete_metadata( 'post', 0, self::META_KEYS['sync_error'], $message, true ); } diff --git a/tests/phpunit/tests/test-media-cloudinary-id-reentry.php b/tests/phpunit/tests/test-media-cloudinary-id-reentry.php index d8eeb9226..736288d9a 100644 --- a/tests/phpunit/tests/test-media-cloudinary-id-reentry.php +++ b/tests/phpunit/tests/test-media-cloudinary-id-reentry.php @@ -152,7 +152,8 @@ function ( $limit, $type, $id ) use ( $attachment_id, &$rounds ) { } /** - * Within its own sync preparation, the attachment URL must be the local one. + * Within its own sync preparation, the attachment URL must be the local one, even for an attachment that already + * has a public ID, which the admin's attachment URL filter would turn into a Cloudinary URL. * * @return void */ @@ -160,8 +161,12 @@ public function test_the_nested_attachment_url_is_the_local_one() { $this->get_sync(); $media = $this->get_media(); $media->add_live_url_filters(); + // Match an admin request: this frontend-only filter is registered because tests don't run in the admin. + remove_filter( 'wp_get_attachment_url', array( \Cloudinary\get_plugin_instance()->get_component( 'delivery' ), 'ensure_relation' ) ); $attachment_id = $this->create_attachment( 'sample.pdf', self::PDF ); + $media->update_post_meta( $attachment_id, Sync::META_KEYS['public_id'], 'sample' ); + $local_url = wp_get_upload_dir()['baseurl'] . '/' . get_post_meta( $attachment_id, '_wp_attached_file', true ); $nested_urls = array(); add_filter( @@ -179,12 +184,9 @@ function ( $url, $id ) use ( $attachment_id, &$nested_urls ) { $media->cloudinary_id( $attachment_id ); - // Only read the local URL now: getting it runs other wp_get_attachment_url filters, which would prepare the - // "delivery" sync type before cloudinary_id() does. - $local_url = $media->local_url( $attachment_id ); - $this->assertNotEmpty( $nested_urls, 'create_delivery() should have asked for the attachment URL.' ); foreach ( $nested_urls as $url ) { + $this->assertStringNotContainsString( 'res.cloudinary.com', $url ); $this->assertSame( $local_url, $url ); } } @@ -337,12 +339,12 @@ protected function create_errored_attachment( $error ) { } /** - * Upgrading from 3.3.9 clears the "delivery" sync loop error, in English and in the current language, so the - * affected attachments are synced again. Every other sync error is kept. + * The first upgrade to a version with the fix clears the "delivery" sync loop error, in English and in the current + * language, when the site ran 3.3.9 or a later release without the fix. Every other sync error is kept. * * @return void */ - public function test_upgrade_from_3_3_9_clears_only_the_delivery_loop_error() { + public function test_upgrade_from_3_3_9_or_later_clears_only_the_delivery_loop_error() { $sync = $this->get_sync(); $english = 'Sync loop detected: the "delivery" sync state could not be saved.'; @@ -361,30 +363,37 @@ function ( $translation, $text, $domain ) { ); $this->assertNotSame( $english, Sync::get_loop_error_message( 'delivery' ) ); - $english_loop = $this->create_errored_attachment( $english ); - $translated_loop = $this->create_errored_attachment( Sync::get_loop_error_message( 'delivery' ) ); - $other_loop = $this->create_errored_attachment( Sync::get_loop_error_message( 'file' ) ); - $other_error = $this->create_errored_attachment( 'Invalid file type' ); + // 3.3.9 introduced the loop. Releases after it without the fix have it too. + foreach ( array( '3.3.9', '3.3.10', '3.4.0' ) as $old_version ) { + delete_option( Sync::META_KEYS['loop_errors_cleared'] ); + $english_loop = $this->create_errored_attachment( $english ); + $translated_loop = $this->create_errored_attachment( Sync::get_loop_error_message( 'delivery' ) ); + $other_loop = $this->create_errored_attachment( Sync::get_loop_error_message( 'file' ) ); + $other_error = $this->create_errored_attachment( 'Invalid file type' ); - $sync->clear_delivery_loop_errors( '3.3.9' ); + $sync->clear_delivery_loop_errors( $old_version ); - $this->assertEmpty( get_post_meta( $english_loop, Sync::META_KEYS['sync_error'], true ) ); - $this->assertEmpty( get_post_meta( $translated_loop, Sync::META_KEYS['sync_error'], true ) ); - $this->assertSame( Sync::get_loop_error_message( 'file' ), get_post_meta( $other_loop, Sync::META_KEYS['sync_error'], true ) ); - $this->assertSame( 'Invalid file type', get_post_meta( $other_error, Sync::META_KEYS['sync_error'], true ) ); + $this->assertEmpty( get_post_meta( $english_loop, Sync::META_KEYS['sync_error'], true ), "Upgrading from $old_version must clear the English error." ); + $this->assertEmpty( get_post_meta( $translated_loop, Sync::META_KEYS['sync_error'], true ), "Upgrading from $old_version must clear the translated error." ); + $this->assertSame( Sync::get_loop_error_message( 'file' ), get_post_meta( $other_loop, Sync::META_KEYS['sync_error'], true ) ); + $this->assertSame( 'Invalid file type', get_post_meta( $other_error, Sync::META_KEYS['sync_error'], true ) ); + } } /** - * Only 3.3.9 flagged these errors by mistake. After an upgrade from any other version, a "delivery" sync loop error - * is a genuine one, and must stay visible. + * Versions before 3.3.9 didn't have the loop, so after an upgrade from one of them, or a new install, a "delivery" + * sync loop error is a genuine one, and must stay visible. * * @return void */ - public function test_upgrade_from_other_versions_keeps_the_delivery_loop_error() { + public function test_upgrade_from_before_3_3_9_keeps_the_delivery_loop_error() { $sync = $this->get_sync(); $attachment_id = $this->create_errored_attachment( Sync::get_loop_error_message( 'delivery' ) ); - foreach ( array( '3.3.8', '3.3.10', '3.4.0' ) as $old_version ) { + // 2.0.1 is what the upgrade reports on a new install. + foreach ( array( '3.3.8', '2.0.1' ) as $old_version ) { + delete_option( Sync::META_KEYS['loop_errors_cleared'] ); + $sync->clear_delivery_loop_errors( $old_version ); $this->assertSame( @@ -395,6 +404,30 @@ public function test_upgrade_from_other_versions_keeps_the_delivery_loop_error() } } + /** + * The cleanup runs only on the first upgrade to a version with the fix. Loops flagged after that are genuine, and + * later upgrades must keep them visible, including on sites that installed a version with the fix. + * + * @return void + */ + public function test_the_cleanup_runs_only_once() { + $sync = $this->get_sync(); + + foreach ( array( '3.3.9', '2.0.1' ) as $first_old_version ) { + delete_option( Sync::META_KEYS['loop_errors_cleared'] ); + $sync->clear_delivery_loop_errors( $first_old_version ); + + $attachment_id = $this->create_errored_attachment( Sync::get_loop_error_message( 'delivery' ) ); + $sync->clear_delivery_loop_errors( '3.4.1' ); + + $this->assertSame( + Sync::get_loop_error_message( 'delivery' ), + get_post_meta( $attachment_id, Sync::META_KEYS['sync_error'], true ), + "After a first upgrade from $first_old_version, a later upgrade must keep the error." + ); + } + } + /** * The cleanup runs on the plugin's version upgrade. *