Skip to content
Open
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
28 changes: 23 additions & 5 deletions src/wp-includes/collaboration/class-wp-sync-post-meta-storage.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ class WP_Sync_Post_Meta_Storage implements WP_Sync_Storage {
const POST_TYPE = 'wp_sync_storage';

/**
* Meta key for awareness state.
* Transient prefix for awareness state.
*
* @since 7.0.0
* @var string
*/
const AWARENESS_META_KEY = 'wp_sync_awareness';
const AWARENESS_TRANSIENT_PREFIX = 'wp_sync_awareness';

/**
* Meta key for sync updates.
Expand Down Expand Up @@ -123,6 +123,24 @@ static function ( $update ): bool {
return $updates;
}

/**
* Gets the transient key for awareness state for a given post ID.
*
* @since 7.0.0
*
* @param int $post_id Post ID.
* @return string Transient key for awareness state.
*/
public function get_awareness_transient_key( $post_id ) {
$cache_key = self::AWARENESS_TRANSIENT_PREFIX . '_' . $post_id;
if ( strlen( $cache_key ) <= 172 ) {
// Safe length for a transient key.
return $cache_key;
}
// If the cache key is too long, hash it to ensure it fits within limits.
return md5( $cache_key );
}

/**
* Gets awareness state for a given room.
*
Expand All @@ -137,7 +155,7 @@ public function get_awareness_state( string $room ): array {
return array();
}

$awareness = get_post_meta( $post_id, self::AWARENESS_META_KEY, true );
$awareness = get_transient( $this->get_awareness_transient_key( $post_id ) );

if ( ! is_array( $awareness ) ) {
return array();
Expand All @@ -161,8 +179,8 @@ public function set_awareness_state( string $room, array $awareness ): bool {
return false;
}

// update_post_meta returns false if the value is the same as the existing value.
update_post_meta( $post_id, self::AWARENESS_META_KEY, $awareness );
// set_transient() can return false if the value is the same as the existing value, which is considered a success regardless.
set_transient( $this->get_awareness_transient_key( $post_id ), $awareness, HOUR_IN_SECONDS );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What this doesn't still address is the issue of the race condition, yeah? Consider the case where two clients attempt to update the same post meta at the same time. As I understand, this is where #11068 would still be advantageous.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought I'd seen them coming from different post IDs but catching up so maybe it needs a room hash.

return true;
}

Expand Down
Loading