MCPcopy Create free account
hub / github.com/Snapchat/KeyDB / dbRandomKey

Function dbRandomKey

src/db.cpp:429–468  ·  view source on GitHub ↗

Return a random key, in form of a Redis object. * If there are no keys, NULL is returned. * * The function makes sure to return keys not already expired. */

Source from the content-addressed store, hash-verified

427 *
428 * The function makes sure to return keys not already expired. */
429robj *dbRandomKey(redisDb *db) {
430 int maxtries = 100;
431 bool allvolatile = db->expireSize() == db->size();
432
433 while(1) {
434 sds key;
435 robj *keyobj;
436
437 auto itr = db->random();
438 if (itr == nullptr) return NULL;
439
440 key = itr.key();
441 keyobj = createStringObject(key,sdslen(key));
442
443 if (itr.val()->FExpires())
444 {
445 if (allvolatile && listLength(g_pserver->masters) && --maxtries == 0) {
446 /* If the DB is composed only of keys with an expire set,
447 * it could happen that all the keys are already logically
448 * expired in the replica, so the function cannot stop because
449 * expireIfNeeded() is false, nor it can stop because
450 * dictGetRandomKey() returns NULL (there are keys to return).
451 * To prevent the infinite loop we do some tries, but if there
452 * are the conditions for an infinite loop, eventually we
453 * return a key name that may be already expired. */
454 return keyobj;
455 }
456 }
457
458 if (itr.val()->FExpires())
459 {
460 if (expireIfNeeded(db,keyobj)) {
461 decrRefCount(keyobj);
462 continue; /* search for another key. This expired. */
463 }
464 }
465
466 return keyobj;
467 }
468}
469
470bool redisDbPersistentData::syncDelete(robj *key)
471{

Callers 2

randomkeyCommandFunction · 0.85
RM_RandomKeyFunction · 0.85

Calls 10

sdslenFunction · 0.85
expireIfNeededFunction · 0.85
decrRefCountFunction · 0.85
expireSizeMethod · 0.80
randomMethod · 0.80
FExpiresMethod · 0.80
createStringObjectFunction · 0.70
sizeMethod · 0.45
keyMethod · 0.45
valMethod · 0.45

Tested by

no test coverage detected