Git Product home page Git Product logo

cache's People

Contributors

alex-krash avatar alexkart avatar cebe avatar dependabot-preview[bot] avatar dependabot[bot] avatar devanych avatar fantom409 avatar flaversaver avatar gerych1984 avatar hiqsol avatar lav45 avatar luizcmarin avatar machour avatar mj4444ru avatar razonyang avatar roxblnfk avatar rustamwin avatar samdark avatar sankaest avatar silverfire avatar skugarev avatar stylecibot avatar terabytesoftw avatar viktorprogger avatar vjik avatar xepozz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cache's Issues

Fix composer.json

  1. The package does not provide PSR-16 implementation anymore.
  2. The package should require PSR-16 implementation.
  3. Drivers should provide PSR-16 implementations.

Cache stampede prevention for empty cache

The current implementation only works when the data is already cached. In this case, every time the data is read from the cache, the algorithm calculates the expiration time and, if key is expired, recompute the cache. But imagine the cache is empty(for the first time) in high traffic. If we get a thousand simultaneous requests, they all hit the empty cache and the system calculates the data for all of them. Which again causes the cache stampede problem.
Is there a way to prevent the calculation of it for all requests in the first time, when our key and data are not cached?
For example lock the key or anything else ?

$now = microtime(true);
$delta = ceil(1000 * ($now - $this->updated)) / 1000;
$expired = $now - $delta * $beta * log(random_int(1, PHP_INT_MAX) / PHP_INT_MAX);

return $this->expiry <= $expired;

ezgif-4-17a8ea5945

Library design

I was looking into this library, trying to work on some issues, and while working with it I noticed that the design of the library doesn’t feel right.
The first thing that bothers me is SimpleCache class, and that it adds additional functionality from the beginning (keys and values normalization, key prefixes, etc., what if you don’t need normalization or you want to handle it yourself) and those methods setValue, getValue etc. that each backend needs to implement instead of implementing interface methods, this is confusing. I think that different backend classes should just implement PSR interface as minimal as possible without any additional functionality and all additional things can be added to decorator (one or several) like Cache class that currently extends functionality.
It will have several significant benefits:

  1. When you are implementing new cache backend, you know exactly what to implement from the PSR interface
  2. The functionality of the new cache backend will be as minimal as it’s required by the interface especially if you don’t need any extra functionality, the library will be more general-purpose and you will have the ability to use it with or without extra functionality
  3. All extra functionality will be added via decorators (one common decorator or several more specific ones)

@samdark, so, what do you think of rewriting of the library a bit to this architecture? Is there any reason why we can’t do this or you don’t see any sense doing this? What if I try to implement it and we’ll see if it’s better than the current one?

Reusable property for TagDependency

What steps will reproduce the problem?

Many data caching with common TagDependency dependency with reusable option that is on.

What is the expected result?

Decrease Cache::multiGet calls from isChanged . Reusable property do not use in this method, but in parent class, in the same method reusable used.

What do you get instead?

When reusable options is on, caching timestamp data of the TagDependency in the static property.

Consider removing add() and addMultiple()

add() and addMultiple() work like set() and setMultiple() except they store cache only if there is no existing value.

Personally, I've never used it. Need opinions about removing these.

Remove need for SUDO by mocking in FileCacheTest.

Currently we can't use travis' container infrastructure since we require sudo because of the FileCacheTest.
As far as I can tell we're testing to if the FileCache will properly fail in case it's set to a different owner.
Since our code is in a namespace and we use unqualified function calls to:

  • fileowner
  • posix_geteuid
  • unlink

We could simply mock fileowner() and unlink() for the test.

Unreached code

I think the code inside if ($this->persistentId !== null) {} in \Yiisoft\Cache\Memcached::addServers can never be executed https://github.com/yiisoft/cache/blob/master/src/Memcached.php#L88.
addServers() method is called only from constructor and $this->persistentId is always null in this case.

The same is for the following blocks https://github.com/yiisoft/cache/blob/master/src/Memcached.php#L114
https://github.com/yiisoft/cache/blob/master/src/Memcached.php#L118
getMemcached() is called from the constructor and then $this->cache is never null.

Support negative duration in CacheInterface::set()

How about adding support to skip caching with negative $duration in \yii\cache\CacheInterface::set()? (and multiSet(), and getOrSet(), of course)

As it done well in \yii\db\Query::cache() (since 2.0.14) - and it's pretty useful.

Of course we can use DummyCache to avoid caching, but it will affect ALL relevant cache-set calls.

My use case is flexiblе cache duration, which depends on environment, and which is different for different data.

So for now actually I have to do it like that:

