|
| 1 | +import { Redis } from 'ioredis' |
| 2 | +import type { Config } from './config.js' |
| 3 | + |
| 4 | +export interface CheckpointData { |
| 5 | + balance: number |
| 6 | + customer_id: string |
| 7 | + credit_type_id: string |
| 8 | + _synced_at: number |
| 9 | +} |
| 10 | + |
| 11 | +export interface PendingEvent { |
| 12 | + event_id: string |
| 13 | + event_type: string |
| 14 | + estimated_cost: number |
| 15 | + timestamp: number |
| 16 | + properties?: Record<string, unknown> |
| 17 | +} |
| 18 | + |
| 19 | +export type { Redis } |
| 20 | + |
| 21 | +export function createRedisClient(config: Config): Redis { |
| 22 | + const client = new Redis(config.REDIS_URL, { maxRetriesPerRequest: 3 }) |
| 23 | + client.on('error', (err) => { |
| 24 | + console.error(JSON.stringify({ msg: 'redis error', error: err.message })) |
| 25 | + }) |
| 26 | + return client |
| 27 | +} |
| 28 | + |
| 29 | +export function checkpointKey(config: Config, customerId: string): string { |
| 30 | + return `${config.CHECKPOINT_PREFIX}net_balance:${customerId}:${config.CREDIT_TYPE_ID}` |
| 31 | +} |
| 32 | + |
| 33 | +export function pendingSetKey(config: Config, customerId: string): string { |
| 34 | + return `${config.OPTIMISTIC_PREFIX}pending:${customerId}` |
| 35 | +} |
| 36 | + |
| 37 | +export async function getCheckpoint( |
| 38 | + redis: Redis, |
| 39 | + config: Config, |
| 40 | + customerId: string |
| 41 | +): Promise<CheckpointData | null> { |
| 42 | + const raw = await redis.get(checkpointKey(config, customerId)) |
| 43 | + if (!raw) return null |
| 44 | + return JSON.parse(raw) as CheckpointData |
| 45 | +} |
| 46 | + |
| 47 | +export async function getPendingEvents( |
| 48 | + redis: Redis, |
| 49 | + config: Config, |
| 50 | + customerId: string |
| 51 | +): Promise<PendingEvent[]> { |
| 52 | + const members = await redis.zrange(pendingSetKey(config, customerId), 0, -1) |
| 53 | + return members.map((m) => JSON.parse(m) as PendingEvent) |
| 54 | +} |
| 55 | + |
| 56 | +export async function sumPendingCosts( |
| 57 | + redis: Redis, |
| 58 | + config: Config, |
| 59 | + customerId: string |
| 60 | +): Promise<{ total: number; count: number }> { |
| 61 | + const events = await getPendingEvents(redis, config, customerId) |
| 62 | + // Sub-cent precision; round to avoid IEEE-754 drift |
| 63 | + const total = Math.round(events.reduce((sum, e) => sum + e.estimated_cost, 0) * 100) / 100 |
| 64 | + return { total, count: events.length } |
| 65 | +} |
0 commit comments