MCPcopy Create free account
hub / github.com/QuantumNous/new-api / writeUserSessionCache

Function writeUserSessionCache

model/user_session.go:276–356  ·  view source on GitHub ↗

writeUserSessionCache writes a bounded Session snapshot. Active snapshots must carry a deadline captured immediately before their authoritative database read or mutation. Delayed fills inherit the unspent portion of that window, so a stale active snapshot cannot outlive a short deny tombstone and re

(entry *userSessionCacheEntry, cacheDeadline time.Time)

Source from the content-addressed store, hash-verified

274// reactivate a revoked Session after the tombstone expires. Deny states pass a
275// zero deadline because their TTL starts when they are published.
276func writeUserSessionCache(entry *userSessionCacheEntry, cacheDeadline time.Time) error {
277 if entry == nil || !common.RedisEnabled {
278 return nil
279 }
280 now := time.Now()
281 sessionExpiresAt := time.Unix(entry.ExpiresAt, 0)
282 sessionTTL := sessionExpiresAt.Sub(now)
283 var redisExpiration int64
284 if entry.Status == UserSessionStatusActive {
285 if cacheDeadline.IsZero() {
286 return ErrUserSessionInvalid
287 }
288 cacheTTL := cacheDeadline.Sub(now)
289 if cacheTTL <= 0 {
290 return errUserSessionCacheObservationStale
291 }
292 if sessionTTL <= 0 {
293 return ErrUserSessionInactive
294 }
295 cacheExpiresAt := cacheDeadline
296 if sessionExpiresAt.Before(cacheExpiresAt) {
297 cacheExpiresAt = sessionExpiresAt
298 }
299 if cacheExpiresAt.Sub(now) < time.Millisecond {
300 return errUserSessionCacheObservationStale
301 }
302 redisExpiration = cacheExpiresAt.UnixMilli()
303 } else {
304 ttl := min(sessionTTL, time.Duration(userCacheTTLSeconds())*time.Second)
305 if ttl <= 0 {
306 ttl = time.Second
307 }
308 redisExpiration = ttl.Milliseconds()
309 if redisExpiration <= 0 {
310 redisExpiration = 1
311 }
312 }
313 entry.CacheSchema = userSessionCacheSchema
314 const script = `
315local current_status = redis.call('HGET', KEYS[1], 'Status')
316local current_version = tonumber(redis.call('HGET', KEYS[1], 'Version') or '0')
317if ARGV[5] == 'active' and (current_status == 'revoking' or current_status == 'revoked') then
318 return 0
319end
320if current_version > tonumber(ARGV[3]) then
321 return 0
322end
323redis.call('HSET', KEYS[1],
324 'SID', ARGV[1], 'UserID', ARGV[2], 'Version', ARGV[3],
325 'UserAuthVersion', ARGV[4], 'Status', ARGV[5],
326 'LoginMethod', ARGV[6], 'IP', ARGV[7], 'UserAgent', ARGV[8],
327 'CreatedAt', ARGV[9], 'LastActiveAt', ARGV[10], 'ExpiresAt', ARGV[11],
328 'RevokedAt', ARGV[12], 'RevokedReason', ARGV[13], 'CacheSchema', ARGV[14])
329if ARGV[5] == 'active' then
330 redis.call('PEXPIREAT', KEYS[1], ARGV[15])
331else
332 redis.call('PEXPIRE', KEYS[1], ARGV[15])
333end

Calls 2

userCacheTTLSecondsFunction · 0.85
userSessionCacheKeyFunction · 0.85