Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion php/class-delivery.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand Down
11 changes: 7 additions & 4 deletions php/class-media.php
Original file line number Diff line number Diff line change
Expand Up @@ -1788,14 +1788,17 @@ 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.
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.
}
}

Expand Down
64 changes: 55 additions & 9 deletions php/class-sync.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
);

Expand All @@ -137,6 +138,59 @@ 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.
*
* 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.
*
* 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 ( 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 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 ( array_unique( $messages ) as $message ) {
delete_metadata( 'post', 0, self::META_KEYS['sync_error'], $message, true );
}
}

/**
Expand Down Expand Up @@ -947,15 +1001,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;
}
Expand Down
259 changes: 259 additions & 0 deletions tests/e2e/cloudinary-upload-sync.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,259 @@
/**
* 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<string, string>}
*/
const SETTINGS = {
auto_sync: 'on',
offload: 'dual_full',
svg_support: 'on',
};

/** @type {Record<string, string>|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<string, { id: number, error: string, publicId: string, synced: boolean, url: string }|null>} 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,
} ) => {
// 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 ) => {
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' );
}
} );
} );
Binary file added tests/e2e/fixtures/test-archive.zip
Binary file not shown.
Binary file added tests/e2e/fixtures/test-audio.mp3
Binary file not shown.
3 changes: 3 additions & 0 deletions tests/e2e/fixtures/test-data.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
name,value
alpha,1
beta,2
Binary file added tests/e2e/fixtures/test-document.docx
Binary file not shown.
Binary file added tests/e2e/fixtures/test-document.pdf
Binary file not shown.
Binary file added tests/e2e/fixtures/test-sheet.xlsx
Binary file not shown.
Loading
Loading