import { type LuaHost } from './lua.js'; /** * A Redis SIMPLE STATUS reply, kept distinct from a bulk string. * * This is not pedantry — it is required for `Upstash-Encoding: base64` fidelity. LIVE-PROBED rule: * with that header on, Upstash base64-encodes every string in `result` at any array depth EXCEPT * the simple-status reply `OK`, which is passed through raw. `PING`'s status `PONG` IS encoded * (`UE9ORw==`), and so is a BULK STRING whose value happens to be `OK` (`GET okkey` → `T0s=`). So * the exemption is scoped to the status reply `OK` specifically, and a twin that exempted any * string equal to `"OK"` would send raw bytes for `GET okkey`. Hence this wrapper. */ export declare class RedisStatus { readonly value: string; constructor(value: string); } export declare const OK: RedisStatus; /** The JSON projection of a RESP reply — what Upstash puts in `{"result": …}`. */ export declare class RedisInteger { readonly integer: string; constructor(integer: string); } export type RedisValue = null | number | string | RedisStatus | RedisInteger | RedisValue[]; /** A command-level failure. `message` is the vendor's literal error string. Maps to HTTP 400. */ export declare class RedisCommandError extends Error { constructor(message: string); } /** Thrown when a write is attempted against a read-only twin. Mapped to HTTP 405 by the handler. */ export declare class ReadOnlyError extends Error { constructor(); } export declare const KEY_TYPES: readonly ["string", "list", "set", "hash", "zset", "stream"]; export type KeyType = typeof KEY_TYPES[number]; export type HashPairs = Array<[string, string]>; export type ZSetPairs = Array<[string, number]>; /** * How a zset is STORED. Scores persist as the STRING Redis itself would print, never as raw JSON * numbers — because `JSON.stringify(Infinity)` is `null`, and `ZADD key +inf member` is ordinary * Redis (leaderboard sentinels, "pin this to the top" idioms). §9 round 1 caught the bug this * prevents: an in-memory `+inf` survived within one request and came back as the literal bulk * string "null" on the next, whereupon `ZRANGEBYSCORE key 0 100` cheerfully returned the member — * a plausible-looking WRONG answer over persisted state, which is the exact failure mode this pack * forbids. `fmtScore`/`toFloat` round-trip inf, -inf and every finite double faithfully. */ type StoredZSet = Array<[string, string]>; export type StreamEntries = Array<[string, HashPairs]>; /** A point-in-time copy of a run's whole mutable state, for script rollback. */ type Snapshot = { rows: OverlayState; touched: Map; scripts: OverlayState; touchedScripts: Map; }; export type KeyRow = { name: string; kind: KeyType; /** string → string; list/set → string[]; hash → [f,v][]; zset → [member,score][]; stream → [id,[f,v][]][] */ v: string | string[] | HashPairs | ZSetPairs | StreamEntries; /** Exact absolute expiry deadline in epoch ms, persisted as decimal digits, or null for "no TTL". */ pexpireAt: string | null; /** Stream only: the last id this stream minted, so `*` stays monotonic. */ lastId?: string; /** Stream only: its consumer groups and counters, as the dialect that serves them keeps them (the redis pack's XGROUP). */ meta?: unknown; /** * A per-key WRITE ORDINAL, incremented on every flush. No command ever reads it and it never * leaves this module — it exists solely to defeat the kernel's action dedupe. * * THE BUG IT FIXES (found by self-attack after §9 round 1): `applyTwinWrite` dedupes by * (content + occurredAt millisecond), so writing a key back to a value it ALREADY HELD at the * same instant produced an actionId identical to the earlier action and was silently dropped as * `replayed`. The projection then folded to the LATER surviving action, so the key kept the * WRONG value while the command's reply reported the right one — reply and state disagreeing, * which is the worst shape a wrong answer can take. Concretely, with a pinned clock: * ZADD e 10 m ; ZADD e INCR 5 m → 15 ; ZADD e XX INCR 5 m → 20 ; ZADD e GT INCR 5 m → 25 ; * ZADD e LT INCR -5 m → answered 20, but ZSCORE still said 25 * because a `[["m","20"]]` action already existed at that instant. The same hazard reaches any * `SET k a ; SET k b ; SET k a` landing inside one millisecond. Bumping an ordinal makes every * write's content unique, so nothing can be mistaken for a replay. */ _rev?: number; }; /** Everything a run needs. `root` scopes the kernel state; `occurredAt` IS the clock. */ export type RedisContext = { root?: string; occurredAt: string; /** When true, any write command raises `ReadOnlyError` (the wire answers its read-only refusal). */ readOnly?: boolean; /** Commands queued in a wire transaction, rather than an ordinary pipeline. */ transaction?: boolean; /** A database other than the service's first (Redis's SELECT n, a vendor's database id), whose keys and scripts * are its own: subjects `db::key:` and `db::script:`. Absent: `key:`, `script:`. */ database?: string; /** The World service whose tree holds the keys: the pack's own. */ service: string; /** The wire the core answers for: its refusals, its commands, its Lua, its layout. */ dialect: RedisDialect; }; /** * WHAT A WIRE ANSWERS DIFFERENTLY. Stock Redis and Upstash's REST envelope serve one set of Redis semantics and * differ in what they refuse and what they add; a dialect carries exactly those differences. */ export type RedisDialect = { /** The refusal for a command neither the core nor the dialect serves. */ unknownCommand: (argv: string[]) => string; /** The refusal for an option of a served command the core does not model (`ZRANGE BYLEX`, `XADD MAXLEN trimming`): * a loud refusal, never a success, in the wire's words. */ unmodeled: (what: string) => string; /** The whole queue-time check, when the wire has its own (Upstash's REST-restricted commands, its table's arity); * absent, a command is checked against the dialect's commands, then the core's, by arity. */ shapeError?: (argv: string[]) => string | null; /** The dialect's own commands, `[min, max]` arguments after the name as `SERVED_COMMANDS`, run before the core. */ commands: Record; exec: (space: KeySpace, argv: string[]) => RedisValue; /** Which of the dialect's commands write. */ writes: ReadonlySet; /** The script environment (`extend`: the command API's name, runtime libraries) and how a Lua number becomes a * command argument (Redis 7: the shortest round-tripping form; Upstash: truncated). */ lua: Required>; /** Whether a script that fails part-way keeps what it wrote (Redis) or leaves nothing (Upstash). */ scriptErrorsKeepWrites: boolean; /** Wire-specific Lua flags. A flag installs a restriction before each command; the core owns `no-writes`. * Flags absent here are refused, never ignored. A transaction is passed explicitly by the wire. */ scriptFlags?: Record (argv: string[]) => void>; /** How the dialect's keys are laid out in the tree, when not one subject per key (`keyspaceImageOf`, `flushKeySpace`). */ storage?: { image: (ctx: RedisContext) => KeyspaceImage; flush: (space: KeySpace) => Promise; }; }; export declare const WRONGTYPE = "WRONGTYPE Operation against a key holding the wrong kind of value"; export declare const NOT_INT = "ERR value is not an integer or out of range"; export declare const NOT_FLOAT = "ERR value is not a valid float"; export declare const SYNTAX = "ERR syntax error"; export declare const NO_SUCH_KEY = "ERR no such key"; export declare function wrongArity(name: string): string; /** * The commands the core serves, each with the most arguments (after the name) its own parsing takes, * `-1` for no bound: `[min, max]`, where `min` is Redis's table arity and `max` is what the command itself * refuses past, with the same "wrong number of arguments". One table for both callers, `execOne` and * `commandShapeError` (which lets a transaction reject a malformed batch at QUEUE time, as Redis's `EXECABORT` * does). SCRIPT is a container: its subcommands are LOAD, EXISTS and FLUSH. SELECT is the dialect's: a database is * a connection's (Redis) or a URL's (Upstash). */ export declare const SERVED_COMMANDS: Record; /** Redis hash tag: the first nonempty {...} pair, otherwise the entire key (an empty first pair is invalid). */ export declare function redisHashTag(key: string): string; /** Key positions of the shared core's commands. Undefined means database-wide access, a script, or an unknown * command; callers must refuse an unsupported restriction rather than guess that the command has no keys. */ export declare function redisCommandKeys(argv: readonly string[]): string[] | undefined; /** * Does this command MUTATE? Takes the whole argv, not just the name, because two commands are * only writes for some of their subcommands. A read-only twin and `EVAL_RO` both key off this, * and getting it wrong in either direction is a bug: too broad refuses legitimate reads (§9 round * 1), too narrow lets a write through a read-only twin. */ export declare function isWriteCommand(name: string, args: readonly string[] | undefined, dialect: RedisDialect): boolean; /** * QUEUE-TIME validation: is this command well-formed enough to accept into a transaction? Returns the wire's * error string, or `null` when the command is fine. Only structural faults live here (unknown command, wrong * arity) — a WRONGTYPE or a bad integer is a RUNTIME error, which does NOT abort a transaction. */ export declare function commandShapeError(argv: unknown[], dialect: RedisDialect): string | null; /** A database's keys, scripts and write ordinals as the tree holds them. Rows past their deadline are kept: a read * asks `live` at its own instant (Redis's `keyIsExpired` is `now > when`, so a key is still ALIVE at exactly its * deadline — §9 round 1 found the twin one millisecond early). */ export type KeyspaceImage = { rows: Map; scripts: Map; revs: Map; }; declare const GONE: unique symbol; type OverlayState = { own: Map; moved: Set; }; /** * A synchronous, in-memory image of the keyspace for the duration of ONE request. * * Seeded from the keyspace's image (the tree folded by `projectResources`, memoized per World state — the kernel IS * the source of truth); every mutation records the key name in `touched`, and the flush writes exactly those keys * back. This run owns its overlays: nothing a run changes reaches the image or a later request except * through the tree. */ export declare class KeySpace { readonly ctx: RedisContext; readonly nowMs: number; private readonly rows; private readonly touched; private readonly scripts; private readonly touchedScripts; /** name → the last write ordinal seen, INCLUDING for keys currently deleted or expired. */ private readonly revs; /** The shared base maps are patched by the next image(); a KeySpace must finish reading its base before it yields. */ readonly image: KeyspaceImage; constructor(ctx: RedisContext, nowMs: number); /** * Is this row expired AS OF NOW? Checked on every read, not merely when the snapshot was built. * * §9 round 2: a deadline set INTO THE PAST inside a batch (`SET k v PXAT 1`, `GETEX k EXAT 1`) * stayed visible for the rest of that batch, and `TTL` answered a huge negative number that real * Redis can never return. Filtering only at construction time made the twin disagree with itself * within one request; re-checking here makes every read path agree at every instant. */ private live; all(): KeyRow[]; scriptFor(sha: string): string | undefined; hasScript(sha: string): boolean; putScript(sha: string, body: string): void; flushScripts(): void; pendingScriptWrites(): Array<{ sha: string; operation: string; body: string | null; }>; get(name: string): KeyRow | undefined; put(row: KeyRow, operation: string): void; remove(name: string, operation: string): void; /** A point-in-time copy, so a failed script can be rolled back to exactly where it started. */ snapshot(): Snapshot; restore(s: Snapshot): void; pendingWrites(): Array<{ name: string; operation: string; row: KeyRow | null; }>; /** The next write ordinal for a key — see `KeyRow._rev`. Survives deletes and expiry. */ nextRev(name: string): number; /** A key's write ordinal as the tree holds it, 0 for a key never written: what a WATCH compares. */ revOf(name: string): number; /** The keys this run has written so far. */ touchedNames(): string[]; /** Did this run write anything? Used to decide whether the sync token advances. */ get dirty(): boolean; } /** One key as a backup holds it: its name, type, value, deadline and a stream's last id. */ export type KeyImage = { name: string; kind: string; v: unknown; pexpireAt: string | null; lastId?: string; }; /** A database's live keys as they stand at `ctx.occurredAt`: what a backup of it holds (the Developer API lane's * backups, ../api/src/semantics/backups.ts). */ export declare function keyspaceImage(ctx: RedisContext): KeyImage[]; /** Read a database as it stands at `ctx.occurredAt`, writing nothing: what the redis pack's WATCH records and compares. */ export declare function readKeySpace(ctx: RedisContext, read: (space: KeySpace) => T): T; /** Replace a database's keys with a backup's: every live key is deleted, then the image's keys are written ("All * existing data in the target database will be deleted before the restore operation begins", * https://upstash.com/docs/redis/features/backup). */ export declare function restoreKeyspace(image: readonly KeyImage[], ctx: RedisContext): Promise; export declare function expectType(row: KeyRow | undefined, kind: KeyType): void; export declare const asString: (row: KeyRow | undefined) => string | undefined; export declare const asList: (row: KeyRow | undefined) => string[]; export declare const asSet: (row: KeyRow | undefined) => string[]; export declare const asHash: (row: KeyRow | undefined) => HashPairs; export declare const asZSet: (row: KeyRow | undefined) => ZSetPairs; /** Serialize for the kernel. The inverse of `asZSet` — see `StoredZSet`. */ export declare const storeZSet: (pairs: ZSetPairs) => StoredZSet; export declare const asStream: (row: KeyRow | undefined) => StreamEntries; export declare function integerArgument(raw: string, message?: string, unsigned?: boolean): bigint; export declare const commandInteger: (raw: string, message?: string) => number; export declare const toInt: (raw: string, message?: string) => number; export declare const unsignedArgument: (raw: string, message: string) => bigint; export declare function positiveInteger(raw: string, message?: string): number; export declare function toFloat(raw: string): number; /** * Redis's float-increment guard. `t_string.c` and `t_hash.c` both do * `if (isnan(value) || isinf(value)) addReplyError(c,"increment would produce NaN or Infinity")`. * * §9 round 2 found this missing on the string and hash paths (it had only been added to the sorted * set): `INCRBYFLOAT f inf` answered 200 with "inf", `INCRBYFLOAT f -inf` then persisted the * literal "NaN", and the very next `INCRBYFLOAT f 1` answered "not a valid float" — the twin had * written a value it could no longer read. A fake success that poisons its own key. */ export declare function guardFloatResult(next: number): number; /** Redis renders a score as a bulk string; infinities spell out. */ export declare function fmtScore(n: number): string; /** Redis sorts a zset by (score, then member lexicographically). */ export declare function sortZSet(pairs: ZSetPairs): ZSetPairs; /** Redis's start/stop index normalisation (negatives count from the end, ends clamp). */ export declare function normalizeRange(startRaw: number, stopRaw: number, length: number): [number, number]; /** Redis glob-style key matching (`*`, `?`, `[abc]`, `[a-c]`, `[^a]`, `\` escape). */ export declare function globMatch(pattern: string, subject: string): boolean; export declare function execOne(space: KeySpace, argv: string[]): RedisValue; /** * A key's fixed position in SCAN's iteration order: the low 31 bits of its own SHA-1. * * Deriving it from the KEY NAME is the whole point — the position is a property of the key, so * adding or deleting any OTHER key cannot move it, and a key present for the whole scan is * therefore returned exactly once. `+1` keeps every value strictly positive so that cursor 0 * unambiguously means "start"/"done" and can never also mean "resume at the first key". */ export declare function scanCursorFor(key: string): number; /** Live key names, with the internal script-cache keys filtered out of the keyspace entirely. */ /** Every live key name. No filtering: the script cache lives in a different subject type entirely, * so there is no internal name for a caller's key to collide with or be hidden by. */ export declare function visibleKeys(space: KeySpace): string[]; export type ScoreBound = { value: number; exclusive: boolean; }; export declare function parseScoreBound(raw: string): ScoreBound; export declare function inScoreRange(score: number, lo: ScoreBound, hi: ScoreBound): boolean; export declare function zrange(space: KeySpace, name: string, a: string[]): RedisValue; export declare function compareStreamIds(left: string, right: string): number; export declare function parseStreamBound(raw: string, side: 'min' | 'max'): string; export type RunItem = { result: RedisValue; } | { error: string; }; /** * Execute a whole request's worth of commands against one root, then flush. * * Each element comes back as `{result}` or `{error}` — the exact per-command envelope Upstash's * `/pipeline` and `/multi-exec` endpoints return and the SDK's `Pipeline.exec` destructures. * * RUNTIME ERRORS DO NOT ABORT — not in a pipeline and (LIVE-PROBED, contrary to the intuition that * a "transaction" rolls back) NOT in `/multi-exec` either: Upstash's own docs say "all commands * will be executed. Upstash Redis will not stop the processing of commands. This is to provide same * semantics with Redis when there are errors inside a transaction." A probe of the real service * confirmed a `SET` after a failing `INCR` in a `/multi-exec` batch is applied. Structural faults — * an unavailable command or a bad arity — are QUEUE-time and DO discard the whole batch, but the * caller (`upstash-twin.ts`) rejects those before this function is ever reached. */ export declare function execRedisRun(commands: string[][], ctx: RedisContext): Promise<{ items: RunItem[]; wrote: boolean; instant: number; touched: string[]; }>; export {};