summaryrefslogtreecommitdiff
blob: 34b0c3f42492517142333de49a6e581b4baccb48 (plain)
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
<?php
declare( strict_types = 1 );

namespace MediaWiki\Extensions\Translate\Synchronization;

use BagOStuff;
use DateTime;

/**
 * Message group synchronization cache. Handles storage of data in the cache
 * to track which groups are currently being synchronized
 * @author Abijeet Patro
 * @license GPL-2.0-or-later
 * @since 2020.06
 */
class GroupSynchronizationCache {
	private const CACHE_PREFIX = 'translate-msg-group-sync';

	private const OP_ADD = 'add';

	private const OP_DEL = 'remove';

	/** @var BagOStuff */
	private $cache;

	/** @var int */
	private $timeout;

	public function __construct( BagOStuff $cache, int $timeout = 600 ) {
		$this->cache = $cache;
		$this->timeout = $timeout;
	}

	/**
	 * Get the groups currently in sync
	 * @return string[]
	 */
	public function getGroupsInSync(): array {
		$groupsCacheKey = $this->getGroupsKey();
		$groupsInSync = $this->cache->get( $groupsCacheKey );

		return $groupsInSync === false ? [] : $groupsInSync;
	}

	/** Start the synchronization process for a group with the given groupId */
	public function startSync( string $groupId ): void {
		$this->cache->set( $this->getSyncTimeKey( $groupId ), ( new DateTime() )->getTimestamp() );
		$this->cache->set( $this->getGroupKey( $groupId ), [] );

		$this->modifyGroupsInSync( $groupId, self::OP_ADD );
	}

	public function getSyncStartTime( string $groupId ): ?int {
		$timestamp = $this->cache->get( $this->getSyncTimeKey( $groupId ) );
		if ( $timestamp === false ) {
			return null;
		}

		return (int)$timestamp;
	}

	/**
	 * End synchronization for a group. Removes the sync time, deletes the group key, and
	 * removes the groupId from groups in sync list
	 */
	public function endSync( string $groupId ): void {
		// Remove all the messages for the group
		$groupKey = $this->getGroupKey( $groupId );
		$groupMessageKeys = $this->cache->get( $groupKey );
		$this->removeMessages( ...$groupMessageKeys );

		// Remove the group message list
		$this->cache->delete( $groupKey );

		// Delete the group sync start time
		$this->cache->delete( $this->getSyncTimeKey( $groupId ) );

		// Remove the group from groups in sync list
		$this->modifyGroupsInSync( $groupId, self::OP_DEL );
	}

	/** Add multiple messages from a group to the cache */
	public function addMessages( string $groupId, MessageUpdateParameter ...$messageParams ): void {
		$messagesToAdd = [];
		foreach ( $messageParams as $messageParam ) {
			$messagesToAdd[ $this->getMessageTitleKey( $messageParam->getPageName() ) ] =
				$messageParam;
		}

		$this->cache->setMulti( $messagesToAdd );
		$this->modifyGroupMessagesInSync( $groupId, $messageParams, self::OP_ADD );
	}

	/** Check if the group is in synchronization */
	public function isGroupBeingProcessed( string $groupId ): bool {
		$groupMessages = $this->cache->get( $this->getGroupKey( $groupId ) );
		return $groupMessages !== false;
	}

	/**
	 * Return messages keys belonging to group Id currently in synchronization.
	 * @param string $groupId
	 * @return string[]
	 */
	public function getGroupMessageKeys( string $groupId ): array {
		$groupMessages = $this->cache->get( $this->getGroupKey( $groupId ) );
		if ( $groupMessages === false ) {
			return [];
		}

		return $groupMessages;
	}

	/**
	 * Return values for multiple messages from the cache.
	 * @param string ...$messageKeys
	 * @return MessageUpdateParameter[] Returns a key value pair, with the key being the
	 * messageKey and value being MessageUpdateParameter or null if the key is not available
	 * in the cache.
	 */
	public function getMessages( string ...$messageKeys ): array {
		$messageCacheKeys = [];
		foreach ( $messageKeys as $messageKey ) {
			$messageCacheKeys[] = $this->getMessageTitleKey( $messageKey );
		}

		$messageParams = $this->cache->getMulti( $messageCacheKeys );

		$allMessageParams = [];
		foreach ( $messageCacheKeys as $index => $messageCacheKey ) {
			$allMessageParams[$messageKeys[$index]] = $messageParams[$messageCacheKey] ?? null;
		}

		return $allMessageParams;
	}

