-
Notifications
You must be signed in to change notification settings - Fork 5
/
cache.ts
165 lines (142 loc) · 4.14 KB
/
cache.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import QuickChart from 'quickchart-js'
import redis from 'redis'
import { BapIdentity } from './bap.js'
import { TimeSeriesData } from './chart.js'
import { getCurrentBlockHeight } from './db.js'
// Redis client setup
const client = redis.createClient({
url: process.env.REDIS_PRIVATE_URL,
})
process.on('SIGINT', () => {
client.quit().then(() => {
console.log('Redis client disconnected')
process.exit(0)
})
})
client.on('connect', async () => {
console.log('Redis: Client connected')
// await loadCache()
})
// Listen to error events on the Redis client
client.on('error', (err) => {
console.error('Redis error:', err)
})
interface CacheBlockHeight {
type: 'blockHeight'
value: number
}
interface CacheChart {
type: 'chart'
value: QuickChart
}
export interface CacheCount {
type: 'count'
value: Record<string, number>[]
}
interface CacheTimeSeriesData {
type: 'timeSeriesData'
value: TimeSeriesData
}
interface CacheIngest {
type: 'ingest'
value: string[]
}
export interface CacheSigner {
type: 'signer'
value: BapIdentity
}
export type CacheValue =
| CacheBlockHeight
| CacheChart
| CacheCount
| CacheTimeSeriesData
| CacheIngest
| CacheSigner
| CacheError
interface CacheError {
type: 'error'
error: number
value: null
}
// Function to serialize and save to Redis
async function saveToRedis<T extends CacheValue>(
key: string,
value: T
): Promise<void> {
await client.set(key, JSON.stringify(value))
}
// Function to read and deserialize from Redis
async function readFromRedis<T extends CacheValue | CacheError>(
key: string
): Promise<T | null> {
const value = await client.get(key)
return value
? (JSON.parse(value) as T)
: ({ type: 'error', value: null, error: 404 } as T)
}
// Shared utility function to get block height
async function getBlockHeightFromCache(): Promise<number> {
let cachedValue = await readFromRedis<CacheBlockHeight>('currentBlockHeight')
if (!cachedValue.value) {
const currentBlockHeight = await getCurrentBlockHeight()
const currentBlockHeightKey = `currentBlockHeight-${currentBlockHeight}`
await saveToRedis(currentBlockHeightKey, {
type: 'blockHeight',
value: currentBlockHeight,
})
return currentBlockHeight
} else {
console.info('Using cached block height')
return cachedValue.value
}
}
// Check if a transaction ID was ingested
async function wasIngested(txid: string): Promise<boolean> {
const cachedValue = await readFromRedis<CacheIngest>(`ingest-${txid}`)
return cachedValue?.value ? cachedValue.value.includes(txid) : false
}
// Cache a new transaction ID
async function cacheIngestedTxid(txid: string): Promise<void> {
const ingestKey = `ingest-${txid}`
const cachedValue = await readFromRedis<CacheIngest>(ingestKey)
let ingestCache = cachedValue?.value ? cachedValue.value : []
if (!ingestCache || !ingestCache.includes(txid)) {
ingestCache = ingestCache ? [...ingestCache, txid] : [txid]
await saveToRedis(ingestKey, { type: 'ingest', value: ingestCache })
}
}
// Function to check if a txid is cached
async function checkCache(txid: string): Promise<boolean> {
return wasIngested(txid) // This uses the same functionality as wasIngested
}
// Function to add a new txid to the cache
async function addToCache(txid: string): Promise<void> {
await cacheIngestedTxid(txid) // Reuses cacheIngestedTxid to maintain the list of txids
}
// Function to load all cached txids from Redis
async function loadCache(): Promise<string[]> {
const cachedValue = await readFromRedis<CacheIngest>('ingest')
return cachedValue?.value ? cachedValue.value : []
}
// Function to count items in Redis cache
async function countCachedItems(): Promise<number> {
const cachedValue = await readFromRedis<CacheIngest>('ingest')
return cachedValue?.value ? cachedValue.value.length : 0
}
// Additional helper function to delete a key from Redis
async function deleteFromCache(key: string): Promise<void> {
await client.del(key)
}
export {
addToCache,
cacheIngestedTxid,
checkCache,
client,
countCachedItems,
deleteFromCache,
getBlockHeightFromCache,
loadCache,
readFromRedis,
saveToRedis,
wasIngested,
}