Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
1441 ariadna 17
namespace core_cache;
1 efrain 18
 
1441 ariadna 19
use core\exception\coding_exception;
20
use stdClass;
1 efrain 21
 
22
/**
23
 * Abstract cache store class.
24
 *
25
 * All cache store plugins must extend this base class.
26
 * It lays down the foundation for what is required of a cache store plugin.
27
 *
28
 * @since Moodle 2.4
1441 ariadna 29
 * @package    core_cache
1 efrain 30
 * @category   cache
31
 * @copyright  2012 Sam Hemelryk
32
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
33
 */
1441 ariadna 34
abstract class store implements store_interface {
1 efrain 35
    // Constants for features a cache store can support
36
 
37
    /**
38
     * Supports multi-part keys
39
     */
40
    const SUPPORTS_MULTIPLE_IDENTIFIERS = 1;
41
    /**
42
     * Ensures data remains in the cache once set.
43
     */
44
    const SUPPORTS_DATA_GUARANTEE = 2;
45
    /**
46
     * Supports a native ttl system.
47
     */
48
    const SUPPORTS_NATIVE_TTL = 4;
49
 
50
    /**
51
     * The cache is searchable by key.
52
     */
53
    const IS_SEARCHABLE = 8;
54
 
55
    /**
56
     * The cache store dereferences objects.
57
     *
58
     * When set, loaders will assume that all data coming from this store has already had all references
59
     * resolved.  So even for complex object structures it will not try to remove references again.
60
     */
61
    const DEREFERENCES_OBJECTS = 16;
62
 
63
    // Constants for the modes of a cache store
64
 
65
    /**
66
     * Application caches. These are shared caches.
67
     */
68
    const MODE_APPLICATION = 1;
69
    /**
70
     * Session caches. Just access to the PHP session.
71
     */
72
    const MODE_SESSION = 2;
73
    /**
74
     * Request caches. Static caches really.
75
     */
76
    const MODE_REQUEST = 4;
77
    /**
78
     * Static caches.
79
     */
80
    const STATIC_ACCEL = '** static accel. **';
81
 
82
    /**
83
     * Returned from get_last_io_bytes if this cache store doesn't support counting bytes read/sent.
84
     */
85
    const IO_BYTES_NOT_SUPPORTED = -1;
86
 
87
    /**
88
     * Constructs an instance of the cache store.
89
     *
90
     * The constructor should be responsible for creating anything needed by the store that is not
91
     * specific to a definition.
92
     * Tasks such as opening a connection to check it is available are best done here.
93
     * Tasks that are definition specific such as creating a storage area for the definition data
94
     * or creating key tables and indexs are best done within the initialise method.
95
     *
96
     * Once a store has been constructed the cache API will check it is ready to be intialised with
97
     * a definition by called $this->is_ready().
98
     * If the setup of the store failed (connection could not be established for example) then
99
     * that method should return false so that the store instance is not selected for use.
100
     *
101
     * @param string $name The name of the cache store
102
     * @param array $configuration The configuration for this store instance.
103
     */
1441 ariadna 104
    abstract public function __construct($name, array $configuration = []);
1 efrain 105
 
106
    /**
107
     * Returns the name of this store instance.
108
     * @return string
109
     */
110
    abstract public function my_name();
111
 
112
    /**
113
     * Initialises a new instance of the cache store given the definition the instance is to be used for.
114
     *
115
     * This function should be used to run any definition specific setup the store instance requires.
116
     * Tasks such as creating storage areas, or creating indexes are best done here.
117
     *
118
     * Its important to note that the initialise method is expected to always succeed.
119
     * If there are setup tasks that may fail they should be done within the __construct method
120
     * and should they fail is_ready should return false.
121
     *
1441 ariadna 122
     * @param definition $definition
1 efrain 123
     */
1441 ariadna 124
    abstract public function initialise(definition $definition);
1 efrain 125
 
126
    /**
127
     * Returns true if this cache store instance has been initialised.
128
     * @return bool
129
     */
130
    abstract public function is_initialised();
131
 
132
    /**
133
     * Returns true if this cache store instance is ready to use.
134
     * @return bool
135
     */
136
    public function is_ready() {
1441 ariadna 137
        return forward_static_call([$this, 'are_requirements_met']);
1 efrain 138
    }
139
 
140
    /**
141
     * Retrieves an item from the cache store given its key.
142
     *
143
     * @param string $key The key to retrieve
144
     * @return mixed The data that was associated with the key, or false if the key did not exist.
145
     */
146
    abstract public function get($key);
147
 
148
    /**
149
     * Retrieves several items from the cache store in a single transaction.
150
     *
151
     * If not all of the items are available in the cache then the data value for those that are missing will be set to false.
152
     *
153
     * @param array $keys The array of keys to retrieve
154
     * @return array An array of items from the cache. There will be an item for each key, those that were not in the store will
155
     *      be set to false.
156
     */
157
    abstract public function get_many($keys);
158
 
159
    /**
160
     * Sets an item in the cache given its key and data value.
161
     *
162
     * @param string $key The key to use.
163
     * @param mixed $data The data to set.
164
     * @return bool True if the operation was a success false otherwise.
165
     */
166
    abstract public function set($key, $data);
167
 
168
    /**
169
     * Sets many items in the cache in a single transaction.
170
     *
171
     * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
172
     *      keys, 'key' and 'value'.
173
     * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
174
     *      sent ... if they care that is.
175
     */
176
    abstract public function set_many(array $keyvaluearray);
177
 
178
    /**
179
     * Deletes an item from the cache store.
180
     *
181
     * @param string $key The key to delete.
182
     * @return bool Returns true if the operation was a success, false otherwise.
183
     */
184
    abstract public function delete($key);
185
 
186
    /**
187
     * Deletes several keys from the cache in a single action.
188
     *
189
     * @param array $keys The keys to delete
190
     * @return int The number of items successfully deleted.
191
     */
192
    abstract public function delete_many(array $keys);
193
 
194
    /**
195
     * Purges the cache deleting all items within it.
196
     *
197
     * @return boolean True on success. False otherwise.
198
     */
199
    abstract public function purge();
200
 
201
    /**
202
     * Performs any necessary operation when the store instance has been created.
203
     *
204
     * @since Moodle 2.5
205
     */
206
    public function instance_created() {
207
        // By default, do nothing.
208
    }
209
 
210
    /**
211
     * Performs any necessary operation when the store instance is being deleted.
212
     *
213
     * This method may be called before the store has been initialised.
214
     *
215
     * @since Moodle 2.5
216
     * @see cleanup()
217
     */
218
    public function instance_deleted() {
219
        if (method_exists($this, 'cleanup')) {
220
            // There used to be a legacy function called cleanup, it was renamed to instance delete.
221
            // To be removed in 2.6.
222
            $this->cleanup();
223
        }
224
    }
225
 
226
    /**
227
     * Returns true if the user can add an instance of the store plugin.
228
     *
229
     * @return bool
230
     */
231
    public static function can_add_instance() {
232
        return true;
233
    }
234
 
235
    /**
236
     * Returns true if the store instance guarantees data.
237
     *
238
     * @return bool
239
     */
240
    public function supports_data_guarantee() {
241
        return $this::get_supported_features() & self::SUPPORTS_DATA_GUARANTEE;
242
    }
243
 
244
    /**
245
     * Returns true if the store instance supports multiple identifiers.
246
     *
247
     * @return bool
248
     */
249
    public function supports_multiple_identifiers() {
250
        return $this::get_supported_features() & self::SUPPORTS_MULTIPLE_IDENTIFIERS;
251
    }
252
 
253
    /**
254
     * Returns true if the store instance supports native ttl.
255
     *
256
     * @return bool
257
     */
258
    public function supports_native_ttl() {
259
        return $this::get_supported_features() & self::SUPPORTS_NATIVE_TTL;
260
    }
261
 
262
    /**
263
     * Returns true if the store instance is searchable.
264
     *
265
     * @return bool
266
     */
267
    public function is_searchable() {
1441 ariadna 268
        return ($this instanceof searchable_cache_interface);
1 efrain 269
    }
270
 
271
    /**
272
     * Returns true if the store automatically dereferences objects.
273
     *
274
     * @return bool
275
     */
276
    public function supports_dereferencing_objects() {
277
        return $this::get_supported_features() & self::DEREFERENCES_OBJECTS;
278
    }
279
 
280
    /**
281
     * Creates a clone of this store instance ready to be initialised.
282
     *
283
     * This method is used so that a cache store needs only be constructed once.
284
     * Future requests for an instance of the store will be given a cloned instance.
285
     *
286
     * If you are writing a cache store that isn't compatible with the clone operation
287
     * you can override this method to handle any situations you want before cloning.
288
     *
289
     * @param array $details An array containing the details of the store from the cache config.
1441 ariadna 290
     * @return store
1 efrain 291
     */
1441 ariadna 292
    public function create_clone(array $details = []) {
1 efrain 293
        // By default we just run clone.
294
        // Any stores that have an issue with this will need to override the create_clone method.
295
        return clone($this);
296
    }
297
 
298
    /**
299
     * Can be overridden to return any warnings this store instance should make to the admin.
300
     *
301
     * This should be used to notify things like configuration conflicts etc.
302
     * The warnings returned here will be displayed on the cache configuration screen.
303
     *
304
     * @return string[] An array of warning strings from the store instance.
305
     */
306
    public function get_warnings() {
1441 ariadna 307
        return [];
1 efrain 308
    }
309
 
310
    /**
311
     * Estimates the storage size used within this cache if the given value is stored with the
312
     * given key.
313
     *
314
     * This function is not exactly accurate; it does not necessarily take into account all the
315
     * overheads involved. It is only intended to give a good idea of the relative size of
316
     * different caches.
317
     *
318
     * The default implementation serializes both key and value and sums the lengths (as a rough
319
     * estimate which is probably good enough for everything unless the cache offers compression).
320
     *
321
     * @param mixed $key Key
322
     * @param mixed $value Value
323
     * @return int Size in bytes
324
     */
325
    public function estimate_stored_size($key, $value): int {
326
        return strlen(serialize($key)) + strlen(serialize($value));
327
    }
328
 
329
    /**
330
     * Gets the amount of memory/storage currently used by this cache store if known.
331
     *
332
     * This value should be obtained quickly from the store itself, if available.
333
     *
334
     * This is the total memory usage of the entire store, not for ther specific cache in question.
335
     *
336
     * Where not supported (default), will always return null.
337
     *
338
     * @return int|null Amount of memory used in bytes or null
339
     */
340
    public function store_total_size(): ?int {
341
        return null;
342
    }
343
 
344
    /**
345
     * Gets the amount of memory used by this specific cache within the store, if known.
346
     *
347
     * This function may be slow and should not be called in normal usage, only for administration
348
     * pages. The value is usually an estimate, and may not be available at all.
349
     *
350
     * When estimating, a number of sample items will be used for the estimate. If set to 50
351
     * (default), then this function will retrieve 50 random items and use that to estimate the
352
     * total size.
353
     *
354
     * The return value has the following fields:
355
     * - supported (true if any other values are completed)
356
     * - items (number of items)
357
     * - mean (mean size of one item in bytes)
358
     * - sd (standard deviation of item size in bytes, based on sample)
359
     * - margin (95% confidence margin for mean - will be 0 if exactly computed)
360
     *
361
     * @param int $samplekeys Number of samples to use
362
     * @return stdClass Object with information about the store size
363
     */
364
    public function cache_size_details(int $samplekeys = 50): stdClass {
365
        $result = (object)[
366
            'supported' => false,
367
            'items' => 0,
368
            'mean' => 0,
369
            'sd' => 0,
1441 ariadna 370
            'margin' => 0,
1 efrain 371
        ];
372
 
373
        // If this cache isn't searchable, we don't know the answer.
374
        if (!$this->is_searchable()) {
375
            return $result;
376
        }
377
        $result->supported = true;
378
 
379
        // Get all the keys for the cache.
380
        $keys = $this->find_all();
381
        $result->items = count($keys);
382
 
383
        // Don't do anything else if there are no items.
384
        if ($result->items === 0) {
385
            return $result;
386
        }
387
 
388
        // Select N random keys.
389
        $exact = false;
390
        if ($result->items <= $samplekeys) {
391
            $samples = $keys;
392
            $exact = true;
393
        } else {
394
            $indexes = array_rand($keys, $samplekeys);
395
            $samples = [];
396
            foreach ($indexes as $index) {
397
                $samples[] = $keys[$index];
398
            }
399
        }
400
 
401
        // Get the random items from cache and estimate the size of each.
402
        $sizes = [];
403
        foreach ($samples as $samplekey) {
404
            $value = $this->get($samplekey);
405
            $sizes[] = $this->estimate_stored_size($samplekey, $value);
406
        }
407
        $number = count($sizes);
408
 
409
        // Calculate the mean and standard deviation.
410
        $result->mean = array_sum($sizes) / $number;
411
        $squarediff = 0;
412
        foreach ($sizes as $size) {
413
            $squarediff += ($size - $result->mean) ** 2;
414
        }
415
        $squarediff /= $number;
416
        $result->sd = sqrt($squarediff);
417
 
418
        // If it's not exact, also calculate the confidence interval.
419
        if (!$exact) {
420
            // 95% confidence has a Z value of 1.96.
421
            $result->margin = (1.96 * $result->sd) / sqrt($number);
422
        }
423
 
424
        return $result;
425
    }
426
 
427
    /**
428
     * Returns true if this cache store instance is both suitable for testing, and ready for testing.
429
     *
430
     * Cache stores that support being used as the default store for unit and acceptance testing should
431
     * override this function and return true if there requirements have been met.
432
     *
433
     * @return bool
434
     */
435
    public static function ready_to_be_used_for_testing() {
436
        return false;
437
    }
438
 
439
    /**
440
     * Gets the number of bytes read from or written to cache as a result of the last action.
441
     *
442
     * This includes calls to the functions get(), get_many(), set(), and set_many(). The number
443
     * is reset by calling any of these functions.
444
     *
445
     * This should be the actual number of bytes of the value read from or written to cache,
446
     * giving an impression of the network or other load. It will not be exactly the same amount
447
     * as netowrk traffic because of protocol overhead, key text, etc.
448
     *
449
     * If not supported, returns IO_BYTES_NOT_SUPPORTED.
450
     *
451
     * @return int Bytes read (or 0 if none/not supported)
452
     * @since Moodle 4.0
453
     */
454
    public function get_last_io_bytes(): int {
455
        return self::IO_BYTES_NOT_SUPPORTED;
456
    }
457
}
1441 ariadna 458
 
459
// Alias this class to the old name.
460
// This file will be autoloaded by the legacyclasses autoload system.
461
// In future all uses of this class will be corrected and the legacy references will be removed.
462
class_alias(store::class, \cache_store::class);