	/**
	 * Update the group cache with the latest information with the status of message
	 * update jobs, then check if the group has timed out and returns the latest information
	 */
	public function getSynchronizationStatus( string $groupId ): GroupSynchronizationResponse {
		$this->syncGroup( $groupId );
		$syncStartTime = $this->getSyncStartTime( $groupId );
		if ( !$syncStartTime ) {
			// Processing is done
			return new GroupSynchronizationResponse( $groupId, [], false );
		}

		$hasTimedOut = $this->hasGroupTimedOut( $syncStartTime );
		$remainingMessages = $this->getGroupMessageKeys( $groupId );

		return new GroupSynchronizationResponse(
			$groupId,
			$remainingMessages,
			$hasTimedOut
		);
	}

	/**
	 * Remove messages from the cache. Removes the message keys, but DOES NOT the update group
	 * message key list.
	 */
	public function removeMessages( string ...$messageKeys ): void {
		$messageCacheKeys = [];
		foreach ( $messageKeys as $key ) {
			$messageCacheKeys[] = $this->getMessageTitleKey( $key );
		}

		$this->cache->deleteMulti( $messageCacheKeys );
	}

	/**
	 * Check messages keys that are still present in the cache and update the list of keys
	 * in the message group.
	 */
	private function syncGroup( string $groupId ): void {
		$groupCacheKey = $this->getGroupKey( $groupId );
		$groupMessages = $this->cache->get( $groupCacheKey );
		if ( $groupMessages === false ) {
			return;
		}

		$messageCacheKeys = [];
		foreach ( $groupMessages as $messageKey ) {
			$messageCacheKeys[] = $this->getMessageTitleKey( $messageKey );
		}

		$messageParams = $this->cache->getMulti( $messageCacheKeys );

		// No keys are present, delete the message and mark the group as synced
		if ( !$messageParams ) {
			$this->endSync( $groupId );
			return;
		}

		// Make a list of remaining jobs that are running.
		$remainingJobTitle = [];
		foreach ( $messageCacheKeys as $index => $messageCacheKey ) {
			if ( isset( $messageParams[$messageCacheKey] ) ) {
				$groupMessageTitle = $groupMessages[$index];
				$remainingJobTitle[] = $groupMessageTitle;
			}
		}

		// Set the group cache with the remaining job title.
		$this->cache->set( $groupCacheKey, $remainingJobTitle );
	}

	private function hasGroupTimedOut( int $syncStartTime ): bool {
		$secondsSinceSyncStart = ( new DateTime() )->getTimestamp() - $syncStartTime;
		return $secondsSinceSyncStart > $this->timeout;
	}

	private function modifyGroupsInSync( string $groupId, string $op ): void {
		$groupsCacheKey = $this->getGroupsKey();
		$this->cache->lock( $groupsCacheKey );

		$groupsInSync = $this->getGroupsInSync();
		if ( $groupsInSync === [] && $op === self::OP_DEL ) {
			return;
		}

		$this->modifyArray( $groupsInSync, $groupId, $op );

		$this->cache->set( $groupsCacheKey, $groupsInSync );
		$this->cache->unlock( $groupsCacheKey );
	}

	private function modifyGroupMessagesInSync(
		string $groupId, array $messageParams, string $op
	): void {
		$groupCacheKey = $this->getGroupKey( $groupId );

		$this->cache->lock( $groupCacheKey );

		$groupMessages = $this->getGroupMessageKeys( $groupId );
		if ( $groupMessages === [] && $op === self::OP_DEL ) {
			return;
		}

		/** @var MessageUpdateParameter $messageParam */
		foreach ( $messageParams as $messageParam ) {
			$messageTitle = $messageParam->getPageName();
			$this->modifyArray( $groupMessages, $messageTitle, $op );
		}

		$this->cache->set( $groupCacheKey, $groupMessages );
		$this->cache->unlock( $groupCacheKey );
	}

	private function modifyArray(
		array &$toModify, string $needle, string $op
	): void {
		$needleIndex = array_search( $needle, $toModify );
		if ( $op === self::OP_ADD && $needleIndex === false ) {
			$toModify[] = $needle;
		} elseif ( $op === self::OP_DEL && $needleIndex !== false ) {
			array_splice( $toModify, $needleIndex, 1 );
		}
	}

	// Cache keys related functions start here.

	private function getGroupsKey(): string {
		return $this->cache->makeKey( self::CACHE_PREFIX );
	}

	private function getSyncTimeKey( string $groupId ): string {
		return $this->cache->makeKey( self::CACHE_PREFIX, $groupId, 'time' );
	}

	private function getGroupKey( string $groupId ): string {
		return $this->cache->makeKey( self::CACHE_PREFIX, 'group', $groupId );
	}

	private function getMessageTitleKey( string $title ): string {
		return $this->cache->makeKey( self::CACHE_PREFIX, 'msg-title', $title );
	}

}