readCache (redis/cache.ts)

airi · server/apps/api/src/libs/redis/cache.ts · typescript · MIT
database

Provides atomic read and write operations for expiring string snapshots in Redis using Lua scripting to ensure data consistency.

// Source: https://github.com/moeru-ai/airi | License: MIT | Copyright 2024-PRESENT Neko Ayaka
// Provided via justclaw.it.com; keep this notice with the code.
import type Redis from 'ioredis'

import { integer, literal, minValue, number, parse, pipe, string, tuple, union } from 'valibot'

const ttlSchema = pipe(number(), integer(), minValue(1))
const snapshotSchema = union([tuple([literal(0)]), tuple([literal(1), string()])])

// Read the value and expiry in one operation so a concurrent replacement
// cannot pair one snapshot with another snapshot's expiry. Reads never renew it.
// The reply is [0] for a miss or [1, value] for a hit, including empty strings.
const readSnapshot = `
if redis.call('PTTL', KEYS[1]) < 0 then
  return {0}
end
return {1, redis.call('GET', KEYS[1])}
`

/** Reads

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key