Merge "mediawiki.requestIdleCallback: Re-enable use of native requestIdleCallback"
[lhc/web/wiklou.git] / includes / externalstore / ExternalStoreDB.php
1 <?php
2 /**
3 * External storage in SQL database.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use Wikimedia\Rdbms\LoadBalancer;
24
25 /**
26 * DB accessable external objects.
27 *
28 * In this system, each store "location" maps to a database "cluster".
29 * The clusters must be defined in the normal LBFactory configuration.
30 *
31 * @ingroup ExternalStorage
32 */
33 class ExternalStoreDB extends ExternalStoreMedium {
34 /**
35 * The provided URL is in the form of DB://cluster/id
36 * or DB://cluster/id/itemid for concatened storage.
37 *
38 * @param string $url
39 * @return string|bool False if missing
40 * @see ExternalStoreMedium::fetchFromURL()
41 */
42 public function fetchFromURL( $url ) {
43 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
44 $ret = $this->fetchBlob( $cluster, $id, $itemID );
45
46 if ( $itemID !== false && $ret !== false ) {
47 return $ret->getItem( $itemID );
48 }
49
50 return $ret;
51 }
52
53 /**
54 * Fetch data from given external store URLs.
55 * The provided URLs are in the form of DB://cluster/id
56 * or DB://cluster/id/itemid for concatened storage.
57 *
58 * @param array $urls An array of external store URLs
59 * @return array A map from url to stored content. Failed results
60 * are not represented.
61 */
62 public function batchFetchFromURLs( array $urls ) {
63 $batched = $inverseUrlMap = [];
64 foreach ( $urls as $url ) {
65 list( $cluster, $id, $itemID ) = $this->parseURL( $url );
66 $batched[$cluster][$id][] = $itemID;
67 // false $itemID gets cast to int, but should be ok
68 // since we do === from the $itemID in $batched
69 $inverseUrlMap[$cluster][$id][$itemID] = $url;
70 }
71 $ret = [];
72 foreach ( $batched as $cluster => $batchByCluster ) {
73 $res = $this->batchFetchBlobs( $cluster, $batchByCluster );
74 /** @var HistoryBlob $blob */
75 foreach ( $res as $id => $blob ) {
76 foreach ( $batchByCluster[$id] as $itemID ) {
77 $url = $inverseUrlMap[$cluster][$id][$itemID];
78 if ( $itemID === false ) {
79 $ret[$url] = $blob;
80 } else {
81 $ret[$url] = $blob->getItem( $itemID );
82 }
83 }
84 }
85 }
86
87 return $ret;
88 }
89
90 public function store( $location, $data ) {
91 $dbw = $this->getMaster( $location );
92 $id = $dbw->nextSequenceValue( 'blob_blob_id_seq' );
93 $dbw->insert( $this->getTable( $dbw ),
94 [ 'blob_id' => $id, 'blob_text' => $data ],
95 __METHOD__ );
96 $id = $dbw->insertId();
97 if ( !$id ) {
98 throw new MWException( __METHOD__ . ': no insert ID' );
99 }
100
101 return "DB://$location/$id";
102 }
103
104 /**
105 * Get a LoadBalancer for the specified cluster
106 *
107 * @param string $cluster Cluster name
108 * @return LoadBalancer
109 */
110 private function getLoadBalancer( $cluster ) {
111 return wfGetLBFactory()->getExternalLB( $cluster );
112 }
113
114 /**
115 * Get a replica DB connection for the specified cluster
116 *
117 * @param string $cluster Cluster name
118 * @return DBConnRef
119 */
120 public function getSlave( $cluster ) {
121 global $wgDefaultExternalStore;
122
123 $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false;
124 $lb = $this->getLoadBalancer( $cluster );
125
126 if ( !in_array( "DB://" . $cluster, (array)$wgDefaultExternalStore ) ) {
127 wfDebug( "read only external store\n" );
128 $lb->allowLagged( true );
129 } else {
130 wfDebug( "writable external store\n" );
131 }
132
133 $db = $lb->getConnectionRef( DB_REPLICA, [], $wiki );
134 $db->clearFlag( DBO_TRX ); // sanity
135
136 return $db;
137 }
138
139 /**
140 * Get a master database connection for the specified cluster
141 *
142 * @param string $cluster Cluster name
143 * @return MaintainableDBConnRef
144 */
145 public function getMaster( $cluster ) {
146 $wiki = isset( $this->params['wiki'] ) ? $this->params['wiki'] : false;
147 $lb = $this->getLoadBalancer( $cluster );
148
149 $db = $lb->getMaintenanceConnectionRef( DB_MASTER, [], $wiki );
150 $db->clearFlag( DBO_TRX ); // sanity
151
152 return $db;
153 }
154
155 /**
156 * Get the 'blobs' table name for this database
157 *
158 * @param IDatabase $db
159 * @return string Table name ('blobs' by default)
160 */
161 public function getTable( $db ) {
162 $table = $db->getLBInfo( 'blobs table' );
163 if ( is_null( $table ) ) {
164 $table = 'blobs';
165 }
166
167 return $table;
168 }
169
170 /**
171 * Fetch a blob item out of the database; a cache of the last-loaded
172 * blob will be kept so that multiple loads out of a multi-item blob
173 * can avoid redundant database access and decompression.
174 * @param string $cluster
175 * @param string $id
176 * @param string $itemID
177 * @return HistoryBlob|bool Returns false if missing
178 */
179 private function fetchBlob( $cluster, $id, $itemID ) {
180 /**
181 * One-step cache variable to hold base blobs; operations that
182 * pull multiple revisions may often pull multiple times from
183 * the same blob. By keeping the last-used one open, we avoid
184 * redundant unserialization and decompression overhead.
185 */
186 static $externalBlobCache = [];
187
188 $cacheID = ( $itemID === false ) ? "$cluster/$id" : "$cluster/$id/";
189 if ( isset( $externalBlobCache[$cacheID] ) ) {
190 wfDebugLog( 'ExternalStoreDB-cache',
191 "ExternalStoreDB::fetchBlob cache hit on $cacheID" );
192
193 return $externalBlobCache[$cacheID];
194 }
195
196 wfDebugLog( 'ExternalStoreDB-cache',
197 "ExternalStoreDB::fetchBlob cache miss on $cacheID" );
198
199 $dbr = $this->getSlave( $cluster );
200 $ret = $dbr->selectField( $this->getTable( $dbr ),
201 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
202 if ( $ret === false ) {
203 wfDebugLog( 'ExternalStoreDB',
204 "ExternalStoreDB::fetchBlob master fallback on $cacheID" );
205 // Try the master
206 $dbw = $this->getMaster( $cluster );
207 $ret = $dbw->selectField( $this->getTable( $dbw ),
208 'blob_text', [ 'blob_id' => $id ], __METHOD__ );
209 if ( $ret === false ) {
210 wfDebugLog( 'ExternalStoreDB',
211 "ExternalStoreDB::fetchBlob master failed to find $cacheID" );
212 }
213 }
214 if ( $itemID !== false && $ret !== false ) {
215 // Unserialise object; caller extracts item
216 $ret = unserialize( $ret );
217 }
218
219 $externalBlobCache = [ $cacheID => $ret ];
220
221 return $ret;
222 }
223
224 /**
225 * Fetch multiple blob items out of the database
226 *
227 * @param string $cluster A cluster name valid for use with LBFactory
228 * @param array $ids A map from the blob_id's to look for to the requested itemIDs in the blobs
229 * @return array A map from the blob_id's requested to their content.
230 * Unlocated ids are not represented
231 */
232 private function batchFetchBlobs( $cluster, array $ids ) {
233 $dbr = $this->getSlave( $cluster );
234 $res = $dbr->select( $this->getTable( $dbr ),
235 [ 'blob_id', 'blob_text' ], [ 'blob_id' => array_keys( $ids ) ], __METHOD__ );
236 $ret = [];
237 if ( $res !== false ) {
238 $this->mergeBatchResult( $ret, $ids, $res );
239 }
240 if ( $ids ) {
241 wfDebugLog( __CLASS__, __METHOD__ .
242 " master fallback on '$cluster' for: " .
243 implode( ',', array_keys( $ids ) ) );
244 // Try the master
245 $dbw = $this->getMaster( $cluster );
246 $res = $dbw->select( $this->getTable( $dbr ),
247 [ 'blob_id', 'blob_text' ],
248 [ 'blob_id' => array_keys( $ids ) ],
249 __METHOD__ );
250 if ( $res === false ) {
251 wfDebugLog( __CLASS__, __METHOD__ . " master failed on '$cluster'" );
252 } else {
253 $this->mergeBatchResult( $ret, $ids, $res );
254 }
255 }
256 if ( $ids ) {
257 wfDebugLog( __CLASS__, __METHOD__ .
258 " master on '$cluster' failed locating items: " .
259 implode( ',', array_keys( $ids ) ) );
260 }
261
262 return $ret;
263 }
264
265 /**
266 * Helper function for self::batchFetchBlobs for merging master/replica DB results
267 * @param array &$ret Current self::batchFetchBlobs return value
268 * @param array &$ids Map from blob_id to requested itemIDs
269 * @param mixed $res DB result from Database::select
270 */
271 private function mergeBatchResult( array &$ret, array &$ids, $res ) {
272 foreach ( $res as $row ) {
273 $id = $row->blob_id;
274 $itemIDs = $ids[$id];
275 unset( $ids[$id] ); // to track if everything is found
276 if ( count( $itemIDs ) === 1 && reset( $itemIDs ) === false ) {
277 // single result stored per blob
278 $ret[$id] = $row->blob_text;
279 } else {
280 // multi result stored per blob
281 $ret[$id] = unserialize( $row->blob_text );
282 }
283 }
284 }
285
286 /**
287 * @param string $url
288 * @return array
289 */
290 protected function parseURL( $url ) {
291 $path = explode( '/', $url );
292
293 return [
294 $path[2], // cluster
295 $path[3], // id
296 isset( $path[4] ) ? $path[4] : false // itemID
297 ];
298 }
299 }