import { exactInteger } from '../exact-json.ts'; // RESP frame parsing and RESP2 replies, shared by the Redis stream and journey tooling. // https://redis.io/docs/latest/develop/reference/protocol-spec/ import { RedisInteger, RedisStatus, type RedisValue } from './engine.ts'; export const binaryText = (b: Uint8Array): string => Array.from(b, (n) => String.fromCharCode(n)).join(''); export const binaryBytes = (s: string): Uint8Array => Uint8Array.from(s, (c) => c.charCodeAt(0)); export type Frame = { value: any; end: number; error?: boolean; type: string }; export function readResp(s: string, start = 0): Frame | undefined { const e = s.indexOf('\r\n', start); if (e < 0) return undefined; const tag = s[start]!, head = s.slice(start + 1, e); let at = e + 2; if (tag === '+' || tag === '-') return { type: tag, value: head, end: at, ...(tag === '-' ? { error: true } : {}) }; if (tag === ':') return { type: tag, value: exactInteger(head), end: at }; if (tag === '_') return { type: tag, value: null, end: at }; if (tag === '#') return { type: tag, value: head === 't', end: at }; if (tag === ',') return { type: tag, value: Number(head), end: at }; const n = Number(head); if (!Number.isSafeInteger(n) || n < -1) throw new Error('Protocol error: invalid length'); if (tag === '$' || tag === '!') { if (n === -1) return { type: tag, value: null, end: at }; if (s.length < at + n + 2) return undefined; if (s.slice(at + n, at + n + 2) !== '\r\n') throw new Error('Protocol error: invalid bulk terminator'); return { type: tag, value: s.slice(at, at + n), end: at + n + 2, ...(tag === '!' ? { error: true } : {}) }; } if (['*', '%', '~', '>'].includes(tag)) { if (n === -1) return { type: tag, value: null, end: at }; const out: any[] = []; for (let i = 0; i < n * (tag === '%' ? 2 : 1); i++) { const f = readResp(s, at); if (!f) return undefined; out.push(f.error ? { error: f.value } : f.value); at = f.end; } return { type: tag, value: tag === '%' ? Object.fromEntries(Array.from({ length: n }, (_, i) => [out[i * 2], out[i * 2 + 1]])) : out, end: at }; } throw new Error('Protocol error: invalid type'); } export function respReply(value: RedisValue | { error: string } | Record): string { if (value instanceof RedisInteger || typeof value === 'object' && value !== null && 'integer' in value) return `:${value.integer}\r\n`; if (value === null) return '$-1\r\n'; if (value instanceof RedisStatus || typeof value === 'object' && !Array.isArray(value) && 'value' in value) return `+${String(value.value).replace(/[\r\n]/g, ' ')}\r\n`; if (typeof value === 'object' && !Array.isArray(value) && 'error' in value) return `-${String(value.error).trim().replace(/[\r\n]/g, ' ')}\r\n`; if (Array.isArray(value)) return `*${value.length}\r\n${value.map((x) => respReply(x)).join('')}`; if (typeof value === 'object') return respReply(Object.entries(value).flat()); if (typeof value === 'number') return Number.isInteger(value) ? `:${value}\r\n` : respReply(String(value)); const s = String(value); return `$${s.length}\r\n${s}\r\n`; } export const commandFrame = (command: string[]): Uint8Array => { const args = command.map((s) => binaryText(new TextEncoder().encode(s))); return binaryBytes(`*${args.length}\r\n${args.map((s) => `$${s.length}\r\n${s}\r\n`).join('')}`); }; export function inlineCommand(line: string): string[] { const words: string[] = []; let word = '', quote = '', active = false; for (let i = 0; i < line.length; i++) { const c = line[i]!; if (c === '\\' && quote) { const next = line[++i]!; if (next === 'x' && /^[0-9a-f]{2}$/i.test(line.slice(i + 1, i + 3))) { word += String.fromCharCode(parseInt(line.slice(i + 1, i + 3), 16)); i += 2; } else word += ({ n: '\n', r: '\r', t: '\t' } as any)[next] ?? next; } else if (quote) { if (c === quote) quote = ''; else word += c; } else if (c === '"' || c === "'") { quote = c; active = true; } else if (/\s/.test(c)) { if (active) { words.push(word); word = ''; active = false; } } else { word += c; active = true; } } if (quote) throw new Error('Protocol error: unbalanced quotes in request'); if (active) words.push(word); return words; } /** Carry RESP integer/status tags across an internal JSON request without losing int64 bytes. */ export function wireValue(value: any): any { if (value instanceof RedisInteger) return { integer: value.integer }; if (Array.isArray(value)) return value.map(wireValue); if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, wireValue(item)])); return value; }