amplify icon indicating copy to clipboard operation
amplify copied to clipboard

amplify.request.cache._key is sometimes doesn't resulting unique value

Open budiadiono opened this issue 12 years ago • 3 comments

To reproduce this issue please try this at browser console:

amplify.request.cache._key('ajax1', '/api/opqrstu/opqrstu-project-1/project/get')

it will resulting "request-ajax1-992640007"

now try with this:

amplify.request.cache._key('ajax1', '/api/abcdefg/abcdefg-project-1/project/get')

then you'll get same result "request-ajax1-992640007"

budiadiono avatar Jan 19 '13 10:01 budiadiono

Furthermore,

amplify.request.cache._key('foo', 'foo?a=1&b=2') === amplify.request.cache._key('foo', 'foo?a=2&b=1')

evaluates to true

drakeh avatar Feb 15 '13 22:02 drakeh

On more: 'x' and 'xxxxxxxxx' gets the same hashvalue, because 'xxxx' XOR 'xxxx' evaluates to zero! Furthermore it seems the algorithm doesn't takes care of unicode - all values shifted by 8 bits.

My suggestions is to use/override the _key function with a better one (e.g. java hashCode or crc32):

        amplify.request.cache._key = function (resourceId, url, data) {

            function hashCode(s) {
                var hash = 0, i, chr, len = s.length;
                if (len === 0) {
                    return hash;
                }
                for (i = 0; i < len; i++) {
                    chr = s.charCodeAt(i);
                    hash = ((hash << 5) - hash) + chr;
                    hash |= 0;
                }
                return hash;
            };

            return 'request-' + resourceId + '-' + hashCode(url + data).toString(16);
        };

toarnold avatar Aug 26 '14 06:08 toarnold

Yah, seriously this hash needs to be changed. Within a couple of hours of trying out amplify I ran into puzzling, buggy behavior that indeed turned out to be cache key collisions.

quidquid avatar Jan 09 '15 04:01 quidquid