// Connection-local Redis request/reply machinery. The pack supplies its dialect and executes through its own context. // https://redis.io/docs/latest/develop/reference/protocol-spec/; commands AUTH, CLIENT, MULTI, EXEC, BZPOPMIN. import type { TwinStream, TwinStreamSink } from '../twin-fetch.ts'; import { RedisStatus, commandInteger, commandShapeError, globMatch, type RedisDialect, type RunItem } from './engine.ts'; import { binaryBytes, binaryText, inlineCommand, readResp, respReply } from './frames.ts'; import { worldNow } from '../world-clock.ts'; import { redisServiceTimes as times } from './service-times.ts'; export type RedisStreamOptions = { dialect: RedisDialect; version: string; password?: string; databases: number; run(commands: string[][], database: string): Promise<{ items: RunItem[]; wrote: boolean; instant?: number; touched?: string[] }>; }; export function createRedisStream(given: RedisStreamOptions): TwinStream { // The pack's run, its time counted for the command it serves (service-times.ts). const options: RedisStreamOptions = { ...given, run: async (commands, database) => { const began = times.now(); times.lapFrom(); try { const ran = await given.run(commands, database); if (ran.wrote) times.wrote(); return ran; } finally { times.lapEnd('8 answer read by the stream'); times.add('run', times.now() - began); } } }; type Session = { id: number; name: string; lib: Record; database: string; authenticated: boolean; queue: string[][] | null; dirty: boolean; subscriptions: Set; patterns: Set; sink: TwinStreamSink; closed: boolean; received: number; answered: number; pump?: () => Promise; blocked?: { command: string[]; deadline: number; timer?: ReturnType } }; const sessions = new Set(); let nextId = 0, commandCount = 0, waiting = 0; let serial: Promise = Promise.resolve(); const ordered = (f: () => Promise): Promise => { const p = serial.then(f); serial = p.catch(() => {}); return p; }; const error = (message: string) => ({ error: message }); const ok = new RedisStatus('OK'); const connectionTrace = (s: Session, stage: string, command?: string) => { try { console.error('[redis-twin-connection]', JSON.stringify({ at: performance.timeOrigin + times.now(), pid: (globalThis as { process?: { pid?: number } }).process?.pid ?? 0, session: s.id, stage, received: s.received, answered: s.answered, ...(command ? { command } : {}) })); } catch { /* diagnostic output cannot change a connection */ } }; const answer = (s: Session, v: any) => { if (!s.closed) { times.timed('reply', () => s.sink.write(binaryBytes(respReply(v)))); s.answered += 1; } }; const close = (s: Session) => { if (!s.closed) connectionTrace(s, 'closed'); s.closed = true; if (s.blocked?.timer) clearTimeout(s.blocked.timer); sessions.delete(s); }; const unblock = (s: Session, v: any) => { if (s.blocked?.timer) clearTimeout(s.blocked.timer); s.blocked = undefined; answer(s, v); queueMicrotask(() => { void s.pump?.(); }); }; const blockRun = async (s: Session, argv: string[]): Promise => { if (argv[0]!.toUpperCase() === 'BZPOPMIN') { for (const key of argv.slice(1, -1)) { const res = (await options.run([['ZPOPMIN', key]], s.database)).items[0]!; if ('error' in res) return res; if (Array.isArray(res.result) && res.result.length) return [key, ...res.result]; } return null; } throw new Error('the blocking command has no executor'); }; // A CLIENT BLOCKED ON KEYS IS ASKED AGAIN ONLY WHEN ONE OF ITS KEYS WAS WRITTEN. Every write asked every blocked // client again, each ask a whole run for each of its keys: Twenty's queue workers hold a blocked client apiece, and // its twin made 59 to 89 runs for 31 to 41 commands in a two-second window, each run about 20 ms, with every // other command waiting behind them (Twenty 51: commands waited 0.6 to 5.9 s). `touched` is the keys the run // wrote, by name, whatever its database (a name written in another database asks a client that then finds // nothing, never the reverse). Without it (an EXEC's queue, a run that does not say, a command that writes // another database's keys) every blocked client is asked, as before. const wake = async (touched?: readonly string[]) => { for (const s of sessions) { if (!s.blocked) continue; if (touched && !s.blocked.command.slice(1, -1).some((key) => touched.includes(key))) continue; const v = await blockRun(s, s.blocked.command); if (v !== null) unblock(s, v); } }; /** Commands that write keys of a database other than their session's: their run's `touched` does not name them all. */ const CROSS_DATABASE = new Set(['MOVE', 'COPY', 'SWAPDB']); const command = async (s: Session, argv: string[], executing = false): Promise => { if (!argv.length || s.closed) return; commandCount++; const cmd = argv[0]!.toUpperCase(), a = argv.slice(1); const shape = commandShapeError(argv, options.dialect); if (shape) { if (s.queue) s.dirty = true; answer(s, error(shape)); return; } if (!executing && !s.authenticated && !['AUTH', 'QUIT'].includes(cmd)) { answer(s, error('NOAUTH Authentication required.')); return; } if (!executing && s.subscriptions.size + s.patterns.size > 0 && !['SUBSCRIBE', 'PSUBSCRIBE', 'UNSUBSCRIBE', 'PUNSUBSCRIBE', 'PING', 'QUIT'].includes(cmd)) { answer(s, error(`ERR Can't execute '${cmd.toLowerCase()}': only (P|S)SUBSCRIBE / (P|S)UNSUBSCRIBE / PING / QUIT / RESET are allowed in this context`)); return; } if (s.queue && !['EXEC', 'MULTI', 'DISCARD', 'QUIT'].includes(cmd)) { s.queue.push(argv); answer(s, new RedisStatus('QUEUED')); return; } switch (cmd) { // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/acl.c "Only two or three argument forms are allowed." case 'AUTH': { if (a.length > 2) { answer(s, error("ERR syntax error")); return; } if (!options.password && a.length === 1) { answer(s, error('ERR AUTH called without any password configured for the default user. Are you sure your configuration is correct?')); return; } if (a.length === 2 && a[0] !== 'default' || options.password && a.at(-1) !== options.password) { answer(s, error('WRONGPASS invalid username-password pair or user is disabled.')); return; } s.authenticated = true; answer(s, ok); return; } case 'SELECT': { let db: number; try { db = commandInteger(a[0]!); } catch { answer(s, error('ERR value is not an integer or out of range')); return; } if (db < -2147483648 || db > 2147483647) { answer(s, error('ERR value is out of range, value must between -2147483648 and 2147483647')); return; } if (db < 0 || db >= options.databases) { answer(s, error('ERR DB index is out of range')); return; } s.database = String(db); answer(s, ok); return; } case 'CLIENT': { const sub = a[0]!.toUpperCase(); if (sub === 'SETNAME') { if (/[^\x21-\x7e]/.test(a[1] ?? '')) { answer(s, error('ERR Client names cannot contain spaces, newlines or special characters.')); return; } s.name = a[1] ?? ''; answer(s, ok); } else if (sub === 'SETINFO') { if (!['LIB-NAME', 'LIB-VER'].includes(a[1]!.toUpperCase())) { answer(s, error(`ERR Unrecognized option '${a[1]}'`)); return; } if (/[^\x21-\x7e]/.test(a[2]!)) { answer(s, error(`ERR ${a[1]} cannot contain spaces, newlines or special characters.`)); return; } s.lib[a[1]!.toUpperCase()] = a[2]!; answer(s, ok); } else if (sub === 'LIST') { let clients = [...sessions]; // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/networking.c "Invalid client ID" if (a[1]?.toUpperCase() === 'ID' && a.length > 2) { let ids: number[]; try { ids = a.slice(2).map((raw) => commandInteger(raw, 'ERR Invalid client ID')); } catch (e) { answer(s, error((e as Error).message)); return; } clients = ids.flatMap((id) => [...sessions].filter((x) => x.id === id)); } else if (a[1]?.toUpperCase() === 'TYPE' && a.length === 3) { const type = a[2]!.toLowerCase(); if (!['normal', 'pubsub', 'master', 'replica'].includes(type)) { answer(s, error(`ERR Unknown client type '${a[2]}'`)); return; } clients = clients.filter((x) => type === (x.subscriptions.size + x.patterns.size ? 'pubsub' : 'normal')); } else if (a.length !== 1) { answer(s, error('ERR syntax error')); return; } answer(s, clients.map((x) => `id=${x.id} addr=127.0.0.1:0 name=${x.name} db=${x.database} flags=${x.subscriptions.size + x.patterns.size ? 'P' : 'N'} lib-name=${x.lib['LIB-NAME'] ?? ''} lib-ver=${x.lib['LIB-VER'] ?? ''}\n`).join('')); } else answer(s, error(options.dialect.unknownCommand(argv))); return; } // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/server.c "It works in a different way if the client is in" case 'PING': if (a.length > 1) { answer(s, error("ERR wrong number of arguments for 'ping' command")); return; } answer(s, s.subscriptions.size + s.patterns.size ? ['pong', a[0] ?? ''] : a.length ? a[0] : new RedisStatus('PONG')); return; // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/server.c "process_id:%I" (genRedisInfoString, # Server): the serving process's pid, which a supervisor reads to know the server it reached is the one it started case 'INFO': { const pid = (globalThis as { process?: { pid?: number } }).process?.pid ?? 0; const blocks: Record = { server: `# Server\r\nredis_version:${options.version}\r\nredis_mode:standalone\r\nprocess_id:${pid}\r\n`, clients: `# Clients\r\nconnected_clients:${sessions.size}\r\nblocked_clients:${[...sessions].filter((x) => x.blocked).length}\r\n`, memory: `# Memory\r\nmaxmemory:0\r\nmaxmemory_policy:noeviction\r\n`, stats: `# Stats\r\ntotal_connections_received:${nextId}\r\ntotal_commands_processed:${commandCount}\r\n`, persistence: '# Persistence\r\nloading:0\r\n' }; answer(s, a.length && !['ALL', 'DEFAULT'].includes(a[0]!.toUpperCase()) ? a.map((x) => blocks[x.toLowerCase()] ?? '').join('') : Object.values(blocks).join('\r\n')); return; } case 'MULTI': if (s.queue) answer(s, error('ERR MULTI calls can not be nested')); else { s.queue = []; s.dirty = false; answer(s, ok); } return; case 'DISCARD': if (!s.queue) answer(s, error('ERR DISCARD without MULTI')); else { s.queue = null; s.dirty = false; answer(s, ok); } return; case 'EXEC': { if (!s.queue) { answer(s, error('ERR EXEC without MULTI')); return; } const q = s.queue; s.queue = null; if (s.dirty) { s.dirty = false; answer(s, error('EXECABORT Transaction discarded because of previous errors.')); return; } // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/multi.c "Exec all the queued commands" // Redis writes the queue length before dispatch; pub/sub may write multiple acknowledgement frames. s.sink.write(binaryBytes(`*${q.length}\r\n`)); for (const queued of q) await command(s, queued, true); await wake(); return; } case 'QUIT': answer(s, ok); close(s); s.sink.end(); return; case 'SUBSCRIBE': case 'PSUBSCRIBE': case 'UNSUBSCRIBE': case 'PUNSUBSCRIBE': { const target = cmd.includes('PSUB') || cmd.includes('PUNSUB') ? s.patterns : s.subscriptions; const removing = cmd.includes('UNSUB'); const names = a.length ? a : [...target]; for (const name of names.length ? names : [null]) { if (name !== null) { if (removing) target.delete(name); else target.add(name); } answer(s, [cmd.toLowerCase(), name, s.subscriptions.size + s.patterns.size]); } return; } case 'PUBLISH': { let count = 0; for (const target of sessions) { if (target.subscriptions.has(a[0]!)) { answer(target, ['message', a[0]!, a[1]!]); count++; } for (const pattern of target.patterns) if (globMatch(pattern, a[0]!)) { answer(target, ['pmessage', pattern, a[0]!, a[1]!]); count++; } } answer(s, count); return; } case 'BZPOPMIN': { // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/timeout.c "timeout is negative" const raw = a.at(-1)!; const infinite = /^[+-]?inf(?:inity)?$/i.test(raw); if (raw !== raw.trim() || raw === '' || !infinite && !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(raw)) { answer(s, error('ERR timeout is not a float or out of range')); return; } const millis = (infinite ? raw.startsWith('-') ? -Infinity : Infinity : Number(raw)) * 1000; if (millis > 9223372036854775807) { answer(s, error('ERR timeout is out of range')); return; } const timeout = Math.ceil(millis); if (!Number.isFinite(timeout) || timeout < 0) { answer(s, error('ERR timeout is negative')); return; } const v = await blockRun(s, argv); if (v !== null) { answer(s, v); return; } // source: https://raw.githubusercontent.com/redis/redis/c9d29f6a918c335bc1778d9f68e521c1bbb36a0f/src/multi.c "we do not want to allow blocking commands inside multi" if (executing) { answer(s, null); return; } const initial = await options.run([], s.database); s.blocked = { command: argv, deadline: timeout === 0 ? Infinity : (initial.instant ?? 0) + timeout }; // A BLOCKED CLIENT WAITS FOR A WRITE OR ITS DEADLINE, AND ASKS THE TREE NOTHING MEANWHILE. A write through this // twin wakes it (wake, after every command that wrote). Its deadline is in the World's time, so the timer // reads the World's clock (world-clock.ts worldNow: one check of the clock file, kept while it stands) and // nothing else. It ran a whole empty request every 50 ms to read that time: the pack's fetch, its context // and the keyspace's image with its tree stamp, for every blocked client, the whole time it was blocked. // Twenty's queue workers each hold one blocked client: its Redis twin made about 18,700 stamps in a run, 56,145 // stat requests, and spent 55 s of 114 busy in them, with no command to answer. No timeout is no timer; a // deadline far off is checked less often, never more than a second apart, and to 50 ms as it nears. const poll = (): void => { if (!s.blocked || s.closed || s.blocked.deadline === Infinity) return; let left: number; try { left = s.blocked.deadline - Date.parse(worldNow()); } catch (cause) { unblock(s, error(`ERR twin: ${cause instanceof Error ? cause.message : String(cause)}`.replace(/[\r\n]+/g, ' '))); return; } if (left <= 0) { void ordered(async () => { if (s.blocked) unblock(s, null); }); return; } s.blocked.timer = setTimeout(poll, Math.max(50, Math.min(1000, left / 2))); }; poll(); return; } default: { const res = await options.run([argv], s.database); const item = res.items[0]!; answer(s, 'error' in item ? item : item.result); if (res.wrote && !executing) await wake(CROSS_DATABASE.has(cmd) ? undefined : res.touched); } } }; return (sink) => { const s: Session = { id: ++nextId, name: '', lib: {}, database: '0', authenticated: !options.password, queue: null, dirty: false, subscriptions: new Set(), patterns: new Set(), sink, closed: false, received: 0, answered: 0 }; sessions.add(s); connectionTrace(s, 'opened'); let buffer = '', chain: Promise = Promise.resolve(); const pending: Array<{ argv: string[]; received: number }> = []; // A command whose storage fails (a World storage lock that timed out, a write that could not be made) answers its // client with an error and the session goes on, as Redis answers one failed command: it was an unhandled // rejection, and the twin's process exited with every client's connection (Twenty 46). const pump = async () => { while (pending.length && !s.blocked && !s.closed) { const { argv, received } = pending.shift()!; try { await ordered(async () => { waiting -= 1; times.begin(received, waiting, { session: s.id, command: argv[0]?.toUpperCase().slice(0, 32) ?? '' }); let threw = false; try { await command(s, argv); } catch (cause) { threw = true; throw cause; } finally { times.end(threw); } }); } catch (cause) { if (!s.closed) answer(s, error(`ERR twin: ${cause instanceof Error ? cause.message : String(cause)}`.replace(/[\r\n]+/g, ' '))); } } }; s.pump = pump; return { data(chunk) { if (s.closed) return; buffer += binaryText(chunk); try { while (buffer.length) { let argv: string[]; let end: number; if (buffer[0] === '*') { const f = readResp(buffer); if (!f) break; if (!Array.isArray(f.value) || f.value.some((x: unknown) => typeof x !== 'string')) throw new Error('Protocol error: expected bulk string'); argv = f.value; end = f.end; } else { const at = buffer.indexOf('\r\n'); if (at < 0) break; argv = inlineCommand(buffer.slice(0, at)); end = at + 2; } buffer = buffer.slice(end); pending.push({ argv, received: times.now() }); waiting += 1; s.received += 1; if (s.received === 1) connectionTrace(s, 'first-command', argv[0]?.toUpperCase().slice(0, 32)); } chain = chain.then(pump); } catch (e) { answer(s, error(`ERR ${(e as Error).message}`)); close(s); sink.end(); } }, settled: () => chain, close: () => { waiting -= pending.length; pending.length = 0; close(s); }, }; }; }