if (Yii::$app->params['cacheDuration.catalogList'] >= 0) {
    Yii::$app->getCache()->set($key, $value, Yii::$app->params['cacheTime.catalogList']);
}

It can be done simplier.

Additional info

Q A
Yii version 2.0.14+
PHP version any
Operating system any

The get() method should be string, with compatible psr/SimpleCache/CacheInterface::get().

The get() method must be compatible with psr/SimpleCache/CacheInterface::get()

interface CacheInterface
{
    /**
     * Fetches a value from the cache.
     *
     * @param string $key     The unique key of this item in the cache.
     * @param mixed  $default Default value to return if the key does not exist.
     *
     * @return mixed The value of the item from the cache, or $default in case of cache miss.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function get($key, $default = null);
}

Prefix restrictions.

cache/src/Cache.php

Lines 299 to 305 in 81977ed

public function setKeyPrefix(string $keyPrefix): void
{
if ($keyPrefix !== '' && !ctype_alnum($keyPrefix)) {
throw new \Yiisoft\Cache\Exception\InvalidArgumentException('Cache key prefix should be alphanumeric');
}
$this->keyPrefix = $keyPrefix;
}

Why impose such restrictions on the prefix when the is_scalar constraint is used for the key?

DbQueryDependency::method to QueryInterface::count

Inconsistency in behavior DbQueryDependency::method and QueryInterface::count

class DbQueryDependency extends Dependency
{
    /**
     * @var string|callable method which should be invoked in over the [[query]] object.
     *
     * If specified as a string an own query method with such name will be invoked, passing [[db]] value as its
     * first argument. For example: `exists`, `all`.
     *
     * This field can be specified as a PHP callback of following signature:
     *
     * ```php
     * function (QueryInterface $query, mixed $db) {
     *     //return mixed;
     * }
     * ```
     *
     * If not set - [[QueryInterface::one()]] will be used.
     */
    public $method;
interface QueryInterface
 /**
     * Returns the number of records.
     * @param string $q the COUNT expression. Defaults to '*'.
     * @param Connection $db the database connection used to execute the query.
     * If this parameter is not given, the `db` application component will be used.
     * @return int number of records.
     */
    public function count($q = '*', $db = null);

SQL error by this code

$cacheProperties = [
    'dependency' => [
        'class' => \yii\caching\DbQueryDependency::class,
        'query' => $query,
        'method' => 'count'
    ],
    'duration' => 60 * 60 * 24
];

if ($this->beginCache($key, $cacheProperties)) {
    // ...
    $this->endCache();
}

ExpressionDependency does not work

$updated_at = rand(1, 10);
        echo $updated_at . PHP_EOL;
        $dependency = new \yii\caching\ExpressionDependency(
            [
                //'expression' => 'date("Y-m-d H:i:s")', // normal work
                'expression' => '$this->params', // use 'params' not work
                'params' => ['updated_at' => $updated_at]
            ]
        );
        $cacheKey = 'goods_view';
        $date = Yii::$app->cache->getOrSet($cacheKey, function () {

            return [rand(20, 100)];
        }, 3600, $dependency);

        print_r($date)  ;
        exit();

Also, when changing the expression, you must use './yii cache/flush-all' to clear the cache to take effect.

How to use both expression and params parameters correctly ?

Additional info

Q A
Yii version 2.0.15.1?
PHP version 5.5
Operating system mac os

Different stores for cache values and tags.

The store for tags in a complex project can be different from the store for the cache itself.
It is necessary to give the opportunity to set the store for tags:

$cache->getOrSet('item_42_price', $callable, null, new TagDependency('item_42', $tagCache));

The Symfony cache allows you to set up the tag store via configuration. It would be convenient if we could specify the tag store in the settings of the cache itself.

ArrayCache data loss between several instances

What steps will reproduce the problem?

`
use Yiisoft\Cache\ArrayCache;

$cache1 = new ArrayCache();
$cache2 = new ArrayCache();

$cache1->set('test', 'sddsbsdbdsbds');

var_dump($cache1->has('test')); //True
var_dump($cache2->has('test')); //False
`

So maybe private array $cache must be static? Otherwise ArrayCache work differently compared with FIleCache, Memcached, APCu etc

No exception thrown for invalid key characters in storage backends

According to PSR-16 some characters must not be used as keys:

The following characters are reserved for future extensions and MUST NOT be supported by implementing libraries: {}()/\@:

Psr\SimpleCache\CacheInterface requires an exception to be thrown for invalid keys:

     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function get($key, $default = null);

So as I understand the spec any key containing one of the above characters MUST also be considered invalid and lead to an exception.

This affects all other cache backends (apc, ...)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.