-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathclass-wp-sync-post-meta-storage.php
More file actions
376 lines (332 loc) · 9.52 KB
/
class-wp-sync-post-meta-storage.php
File metadata and controls
376 lines (332 loc) · 9.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
<?php
/**
* WP_Sync_Post_Meta_Storage class
*
* @package WordPress
*/
/**
* Core class that provides an interface for storing and retrieving sync
* updates and awareness data during a collaborative session.
*
* Data is stored as post meta on a dedicated post per room of a custom post type.
*
* @since 7.0.0
*
* @access private
*/
class WP_Sync_Post_Meta_Storage implements WP_Sync_Storage {
/**
* Post type for sync storage.
*
* @since 7.0.0
* @var string
*/
const POST_TYPE = 'wp_sync_storage';
/**
* Meta key for awareness state.
*
* @since 7.0.0
* @var string
*/
const AWARENESS_META_KEY = 'wp_sync_awareness';
/**
* Meta key for sync updates.
*
* @since 7.0.0
* @var string
*/
const SYNC_UPDATE_META_KEY = 'wp_sync_update';
/**
* Cache of cursors by room.
*
* @since 7.0.0
* @var array<string, int>
*/
private array $room_cursors = array();
/**
* Cache of update counts by room.
*
* @since 7.0.0
* @var array<string, int>
*/
private array $room_update_counts = array();
/**
* Cache of storage post IDs by room hash.
*
* @since 7.0.0
* @var array<string, int>
*/
private static array $storage_post_ids = array();
/**
* Adds a sync update to a given room.
*
* @since 7.0.0
*
* @param string $room Room identifier.
* @param mixed $update Sync update.
* @return bool True on success, false on failure.
*/
public function add_update( string $room, $update ): bool {
$post_id = $this->get_storage_post_id( $room );
if ( null === $post_id ) {
return false;
}
$meta_id = $this->with_suspended_posts_last_changed_update(
fn() => add_post_meta( $post_id, self::SYNC_UPDATE_META_KEY, $update, false )
);
if ( $meta_id ) {
wp_cache_delete( "sync_room_state_{$this->get_room_hash( $room )}", 'sync' );
}
return (bool) $meta_id;
}
/**
* Gets awareness state for a given room.
*
* Awareness data is stored in a transient with a short TTL. Transients may
* be evicted at any time (cache flush, deploy, expiration), in which case
* this method returns an empty array and clients briefly appear offline
* until the next poll repopulates state (typically under one second).
*
* @since 7.0.0
*
* @param string $room Room identifier.
* @return array<int, mixed> Awareness state.
*/
public function get_awareness_state( string $room ): array {
$awareness = get_transient( "sync_awareness_{$this->get_room_hash( $room )}" );
if ( ! is_array( $awareness ) ) {
return array();
}
return array_values( $awareness );
}
/**
* Sets awareness state for a given room.
*
* Uses a transient rather than post meta to avoid database write churn,
* since awareness data (cursor positions, selections) is ephemeral and
* repopulated on every client poll. A cache eviction only causes a brief
* flicker rather than data loss.
*
* @since 7.0.0
*
* @param string $room Room identifier.
* @param array<int, mixed> $awareness Serializable awareness state.
* @return bool True on success, false on failure.
*/
public function set_awareness_state( string $room, array $awareness ): bool {
return set_transient( "sync_awareness_{$this->get_room_hash( $room )}", $awareness, MINUTE_IN_SECONDS );
}
/**
* Gets the current cursor for a given room.
*
* The cursor is set during get_updates_after_cursor() and represents the
* highest meta_id seen for the room's sync updates.
*
* @since 7.0.0
*
* @param string $room Room identifier.
* @return int Current cursor for the room.
*/
public function get_cursor( string $room ): int {
return $this->room_cursors[ $room ] ?? 0;
}
/**
* Gets or creates the storage post for a given room.
*
* Each room gets its own dedicated post so that post meta cache
* invalidation is scoped to a single room rather than all of them.
*
* @since 7.0.0
*
* @param string $room Room identifier.
* @return int|null Post ID.
*/
private function get_storage_post_id( string $room ): ?int {
$room_hash = $this->get_room_hash( $room );
if ( isset( self::$storage_post_ids[ $room_hash ] ) ) {
return self::$storage_post_ids[ $room_hash ];
}
// Try to find an existing post for this room.
$posts = get_posts(
array(
'post_type' => self::POST_TYPE,
'posts_per_page' => 1,
'post_status' => 'publish',
'name' => $room_hash,
'fields' => 'ids',
)
);
$post_id = array_first( $posts );
if ( is_int( $post_id ) ) {
self::$storage_post_ids[ $room_hash ] = $post_id;
return $post_id;
}
// Create new post for this room.
$post_id = wp_insert_post(
array(
'post_type' => self::POST_TYPE,
'post_status' => 'publish',
'post_title' => 'Sync Storage',
'post_name' => $room_hash,
)
);
if ( is_int( $post_id ) ) {
self::$storage_post_ids[ $room_hash ] = $post_id;
return $post_id;
}
return null;
}
/**
* Gets the number of updates stored for a given room.
*
* @since 7.0.0
*
* @param string $room Room identifier.
* @return int Number of updates stored for the room.
*/
public function get_update_count( string $room ): int {
return $this->room_update_counts[ $room ] ?? 0;
}
/**
* Retrieves sync updates from a room after the given cursor.
*
* @since 7.0.0
*
* @param string $room Room identifier.
* @param int $cursor Return updates after this cursor (meta_id).
* @return array<int, mixed> Sync updates.
*/
public function get_updates_after_cursor( string $room, int $cursor ): array {
global $wpdb;
$room_hash = $this->get_room_hash( $room );
$state_cache_key = "sync_room_state_{$room_hash}";
$cached = wp_cache_get( $state_cache_key, 'sync' );
if ( is_array( $cached ) && $cached['cursor'] <= $cursor ) {
$this->room_cursors[ $room ] = $cached['cursor'];
$this->room_update_counts[ $room ] = $cached['count'];
return array();
}
$post_id = $this->get_storage_post_id( $room );
if ( null === $post_id ) {
$this->room_cursors[ $room ] = 0;
$this->room_update_counts[ $room ] = 0;
return array();
}
// Capture the current room state first so the returned cursor is race-safe.
$stats = $wpdb->get_row(
$wpdb->prepare(
"SELECT COUNT(*) AS total_updates, COALESCE( MAX(meta_id), 0 ) AS max_meta_id FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = %s",
$post_id,
self::SYNC_UPDATE_META_KEY
)
);
$total_updates = $stats ? (int) $stats->total_updates : 0;
$max_meta_id = $stats ? (int) $stats->max_meta_id : 0;
$this->room_update_counts[ $room ] = $total_updates;
$this->room_cursors[ $room ] = $max_meta_id;
wp_cache_set(
$state_cache_key,
array(
'cursor' => $max_meta_id,
'count' => $total_updates,
),
'sync'
);
if ( $max_meta_id <= $cursor ) {
return array();
}
$rows = $wpdb->get_results(
$wpdb->prepare(
"SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = %s AND meta_id > %d AND meta_id <= %d ORDER BY meta_id ASC",
$post_id,
self::SYNC_UPDATE_META_KEY,
$cursor,
$max_meta_id
)
);
if ( ! $rows ) {
return array();
}
$updates = array();
foreach ( $rows as $row ) {
$update = maybe_unserialize( $row->meta_value );
$updates[] = $update;
}
return $updates;
}
/**
* Removes updates from a room that are older than the given cursor.
*
* @since 7.0.0
*
* @param string $room Room identifier.
* @param int $cursor Remove updates with meta_id < this cursor.
* @return bool True on success, false on failure.
*/
public function remove_updates_before_cursor( string $room, int $cursor ): bool {
global $wpdb;
$post_id = $this->get_storage_post_id( $room );
if ( null === $post_id ) {
return false;
}
$deleted_rows = $wpdb->query(
$wpdb->prepare(
"DELETE FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = %s AND meta_id < %d",
$post_id,
self::SYNC_UPDATE_META_KEY,
$cursor
)
);
if ( false === $deleted_rows ) {
return false;
}
if ( $deleted_rows > 0 ) {
wp_cache_delete( $post_id, 'post_meta' );
wp_cache_delete( "sync_room_state_{$this->get_room_hash( $room )}", 'sync' );
}
return true;
}
/**
* Invokes the provided callback while the suspending setting the posts last_changed cache key.
*
* @since 7.0.0
* @see wp_cache_set_posts_last_changed()
*
* @template T
* @param Closure(): T $callback Callback.
* @return T Return value from the callback.
*/
private function with_suspended_posts_last_changed_update( Closure $callback ) {
$priorities = array(
'added_post_meta' => has_action( 'added_post_meta', 'wp_cache_set_posts_last_changed' ),
'updated_post_meta' => has_action( 'updated_post_meta', 'wp_cache_set_posts_last_changed' ),
'deleted_post_meta' => has_action( 'deleted_post_meta', 'wp_cache_set_posts_last_changed' ),
);
foreach ( $priorities as $action => $priority ) {
if ( false !== $priority ) {
remove_action( $action, 'wp_cache_set_posts_last_changed', $priority );
}
}
$return_value = $callback();
foreach ( $priorities as $action => $priority ) {
if ( false !== $priority ) {
add_action( $action, 'wp_cache_set_posts_last_changed', $priority );
}
}
return $return_value;
}
/**
* Returns a hash of the room identifier.
*
* Used as the post slug for storage posts, as a segment in cache keys,
* and as part of transient names.
*
* @since 7.0.0
*
* @param string $room Room identifier.
* @return string MD5 hash of the room.
*/
private function get_room_hash( string $room ): string {
return md5( $room );
}
}