8000 Use zend_hrtime instead of time(NULL) since it's monotonic · phpredis/phpredis@f01f805 · GitHub
[go: up one dir, main page]

Skip to content

Commit f01f805

Browse files
Use zend_hrtime instead of time(NULL) since it's monotonic
`time(NULL)` isn't monotonic and can run backwards so switch to `zend_hrtime` which uses `clock_gettime(CLOCK_MONOTONIC)` on Linux and `QueryPerformanceCounter`on Windows.
1 parent fead6c7 commit f01f805

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

cluster_library.c

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@
66
#include "crc16.h"
77
#include <zend_exceptions.h>
88

9+
#if PHP_VERSION_ID < 80300
10+
#include "ext/standard/hrtime.h"
11+
#else
12+
#include "Zend/zend_hrtime.h"
13+
#endif
14+
915
#ifdef HAVE_REDIS_ATOMICS_MMAP
1016
#include <stdatomic.h>
1117
#include <sys/mman.h>
@@ -891,14 +897,26 @@ cluster_free(redisCluster *c, int free_ctx)
891897
if (free_ctx) efree(c);
892898
}
893899

900+
static inline uint64_t redis_time(void) {
901+
#define REDIS_NANO_IN_SEC ((uint64_t)1000000000)
902+
903+
#if PHP_VERSION_ID < 80300
904+
return php_hrtime_current() / REDIS_NANO_IN_SEC;
905+
#else
906+
return zend_hrtime() / REDIS_NANO_IN_SEC;
907+
#endif
908+
909+
#undef REDIS_NANO_IN_SEC
910+
}
911+
894912
static zend_long cluster_cache_expiry(void) {
895913
zend_long expiry;
896914

897915
expiry = INI_INT("redis.clusters.slot_cache_expiry");
898916
if (expiry <= 0)
899917
return 0;
900918

901-
return time(NULL) + expiry;
919+
return redis_time() + expiry;
902920
}
903921

904922
#ifdef HAVE_REDIS_ATOMICS_MMAP
@@ -3172,7 +3190,7 @@ PHP_REDIS_API redisCachedCluster *cluster_cache_load(zend_string *hash) {
31723190

31733191
cc = le->ptr;
31743192
/* Short circuit if it should be expired */
3175-
if (cc->expiry != 0 && cc->expiry <= time(NULL))
3193+
if (cc->expiry != 0 && cc->expiry <= redis_time())
31763194
return NULL;
31773195

31783196
#ifdef HAVE_REDIS_ATOMICS_MMAP

0 commit comments

Comments
 (0)
0