From 25a103916d4495d07ffa6503a7bfab55fa124e92 Mon Sep 17 00:00:00 2001 From: phoenixphoebus <151787300+phoenixphoebus@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:00:26 -0800 Subject: [PATCH 1/2] Show binary elements in collection keys safely Read hash, list, set, sorted set and stream elements as bytes and escape values that are not valid UTF-8 as \xNN. Binary elements are flagged by index so the UI marks them read-only, and saves refuse to overwrite fields or elements that currently hold binary data. Paged collections return the binary indexes of each page; Load more shifts them to where the page's elements land and dedupes with the binary flag, so a binary member is not merged with a text member that escapes to the same string. Co-Authored-By: Claude Opus 5.5 Signed-off-by: phoenixphoebus <151787300+phoenixphoebus@users.noreply.github.com> --- .../key-browser/key-details/binary-indexes.ts | 16 + .../key-browser/key-details/binary-value.tsx | 48 +++ .../key-details/key-details-hash.tsx | 74 ++-- .../key-details/key-details-list.tsx | 15 +- .../key-details/key-details-set.tsx | 15 +- .../key-details/key-details-stream.tsx | 13 +- .../key-details/key-details-string.tsx | 10 +- .../key-details/key-details-zset.tsx | 18 +- .../key-browser/key-details/key-details.tsx | 7 + .../keys/keyBrowserSlice.test.ts | 56 ++- .../valkey-features/keys/keyBrowserSlice.ts | 34 +- .../key-browser.integration.test.ts | 41 ++- .../server/src/__tests__/keys-browser.test.ts | 212 ++++++++++- apps/server/src/keys-browser.ts | 345 ++++++++++++++---- .../src/content/docs/features/key-browser.md | 10 + 15 files changed, 793 insertions(+), 121 deletions(-) create mode 100644 apps/frontend/src/components/key-browser/key-details/binary-indexes.ts create mode 100644 apps/frontend/src/components/key-browser/key-details/binary-value.tsx diff --git a/apps/frontend/src/components/key-browser/key-details/binary-indexes.ts b/apps/frontend/src/components/key-browser/key-details/binary-indexes.ts new file mode 100644 index 000000000..b1836158f --- /dev/null +++ b/apps/frontend/src/components/key-browser/key-details/binary-indexes.ts @@ -0,0 +1,16 @@ +export interface BinaryStreamPart { + entry: number; + field: number; + part: "field" | "value"; +} + +/** + * Looks up whether a stream entry's field name or value at `elements[entry].value[field]` is binary. + */ +export function binaryStreamPartLookup(parts?: BinaryStreamPart[]) { + const set = new Set((parts ?? []).map(({ entry, field, part }) => `${entry}:${field}:${part}`)) + return { + has: (entry: number, field: number, part: BinaryStreamPart["part"]) => set.has(`${entry}:${field}:${part}`), + entryCount: new Set((parts ?? []).map(({ entry }) => entry)).size, + } +} diff --git a/apps/frontend/src/components/key-browser/key-details/binary-value.tsx b/apps/frontend/src/components/key-browser/key-details/binary-value.tsx new file mode 100644 index 000000000..068f241e1 --- /dev/null +++ b/apps/frontend/src/components/key-browser/key-details/binary-value.tsx @@ -0,0 +1,48 @@ +import { TriangleAlert } from "lucide-react" +import { Badge } from "../../ui/badge" +import { Typography } from "../../ui/typography" +import { cn } from "@/lib/utils" + +interface BinaryValueProps { + value: string | number; + isBinary: boolean; + className?: string; +} + +/** + * Shows a read-only value; escaped binary text has no spaces, so it is broken anywhere and badged. + */ +export function BinaryValue({ value, isBinary, className }: BinaryValueProps) { + if (!isBinary) return {String(value)} + return ( +
+ {value} + + binary + +
+ ) +} + +interface BinaryNoticeProps { + count: number; + // Omit for a single value such as a string; otherwise the number of elements and what they're called. + total?: number; + noun?: string; +} + +/** + * One visible notice per key explaining binary data, so it doesn't rely on a hover-only tooltip. + */ +export function BinaryNotice({ count, total, noun }: BinaryNoticeProps) { + if (count === 0) return null + const subject = total === undefined ? "This value contains" : `${count} of ${total} ${noun} ${count === 1 ? "contains" : "contain"}` + return ( +
+ + + {subject} binary data, shown escaped (\xNN) and read-only. + +
+ ) +} diff --git a/apps/frontend/src/components/key-browser/key-details/key-details-hash.tsx b/apps/frontend/src/components/key-browser/key-details/key-details-hash.tsx index 4c745a548..9fa55a45c 100644 --- a/apps/frontend/src/components/key-browser/key-details/key-details-hash.tsx +++ b/apps/frontend/src/components/key-browser/key-details/key-details-hash.tsx @@ -7,6 +7,7 @@ import { EditActionButtons } from "../../ui/edit-action-buttons" import DeleteModal from "../../ui/delete-modal" import { Typography } from "../../ui/typography" import LoadMoreElements from "./load-more-elements" +import { BinaryNotice, BinaryValue } from "./binary-value" import { useAppDispatch } from "@/hooks/hooks" import { updateKeyRequested } from "@/state/valkey-features/keys/keyBrowserSlice" import { cn } from "@/lib/utils" @@ -26,6 +27,8 @@ interface KeyDetailsHashProps { collectionSize?: number; elements: ElementInfo[]; cursor?: string; + binaryKeyIndexes?: number[]; + binaryValueIndexes?: number[]; }; connectionId: string; readOnly:boolean; @@ -37,6 +40,10 @@ interface NewField { value: string; } +/** + * Shows and edits a hash's fields. Binary field names and values are badged and read-only; + * a text field holding a binary value can still be deleted by name. + */ export default function KeyDetailsHash( { selectedKey, selectedKeyInfo, connectionId, readOnly = false }: KeyDetailsHashProps, ) { @@ -46,6 +53,10 @@ export default function KeyDetailsHash( const [deletedHashFields, setDeletedHashFields] = useState>(new Set()) const [pendingDeleteField, setPendingDeleteField] = useState(null) const [newFields, setNewFields] = useState([]) + const binaryKeyIndexes = new Set(selectedKeyInfo.binaryKeyIndexes) + const binaryValueIndexes = new Set(selectedKeyInfo.binaryValueIndexes) + const binaryFieldCount = new Set([...binaryKeyIndexes, ...binaryValueIndexes]).size + const isTextField = (index: number) => !binaryKeyIndexes.has(index) && !binaryValueIndexes.has(index) const handleEdit = () => { if (isEditable) { @@ -57,8 +68,9 @@ export default function KeyDetailsHash( } else { // Start editing const initialHashValue: { [key: string]: string } = {} - selectedKeyInfo.elements.forEach((element: ElementInfo) => { - initialHashValue[element.key] = element.value + // Binary fields are left out so saving never writes their escaped text back as a new field + selectedKeyInfo.elements.forEach((element: ElementInfo, index: number) => { + if (isTextField(index)) initialHashValue[element.key] = element.value }) setEditedHashValue(initialHashValue) setDeletedHashFields(new Set()) @@ -68,9 +80,11 @@ export default function KeyDetailsHash( } const handleSave = () => { - // combine existing edited fields and new fields + const originalValues = new Map(selectedKeyInfo.elements.map((element: ElementInfo) => [element.key, element.value])) + // combine changed existing fields and new fields; unchanged fields are not sent, so a field that + // turned binary after the key loaded is never overwritten unless the user edited it const existingFields = Object.entries(editedHashValue) - .filter(([field]) => !deletedHashFields.has(field)) + .filter(([field, value]) => !deletedHashFields.has(field) && value !== originalValues.get(field)) .map(([field, value]) => ({ field, value, @@ -84,14 +98,18 @@ export default function KeyDetailsHash( value: nf.value, })) - dispatch(updateKeyRequested({ - connectionId: connectionId, - key: selectedKey, - keyType: "hash", - fields: [...existingFields, ...newFieldsToAdd], - deletedHashFields: Array.from(deletedHashFields), - count: selectedKeyInfo.elements.length + newFieldsToAdd.length, - })) + const fields = [...existingFields, ...newFieldsToAdd] + // Nothing changed: the server rejects an update with no fields, so just leave edit mode + if (fields.length > 0 || deletedHashFields.size > 0) { + dispatch(updateKeyRequested({ + connectionId: connectionId, + key: selectedKey, + keyType: "hash", + fields, + deletedHashFields: Array.from(deletedHashFields), + count: selectedKeyInfo.elements.length + newFieldsToAdd.length, + })) + } setIsEditable(false) setEditedHashValue({}) setDeletedHashFields(new Set()) @@ -162,20 +180,30 @@ export default function KeyDetailsHash( + {binaryFieldCount > 0 && ( +
+ +
+ )} {selectedKeyInfo.elements - .filter((element: ElementInfo) => !deletedHashFields.has(element.key)) - .map((element: ElementInfo, index: number) => ( + .map((element: ElementInfo, index: number) => ({ element, index })) + .filter(({ element }) => !deletedHashFields.has(element.key)) + .map(({ element, index }) => (
- {element.key} +
- {isEditable ? ( + {isEditable && !binaryKeyIndexes.has(index) ? (
- handleHashFieldChange(element.key, e.target.value)} - type="text" - value={editedHashValue[element.key] || ""} - /> + {binaryValueIndexes.has(index) ? ( + + ) : ( + handleHashFieldChange(element.key, e.target.value)} + type="text" + value={editedHashValue[element.key] || ""} + /> + )}
diff --git a/apps/frontend/src/components/key-browser/key-details/key-details-list.tsx b/apps/frontend/src/components/key-browser/key-details/key-details-list.tsx index 5b45ac65c..9e65fd05c 100644 --- a/apps/frontend/src/components/key-browser/key-details/key-details-list.tsx +++ b/apps/frontend/src/components/key-browser/key-details/key-details-list.tsx @@ -7,6 +7,7 @@ import { EditActionButtons } from "../../ui/edit-action-buttons" import DeleteModal from "../../ui/delete-modal" import { Typography } from "../../ui/typography" import LoadMoreElements from "./load-more-elements" +import { BinaryNotice, BinaryValue } from "./binary-value" import { useAppDispatch } from "@/hooks/hooks" import { updateKeyRequested } from "@/state/valkey-features/keys/keyBrowserSlice" import { cn } from "@/lib/utils" @@ -21,6 +22,7 @@ interface KeyDetailsListProps { collectionSize?: number; elements: string[]; cursor?: string; + binaryIndexes?: number[]; }; connectionId: string; readOnly: boolean; @@ -31,6 +33,9 @@ interface NewItem { value: string; } +/** + * Shows and edits a list's elements; binary elements are badged and read-only. + */ export default function KeyDetailsList( { selectedKey, selectedKeyInfo, connectionId, readOnly = false }: KeyDetailsListProps, ) { @@ -40,6 +45,7 @@ export default function KeyDetailsList( const [deletedIndices, setDeletedIndices] = useState>(new Set()) const [pendingDeleteIndex, setPendingDeleteIndex] = useState(null) const [newItems, setNewItems] = useState([]) + const binaryIndexes = new Set(selectedKeyInfo.binaryIndexes) const handleEdit = () => { if (isEditable) { @@ -150,6 +156,11 @@ export default function KeyDetailsList(
+ {binaryIndexes.size > 0 && ( +
+ +
+ )} {selectedKeyInfo.elements .map((element: string, index: number) => ({ element, index })) .filter(({ index }) => !deletedIndices.has(index)) @@ -157,7 +168,7 @@ export default function KeyDetailsList(
{index}
- {isEditable ? ( + {isEditable && !binaryIndexes.has(index) ? (
) : ( - {String(element)} + )}
diff --git a/apps/frontend/src/components/key-browser/key-details/key-details-set.tsx b/apps/frontend/src/components/key-browser/key-details/key-details-set.tsx index 41bb94ef1..08046708e 100644 --- a/apps/frontend/src/components/key-browser/key-details/key-details-set.tsx +++ b/apps/frontend/src/components/key-browser/key-details/key-details-set.tsx @@ -7,6 +7,7 @@ import { EditActionButtons } from "../../ui/edit-action-buttons" import DeleteModal from "../../ui/delete-modal" import { Typography } from "../../ui/typography" import LoadMoreElements from "./load-more-elements" +import { BinaryNotice, BinaryValue } from "./binary-value" import { useAppDispatch } from "@/hooks/hooks" import { updateKeyRequested } from "@/state/valkey-features/keys/keyBrowserSlice" import { cn } from "@/lib/utils" @@ -21,6 +22,7 @@ interface KeyDetailsSetProps { collectionSize?: number; elements: string[]; cursor?: string; + binaryIndexes?: number[]; }; connectionId: string; readOnly: boolean; @@ -31,6 +33,9 @@ interface NewItem { value: string; } +/** + * Shows and edits a set's members; binary members are badged and read-only. + */ export default function KeyDetailsSet( { selectedKey, selectedKeyInfo, connectionId, readOnly = false }: KeyDetailsSetProps, ) { @@ -40,6 +45,7 @@ export default function KeyDetailsSet( const [deletedValues, setDeletedValues] = useState>(new Set()) const [pendingDeleteValue, setPendingDeleteValue] = useState(null) const [newItems, setNewItems] = useState([]) + const binaryIndexes = new Set(selectedKeyInfo.binaryIndexes) const handleEdit = () => { if (isEditable) { @@ -147,6 +153,11 @@ export default function KeyDetailsSet(
+ {binaryIndexes.size > 0 && ( +
+ +
+ )} {selectedKeyInfo.elements .map((element: string, index: number) => ({ element, index })) .filter(({ element }) => !deletedValues.has(element)) @@ -154,7 +165,7 @@ export default function KeyDetailsSet(
{index}
- {isEditable ? ( + {isEditable && !binaryIndexes.has(index) ? (
) : ( - {String(element)} + )}
diff --git a/apps/frontend/src/components/key-browser/key-details/key-details-stream.tsx b/apps/frontend/src/components/key-browser/key-details/key-details-stream.tsx index 2d5937b7b..54d03f3ea 100644 --- a/apps/frontend/src/components/key-browser/key-details/key-details-stream.tsx +++ b/apps/frontend/src/components/key-browser/key-details/key-details-stream.tsx @@ -1,4 +1,6 @@ import { Typography } from "../../ui/typography" +import { BinaryNotice, BinaryValue } from "./binary-value" +import { binaryStreamPartLookup, type BinaryStreamPart } from "./binary-indexes" import { cn } from "@/lib/utils" interface KeyDetailsStreamProps { @@ -13,16 +15,23 @@ interface KeyDetailsStreamProps { key: string; value: [string, string][]; }>; + binaryStreamParts?: BinaryStreamPart[]; }; connectionId: string; readOnly: boolean; } +/** + * Shows a stream's entries and their fields; binary field names and values are badged where they occur. + */ export default function KeyDetailsStream( { selectedKeyInfo }: KeyDetailsStreamProps, ) { + const binaryParts = binaryStreamPartLookup(selectedKeyInfo.binaryStreamParts) + return (
+ {selectedKeyInfo?.elements.map((entry, index: number) => (
@@ -44,10 +53,10 @@ export default function KeyDetailsStream( {entry.value.map(([field, value], fieldIndex: number) => ( - {field} + - {value} + ))} diff --git a/apps/frontend/src/components/key-browser/key-details/key-details-string.tsx b/apps/frontend/src/components/key-browser/key-details/key-details-string.tsx index 6b6b950c2..489f3db73 100644 --- a/apps/frontend/src/components/key-browser/key-details/key-details-string.tsx +++ b/apps/frontend/src/components/key-browser/key-details/key-details-string.tsx @@ -2,6 +2,7 @@ import { useState } from "react" import { EditActionButtons } from "../../ui/edit-action-buttons" import { Textarea } from "../../ui/textarea" import { Typography } from "../../ui/typography" +import { BinaryNotice } from "./binary-value" import { useAppDispatch } from "@/hooks/hooks" import { updateKeyRequested } from "@/state/valkey-features/keys/keyBrowserSlice" import { cn } from "@/lib/utils" @@ -70,6 +71,13 @@ export default function KeyDetailsString( + {selectedKeyInfo.isBinary && ( + + + + + + )} {isEditable ? ( @@ -81,7 +89,7 @@ export default function KeyDetailsString( value={editedValue} /> ) : ( - + {selectedKeyInfo.elements} )} diff --git a/apps/frontend/src/components/key-browser/key-details/key-details-zset.tsx b/apps/frontend/src/components/key-browser/key-details/key-details-zset.tsx index 94fcee36b..8ee0d540e 100644 --- a/apps/frontend/src/components/key-browser/key-details/key-details-zset.tsx +++ b/apps/frontend/src/components/key-browser/key-details/key-details-zset.tsx @@ -3,6 +3,7 @@ import { Input } from "../../ui/input" import { EditActionButtons } from "../../ui/edit-action-buttons" import { Typography } from "../../ui/typography" import LoadMoreElements from "./load-more-elements" +import { BinaryNotice, BinaryValue } from "./binary-value" import { useAppDispatch } from "@/hooks/hooks" import { updateKeyRequested } from "@/state/valkey-features/keys/keyBrowserSlice" import { cn } from "@/lib/utils" @@ -22,17 +23,22 @@ interface KeyDetailsZSetProps { collectionSize?: number; elements: ZSetElement[]; cursor?: string; + binaryIndexes?: number[]; }; connectionId: string; readOnly: boolean; } +/** + * Shows and edits a sorted set's members and scores; binary members are badged and read-only. + */ export default function KeyDetailsZSet( { selectedKey, selectedKeyInfo, connectionId, readOnly = false }: KeyDetailsZSetProps, ) { const dispatch = useAppDispatch() const [isEditable, setIsEditable] = useState(false) const [editedValues, setEditedValues] = useState([]) + const binaryIndexes = new Set(selectedKeyInfo.binaryIndexes) console.debug("selectedKeyInfo:::", selectedKeyInfo) @@ -55,7 +61,8 @@ export default function KeyDetailsZSet( member: selectedKeyInfo.elements[index].key, score: newScore, })) - .filter((update, index) => update.score !== selectedKeyInfo.elements[index].value) + // Binary members can't be addressed by their escaped text, so their scores are never sent + .filter((update, index) => !binaryIndexes.has(index) && update.score !== selectedKeyInfo.elements[index].value) dispatch(updateKeyRequested({ connectionId: connectionId, @@ -93,11 +100,16 @@ export default function KeyDetailsZSet(
+ {binaryIndexes.size > 0 && ( +
+ +
+ )} {selectedKeyInfo.elements.map((element: ZSetElement, index: number) => (
- {element.key} +
- {isEditable ? ( + {isEditable && !binaryIndexes.has(index) ? ( handleValueChange(index, e.target.value)} diff --git a/apps/frontend/src/components/key-browser/key-details/key-details.tsx b/apps/frontend/src/components/key-browser/key-details/key-details.tsx index 0620b0e14..8a08eb495 100644 --- a/apps/frontend/src/components/key-browser/key-details/key-details.tsx +++ b/apps/frontend/src/components/key-browser/key-details/key-details.tsx @@ -27,6 +27,10 @@ interface BaseKeyInfo { elementsWarning?: string; isBinary?: boolean; cursor?: string; + binaryIndexes?: number[]; + binaryKeyIndexes?: number[]; + binaryValueIndexes?: number[]; + binaryStreamParts?: { entry: number; field: number; part: "field" | "value" }[]; } interface ElementInfo { @@ -80,6 +84,9 @@ interface keyDetailsProps { readOnly: boolean; } +/** + * Details panel for the selected key: header, TTL and size, and the type-specific value view. + */ export default function KeyDetails({ selectedKey, selectedKeyInfo, connectionId, setSelectedKey, readOnly = false }: keyDetailsProps) { const dispatch = useAppDispatch() const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false) diff --git a/apps/frontend/src/state/valkey-features/keys/keyBrowserSlice.test.ts b/apps/frontend/src/state/valkey-features/keys/keyBrowserSlice.test.ts index 449263264..bc937ecaa 100644 --- a/apps/frontend/src/state/valkey-features/keys/keyBrowserSlice.test.ts +++ b/apps/frontend/src/state/valkey-features/keys/keyBrowserSlice.test.ts @@ -633,7 +633,7 @@ describe("keyBrowserSlice", () => { }) describe("getKeyElements", () => { - const stateWithKey = (key: { type: string; elements: unknown[]; cursor?: string }) => ({ + const stateWithKey = (key: { type: string; elements: unknown[]; cursor?: string; binaryIndexes?: number[] }) => ({ "conn-1": { ...defaultConnectionState, keys: [{ name: "k", collectionSize: 10, ...key }], @@ -669,6 +669,60 @@ describe("keyBrowserSlice", () => { expect(state["conn-1"].elementsLoading["k"]).toBeUndefined() }) + it("shifts the page's binary indexes to where its elements land", () => { + const state = keyBrowserReducer( + stateWithKey({ type: "list", elements: ["a", "\\xff"], binaryIndexes: [1], cursor: "2" }), + getKeyElementsFulfilled({ + connectionId: "conn-1", + key: "k", + cursor: "2", + nextCursor: "4", + elements: ["\\x80", "d"], + binaryIndexes: [0], + collectionSize: 10, + }), + ) + + expect(state["conn-1"].keys[0].elements).toEqual(["a", "\\xff", "\\x80", "d"]) + expect(state["conn-1"].keys[0].binaryIndexes).toEqual([1, 2]) + }) + + it("keeps a binary member that escapes to the same text as a loaded text member", () => { + // The bytes \x80 show as "\x80", which is also how the 4-character text member "\x80" reads. + const state = keyBrowserReducer( + stateWithKey({ type: "set", elements: ["\\x80", "b"], cursor: "9" }), + getKeyElementsFulfilled({ + connectionId: "conn-1", + key: "k", + cursor: "9", + elements: ["b", "\\x80"], + binaryIndexes: [1], + collectionSize: 3, + }), + ) + + expect(state["conn-1"].keys[0].elements).toEqual(["\\x80", "b", "\\x80"]) + expect(state["conn-1"].keys[0].binaryIndexes).toEqual([2]) + }) + + it("shifts hash field name and value indexes separately", () => { + const state = keyBrowserReducer( + stateWithKey({ type: "hash", elements: [{ key: "f1", value: "v1" }], cursor: "5" }), + getKeyElementsFulfilled({ + connectionId: "conn-1", + key: "k", + cursor: "5", + elements: [{ key: "\\xff", value: "v2" }, { key: "f3", value: "\\x00" }], + binaryKeyIndexes: [0], + binaryValueIndexes: [1], + collectionSize: 3, + }), + ) + + expect(state["conn-1"].keys[0].binaryKeyIndexes).toEqual([1]) + expect(state["conn-1"].keys[0].binaryValueIndexes).toEqual([2]) + }) + it("clears the cursor when the last page arrives", () => { const state = keyBrowserReducer( stateWithKey({ type: "list", elements: ["a"], cursor: "1" }), diff --git a/apps/frontend/src/state/valkey-features/keys/keyBrowserSlice.ts b/apps/frontend/src/state/valkey-features/keys/keyBrowserSlice.ts index 593f6d501..946560001 100644 --- a/apps/frontend/src/state/valkey-features/keys/keyBrowserSlice.ts +++ b/apps/frontend/src/state/valkey-features/keys/keyBrowserSlice.ts @@ -11,6 +11,11 @@ interface KeyInfo { elements?: any; elementsWarning?: string; cursor?: string; + isBinary?: boolean; + binaryIndexes?: number[]; + binaryKeyIndexes?: number[]; + binaryValueIndexes?: number[]; + binaryStreamParts?: { entry: number; field: number; part: "field" | "value" }[]; } interface KeyBrowserState { @@ -308,6 +313,10 @@ const keyBrowserSlice = createSlice({ // eslint-disable-next-line @typescript-eslint/no-explicit-any elements: any[]; collectionSize: number; + // Indexes of binary elements within this page's `elements`. + binaryIndexes?: number[]; + binaryKeyIndexes?: number[]; + binaryValueIndexes?: number[]; }>, ) => { const { connectionId, key, cursor, nextCursor, elements, collectionSize } = action.payload @@ -316,9 +325,28 @@ const keyBrowserSlice = createSlice({ delete connection.elementsLoading[key] const target = connection.keys.find((k) => k.name === key) if (!target || !Array.isArray(target.elements) || target.cursor !== cursor) return - const idOf = (element: string | { key: string }) => typeof element === "string" ? element : element.key - const seen = target.type === "list" ? null : new Set(target.elements.map(idOf)) - target.elements.push(...(seen ? elements.filter((element) => !seen.has(idOf(element))) : elements)) + const pageBinary = new Set(action.payload.binaryIndexes) + const pageKeyBinary = new Set(action.payload.binaryKeyIndexes) + const pageValueBinary = new Set(action.payload.binaryValueIndexes) + // Binary members arrive escaped and can read like a text member, so the binary flag is part of the identity. + const idOf = (element: string | { key: string }, isBinary: boolean) => + `${isBinary ? "b" : "t"}:${typeof element === "string" ? element : element.key}` + const loadedBinary = new Set([...(target.binaryIndexes ?? []), ...(target.binaryKeyIndexes ?? [])]) + const seen = target.type === "list" + ? null + : new Set(target.elements.map((element: string | { key: string }, i: number) => idOf(element, loadedBinary.has(i)))) + elements.forEach((element, i) => { + if (seen) { + const id = idOf(element, pageBinary.has(i) || pageKeyBinary.has(i)) + if (seen.has(id)) return + seen.add(id) + } + // Page indexes are shifted to where the element lands in the loaded list. + const index = target.elements.push(element) - 1 + if (pageBinary.has(i)) target.binaryIndexes = [...(target.binaryIndexes ?? []), index] + if (pageKeyBinary.has(i)) target.binaryKeyIndexes = [...(target.binaryKeyIndexes ?? []), index] + if (pageValueBinary.has(i)) target.binaryValueIndexes = [...(target.binaryValueIndexes ?? []), index] + }) target.cursor = nextCursor target.collectionSize = collectionSize }, diff --git a/apps/server/src/__integration__/key-browser.integration.test.ts b/apps/server/src/__integration__/key-browser.integration.test.ts index 756345d95..af8796243 100644 --- a/apps/server/src/__integration__/key-browser.integration.test.ts +++ b/apps/server/src/__integration__/key-browser.integration.test.ts @@ -14,14 +14,17 @@ describe("integration / key browser", async () => { const connectionDetails = defaultConnectionDetails() const connectionId = buildConnectionId(connectionDetails.host, connectionDetails.port, 0) const testKey = `it:${randomUUID()}:roundtrip` + const binaryHashKey = `it:${randomUUID()}:binary-hash` after(async () => { - // delete the test key if still present. + // delete the test keys if still present. if (ws && connectionId) { - ws.send({ - type: VALKEY.KEYS.deleteKeyRequested, - payload: { connectionId, key: testKey }, - }) + for (const key of [testKey, binaryHashKey]) { + ws.send({ + type: VALKEY.KEYS.deleteKeyRequested, + payload: { connectionId, key }, + }) + } } await ws.close() }) @@ -72,4 +75,32 @@ describe("integration / key browser", async () => { assert.equal(delMsg.payload?.key, testKey) assert.equal(delMsg.payload?.deleted, true, "deleted should be true for an existing key") }) + + it("shows text fields of a hash that also holds binary fields", async () => { + // WebSocket payloads are text, so the non-UTF-8 bytes are written from Lua. + ws.send({ + type: VALKEY.COMMAND.sendRequested, + payload: { + connectionId, + command: `EVAL "return redis.call('HSET', KEYS[1], 'name', 'alice', string.char(128, 129), 'x', 'blob', string.char(255))" 1 ${binaryHashKey}`, + }, + }) + await ws.waitFor(VALKEY.COMMAND.sendFulfilled, 10000) + + ws.send({ + type: VALKEY.KEYS.getKeyTypeRequested, + payload: { connectionId, key: binaryHashKey }, + }) + const keyMsg = await ws.waitFor(VALKEY.KEYS.getKeyTypeFulfilled, 10000) + const elements = keyMsg.payload?.elements as { key: string; value: string }[] + + assert.equal(keyMsg.payload?.elementsWarning, undefined) + assert.equal(keyMsg.payload?.collectionSize, 3) + const byField = new Map(elements.map(({ key, value }, index) => [key, { value, index }])) + assert.equal(byField.get("name")?.value, "alice") + assert.equal(byField.get("\\x80\\x81")?.value, "x") + assert.equal(byField.get("blob")?.value, "\\xff") + assert.deepEqual(keyMsg.payload?.binaryKeyIndexes, [byField.get("\\x80\\x81")?.index]) + assert.deepEqual(keyMsg.payload?.binaryValueIndexes, [byField.get("blob")?.index]) + }) }) diff --git a/apps/server/src/__tests__/keys-browser.test.ts b/apps/server/src/__tests__/keys-browser.test.ts index 781abf905..10f1912fe 100644 --- a/apps/server/src/__tests__/keys-browser.test.ts +++ b/apps/server/src/__tests__/keys-browser.test.ts @@ -187,14 +187,133 @@ describe("getKeyInfo", () => { assert.strictEqual(result.name, "mystream") assert.strictEqual(result.type, "stream") assert.strictEqual(result.collectionSize, 2) - assert.ok(Array.isArray(result.elements)) - // Stream entries are nested arrays: [[id, [field, value, ...]], ...] - const elements = result.elements as string[][] - assert.strictEqual(elements.length, 2) - assert.ok(Array.isArray(elements[0])) - assert.ok(Array.isArray(elements[1])) + // Plain RESP entries are normalized to the GLIDE shape: { key: id, value: [[field, value], ...] } + assert.deepStrictEqual(result.elements, [ + { key: "1234567890-0", value: [["field1", "value1"], ["field2", "value2"]] }, + { key: "1234567891-0", value: [["field3", "value3"]] }, + ]) + }) + + }) + + describe("binary collection elements", () => { + it("should flag binary hash field names and values separately while keeping text fields", async () => { + const mockClient = createMockClient({ + TYPE: "hash", + TTL: -1, + MEMORY: 200, + HLEN: 3, + HSCAN: [Buffer.from("0"), [ + Buffer.from("name"), Buffer.from("alice"), + Buffer.from([0x80, 0x81]), Buffer.from("v"), + Buffer.from("blob"), Buffer.from([0xff, 0x00]), + ]], + }) + + const result = await getKeyInfo(mockClient as any, "myhash") + + assert.strictEqual(result.elementsWarning, undefined) + assert.deepStrictEqual(result.elements, [ + { key: "name", value: "alice" }, + { key: "\\x80\\x81", value: "v" }, + { key: "blob", value: "\\xff\\x00" }, + ]) + assert.deepStrictEqual(result.binaryKeyIndexes, [1]) + assert.deepStrictEqual(result.binaryValueIndexes, [2]) + assert.strictEqual(result.binaryIndexes, undefined) + }) + + it("should omit binary indexes and dedupe repeated SCAN fields for text-only hashes", async () => { + const mockClient = createMockClient({ + TYPE: "hash", + TTL: -1, + MEMORY: 200, + HLEN: 1, + HSCAN: [Buffer.from("0"), [Buffer.from("f"), Buffer.from("v"), Buffer.from("f"), Buffer.from("v")]], + }) + + const result = await getKeyInfo(mockClient as any, "myhash") + + assert.deepStrictEqual(result.elements, [{ key: "f", value: "v" }]) + assert.strictEqual(result.binaryKeyIndexes, undefined) + assert.strictEqual(result.binaryValueIndexes, undefined) + }) + + it("should escape binary set members", async () => { + const mockClient = createMockClient({ + TYPE: "set", + TTL: -1, + MEMORY: 100, + SCARD: 2, + SSCAN: [Buffer.from("0"), [Buffer.from("apple"), Buffer.from([0xc3, 0x28])]], + }) + + const result = await getKeyInfo(mockClient as any, "myset") + + assert.deepStrictEqual(result.elements, ["apple", "\\xc3("]) + assert.deepStrictEqual(result.binaryIndexes, [1]) + }) + + it("should escape binary list elements", async () => { + const mockClient = createMockClient({ + TYPE: "list", + TTL: -1, + MEMORY: 100, + LLEN: 3, + LRANGE: [Buffer.from("one"), Buffer.from([0x80, 0x00]), Buffer.from("two")], + }) + + const result = await getKeyInfo(mockClient as any, "mylist") + + assert.deepStrictEqual(result.elements, ["one", "\\x80\\x00", "two"]) + assert.deepStrictEqual(result.binaryIndexes, [1]) + }) + + it("should escape binary zset members and read scores from numbers or bytes", async () => { + const mockClient = createMockClient({ + TYPE: "zset", + TTL: -1, + MEMORY: 100, + ZCARD: 2, + ZRANGE: [ + { key: Buffer.from("a"), value: 1 }, + { key: Buffer.from([0xfe, 0xff]), value: Buffer.from("2.5") }, + ], + }) + + const result = await getKeyInfo(mockClient as any, "myzset") + + assert.deepStrictEqual(result.elements, [{ key: "a", value: 1 }, { key: "\\xfe\\xff", value: "2.5" }]) + assert.deepStrictEqual(result.binaryIndexes, [1]) }) + it("should escape binary stream fields and values and locate each one", async () => { + const mockClient = createMockClient({ + TYPE: "stream", + TTL: -1, + MEMORY: 100, + XLEN: 2, + XRANGE: [ + { key: Buffer.from("1-0"), value: [[Buffer.from("name"), Buffer.from("bob")]] }, + { key: Buffer.from("2-0"), value: [ + [Buffer.from("payload"), Buffer.from([0x89, 0x50])], + [Buffer.from([0xff]), Buffer.from("text")], + ] }, + ], + }) + + const result = await getKeyInfo(mockClient as any, "mystream") + + assert.deepStrictEqual(result.elements, [ + { key: "1-0", value: [["name", "bob"]] }, + { key: "2-0", value: [["payload", "\\x89P"], ["\\xff", "text"]] }, + ]) + assert.deepStrictEqual(result.binaryStreamParts, [ + { entry: 1, field: 0, part: "value" }, + { entry: 1, field: 1, part: "field" }, + ]) + assert.strictEqual(result.binaryIndexes, undefined) + }) }) describe("json keys", () => { @@ -881,6 +1000,59 @@ describe("updateKey", () => { assert.strictEqual(writes.length, 0) }) }) + + describe("hash keys", () => { + it("refuses to overwrite fields holding binary data and issues no write", async () => { + const mockClient = { + customCommand: mock.fn(async (cmd: string[]) => + cmd[0] === "HMGET" ? [Buffer.from("text"), Buffer.from([0xff, 0xfe]), null] : null, + ), + } + const { mockWs: ws, messages } = createMockWs() + + await updateKey(mockClient as any, ws as any, { + connectionId: "conn-123", + key: "myhash", + keyType: "hash", + fields: [ + { field: "name", value: "a" }, + { field: "blob", value: "b" }, + { field: "new", value: "c" }, + ], + }) + + const failed = getMessageOfType(messages, VALKEY.KEYS.updateKeyFailed) + assert.strictEqual(failed.payload.error, "Fields blob hold binary data and cannot be edited as text.") + const writes = mockClient.customCommand.mock.calls.filter( + (call: any) => ["HSET", "HDEL"].includes(call.arguments[0][0]), + ) + assert.strictEqual(writes.length, 0) + }) + }) + + describe("list keys", () => { + it("refuses to overwrite elements holding binary data and issues no write", async () => { + const exec = mock.fn(async () => []) + const mockClient = { + customCommand: mock.fn(async (cmd: string[]) => + cmd[0] === "LINDEX" && cmd[2] === "1" ? Buffer.from([0x80, 0x00]) : Buffer.from("text"), + ), + exec, + } + const { mockWs: ws, messages } = createMockWs() + + await updateKey(mockClient as any, ws as any, { + connectionId: "conn-123", + key: "mylist", + keyType: "list", + listUpdates: [{ index: 0, value: "a" }, { index: 1, value: "b" }], + }) + + const failed = getMessageOfType(messages, VALKEY.KEYS.updateKeyFailed) + assert.strictEqual(failed.payload.error, "Elements at index 1 hold binary data and cannot be edited as text.") + assert.strictEqual(exec.mock.calls.length, 0) + }) + }) }) function createCommandClient(handler: (cmd: string[]) => any) { @@ -1083,6 +1255,34 @@ describe("getKeyElements", () => { assert.strictEqual(message.payload.nextCursor, undefined) }) + it("flags binary elements with indexes relative to the page it returns", async () => { + const client = createMockClient({ + ZCARD: 53, + ZRANGE: [{ key: Buffer.from("m50"), value: 1 }, { key: Buffer.from([0xc3, 0x28]), value: 2 }], + }) + + await getKeyElements(client as any, mockWs, { connectionId: "conn-1", key: "myzset", keyType: "zset", cursor: "50" }) + + const message = getMessageOfType(messages, VALKEY.KEYS.getKeyElementsFulfilled) + assert.deepStrictEqual(message.payload.elements, [{ key: "m50", value: 1 }, { key: "\\xc3(", value: 2 }]) + assert.deepStrictEqual(message.payload.binaryIndexes, [1]) + assert.strictEqual(message.payload.nextCursor, "52") + }) + + it("flags binary hash field names and values on a later page", async () => { + const client = createMockClient({ + HLEN: 3, + HSCAN: [Buffer.from("0"), [Buffer.from([0xff]), Buffer.from("v"), Buffer.from("f"), Buffer.from([0x80])]], + }) + + await getKeyElements(client as any, mockWs, { connectionId: "conn-1", key: "myhash", keyType: "hash", cursor: "7" }) + + const message = getMessageOfType(messages, VALKEY.KEYS.getKeyElementsFulfilled) + assert.deepStrictEqual(message.payload.elements, [{ key: "\\xff", value: "v" }, { key: "f", value: "\\x80" }]) + assert.deepStrictEqual(message.payload.binaryKeyIndexes, [0]) + assert.deepStrictEqual(message.payload.binaryValueIndexes, [1]) + }) + it("returns an empty page with no next cursor when the cursor is past the end", async () => { const client = createMockClient({ LLEN: 10, LRANGE: [] }) diff --git a/apps/server/src/keys-browser.ts b/apps/server/src/keys-browser.ts index 9e76f0b20..e9995147d 100644 --- a/apps/server/src/keys-browser.ts +++ b/apps/server/src/keys-browser.ts @@ -1,14 +1,15 @@ import { WebSocket } from "ws" -import { - GlideClient, - GlideClusterClient, - Batch, ClusterBatch, - RouteOption, - ConnectionError, - TimeoutError, - ClosingError, +import { + GlideClient, + GlideClusterClient, + Batch, ClusterBatch, + RouteOption, + ConnectionError, + TimeoutError, + ClosingError, Decoder, - GlideReturnType + GlideReturnType, + GlideString } from "@valkey/valkey-glide" import pLimit from "p-limit" import { VALKEY, VALKEY_CLIENT } from "valkey-common" @@ -19,7 +20,17 @@ import { buildScanCommandArgs } from "./valkey-client-commands" const keyValueSizeLimitBytes = Number(process.env.KEY_VALUE_SIZE_LIMIT_BYTES) || VALKEY_CLIENT.KEY_VALUE_SIZE_LIMIT_BYTES -interface EnrichedKeyInfo { +/** + * Indexes of binary elements in one page of a list, set, sorted set or hash. + * They are relative to that page's `elements`. + */ +interface BinaryElementIndexes { + binaryIndexes?: number[]; // indexes into list, set or sorted set `elements` that hold binary data, shown escaped. + binaryKeyIndexes?: number[]; // indexes of hash elements whose field name is binary. + binaryValueIndexes?: number[]; // indexes of hash elements whose value is binary. +} + +interface EnrichedKeyInfo extends BinaryElementIndexes { name: string; type: string; ttl: number; @@ -30,6 +41,92 @@ interface EnrichedKeyInfo { elementsWarning?: string; // alternative for elements when they cannot be displayed. isBinary?: boolean; cursor?: string; + binaryStreamParts?: BinaryStreamPart[]; // stream fields or values that are binary. +} + +/** + * Locates one binary field name or value inside a stream entry: `elements[entry].value[field]`. + */ +type BinaryStreamPart = { entry: number; field: number; part: "field" | "value" } + +/** + * Valkey strings are binary-safe, so a value may not be valid UTF-8. Strict decoding tells + * text apart from binary: binary is escaped for display and flagged so edits can be blocked. + */ +const utf8Decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }) + +/** + * Decodes a reply as UTF-8 text, falling back to `\xNN` escapes when the bytes aren't valid UTF-8. + * Numbers and booleans are stringified; an Error reply is rethrown. + */ +function decodeToStringValue(raw: GlideReturnType): { value: string; isBinary: boolean } { + if (typeof raw === "string") return { value: raw, isBinary: false } + if (typeof raw === "number" || typeof raw === "bigint" || typeof raw === "boolean") { + return { value: String(raw), isBinary: false } + } + if (raw instanceof Error) throw raw + if (!Buffer.isBuffer(raw)) { + throw new TypeError(`Expected a string or Buffer reply, got ${typeof raw}`) + } + try { + return { value: utf8Decoder.decode(raw), isBinary: false } + } catch { + const escaped = raw.reduce((s, byte) => + s + (byte >= 0x20 && byte <= 0x7e ? String.fromCharCode(byte) : "\\x" + byte.toString(16).padStart(2, "0")), "", + ) + return { value: escaped, isBinary: true } + } +} + +/** + * Cursors, stream IDs and scores are always ASCII, so they are read as plain text. + */ +function toText(raw: GlideReturnType): string { + return decodeToStringValue(raw).value +} + +/** + * Identifies an element by its raw bytes; escaped binary text isn't unique, so it can't be used for dedupe. + */ +function rawIdentity(raw: GlideReturnType): string { + return Buffer.isBuffer(raw) ? raw.toString("latin1") : String(raw) +} + +/** + * Indexes of the items that pass `test`, or undefined when none do so the payload stays unchanged for text-only keys. + */ +function indexesWhere(items: T[], test: (item: T) => boolean): number[] | undefined { + const indexes = items.flatMap((item, i) => (test(item) ? [i] : [])) + return indexes.length > 0 ? indexes : undefined +} + +/** + * Splits decoded elements into the `elements` payload plus the indexes of the binary ones. + */ +function withBinaryIndexes(decoded: { value: T; isBinary: boolean }[]): { elements: T[]; binaryIndexes?: number[] } { + const binaryIndexes = indexesWhere(decoded, ({ isBinary }) => isBinary) + return { + elements: decoded.map(({ value }) => value), + ...(binaryIndexes ? { binaryIndexes } : {}), + } +} + +type DecodedHashField = { value: { key: string; value: string }; isKeyBinary: boolean; isValueBinary: boolean } + +/** + * Splits decoded hash fields into the `elements` payload plus the indexes of binary field names and binary values, + * so a text field holding a binary value can still be deleted by name. + */ +function withHashBinaryIndexes(decoded: DecodedHashField[]): { + elements: { key: string; value: string }[]; binaryKeyIndexes?: number[]; binaryValueIndexes?: number[] +} { + const binaryKeyIndexes = indexesWhere(decoded, ({ isKeyBinary }) => isKeyBinary) + const binaryValueIndexes = indexesWhere(decoded, ({ isValueBinary }) => isValueBinary) + return { + elements: decoded.map(({ value }) => value), + ...(binaryKeyIndexes ? { binaryKeyIndexes } : {}), + ...(binaryValueIndexes ? { binaryValueIndexes } : {}), + } } const pagedSizeCommands = new Map([ @@ -39,12 +136,17 @@ const pagedSizeCommands = new Map([ ["zset", "ZCARD"], ]) -interface ElementPage { +interface ElementPage extends BinaryElementIndexes { collectionSize: number; elements: unknown[]; cursor?: string; } +/** + * Reads one page of a set or hash with SSCAN/HSCAN, deduping by raw bytes. + * Hash fields become `{ key, value }` pairs. Binary data is escaped; binary set members are listed in + * `binaryIndexes`, binary hash field names in `binaryKeyIndexes` and binary hash values in `binaryValueIndexes`. + */ async function scanPage( client: GlideClient | GlideClusterClient, key: string, @@ -52,25 +154,54 @@ async function scanPage( cursor: string, count: number, ): Promise> { - const results = new Map() + // Keyed by raw bytes so elements SCAN returns more than once are only kept once. + const members = new Map() + const hashFields = new Map() + const size = () => (isHash ? hashFields.size : members.size) let next = cursor do { const [newCursor, raw] = await client.customCommand([ isHash ? "HSCAN" : "SSCAN", key, next, "COUNT", count.toString(), - ]) as [string, GlideReturnType[]] + ], { decoder: Decoder.Bytes }) as [GlideReturnType, GlideReturnType[]] if (isHash) { + // Hash replies are a flat [field1, value1, ...] array. for (let i = 0; i < raw.length; i += 2) { - results.set(raw[i] as string, { key: raw[i] as string, value: raw[i + 1] as string }) + const field = decodeToStringValue(raw[i]) + const value = decodeToStringValue(raw[i + 1]) + hashFields.set(rawIdentity(raw[i]), { + value: { key: field.value, value: value.value }, + isKeyBinary: field.isBinary, + isValueBinary: value.isBinary, + }) } } else { - raw.forEach((member) => results.set(member as string, member as string)) + raw.forEach((member) => members.set(rawIdentity(member), decodeToStringValue(member))) } - next = newCursor - } while (next !== "0" && results.size < count) + next = toText(newCursor) + } while (next !== "0" && size() < count) + + return { + ...(isHash + ? withHashBinaryIndexes(Array.from(hashFields.values())) + : withBinaryIndexes(Array.from(members.values()))), + cursor: next === "0" ? undefined : next, + } +} + +type RawZSetMember = { key: GlideString; value: GlideReturnType } - return { elements: Array.from(results.values()), cursor: next === "0" ? undefined : next } +/** + * Scores arrive as numbers (RESP3 doubles) or, from older servers, as bulk strings. + */ +function decodeScore(raw: GlideReturnType): string | number { + return Buffer.isBuffer(raw) ? toText(raw) : raw as string | number } +/** + * Reads one page of a hash, set, list or sorted set, starting at `cursor`. + * Hashes and sets page with a SCAN cursor; lists and sorted sets with a start index. + * Binary elements are escaped and their indexes within this page are returned alongside. + */ async function fetchElementPage( client: GlideClient | GlideClusterClient, key: string, @@ -93,13 +224,24 @@ async function fetchElementPage( const rangeArgs = keyType === "list" ? ["LRANGE", key, start.toString(), (start + pageSize - 1).toString()] : ["ZRANGE", key, start.toString(), (start + pageSize - 1).toString(), "WITHSCORES"] - const [collectionSize, page] = await Promise.all([getSize, client.customCommand(rangeArgs)]) as [number, unknown[] | null] - const elements = page ?? [] - const next = start + elements.length - - return { collectionSize, elements, cursor: elements.length > 0 && next < collectionSize ? next.toString() : undefined } + const [collectionSize, page] = await Promise.all([ + getSize, client.customCommand(rangeArgs, { decoder: Decoder.Bytes }), + ]) as [number, GlideReturnType[] | null] + const raw = page ?? [] + const decoded = keyType === "list" + ? withBinaryIndexes(raw.map((element) => decodeToStringValue(element))) + : withBinaryIndexes((raw as unknown as RawZSetMember[]).map(({ key: member, value: score }) => { + const { value, isBinary } = decodeToStringValue(member) + return { value: { key: value, value: decodeScore(score) }, isBinary } + })) + const next = start + raw.length + + return { collectionSize, ...decoded, cursor: raw.length > 0 && next < collectionSize ? next.toString() : undefined } } +/** + * Loads the first page of a hash, set, list or sorted set; the rest is fetched on demand with `getKeyElements`. + */ async function getPagedKeyInfo( client: GlideClient | GlideClusterClient, keyInfo: EnrichedKeyInfo, @@ -113,6 +255,55 @@ async function getPagedKeyInfo( } } +type StreamEntry = { key: string; value: [string, string][] } + +type DecodedStreamEntry = { value: StreamEntry; id: string; binaryParts: Omit[] } + +/** + * GLIDE returns entries as { key: id, value: [[field, value], ...] }; plain RESP arrays are [id, [field, value, ...]]. + * Both are normalized to the GLIDE shape. Each binary field name or value is recorded in `binaryParts`. + */ +function decodeStreamEntry(raw: GlideReturnType): DecodedStreamEntry { + const binaryParts: Omit[] = [] + const decodePair = (rawField: GlideReturnType, rawValue: GlideReturnType, field: number): [string, string] => { + const decodedField = decodeToStringValue(rawField) + const decodedValue = decodeToStringValue(rawValue) + if (decodedField.isBinary) binaryParts.push({ field, part: "field" }) + if (decodedValue.isBinary) binaryParts.push({ field, part: "value" }) + return [decodedField.value, decodedValue.value] + } + + if (Array.isArray(raw)) { + const [rawId, rawFields] = raw as [GlideReturnType, GlideReturnType[]] + const id = toText(rawId) + const fields: [string, string][] = [] + for (let i = 0; i < rawFields.length; i += 2) { + fields.push(decodePair(rawFields[i], rawFields[i + 1], i / 2)) + } + return { value: { key: id, value: fields }, id, binaryParts } + } + + const { key, value } = raw as { key: GlideReturnType; value: GlideReturnType[][] } + const id = toText(key) + const fields = value.map(([field, fieldValue], i) => decodePair(field, fieldValue, i)) + return { value: { key: id, value: fields }, id, binaryParts } +} + +/** + * Splits decoded stream entries into the `elements` payload plus the location of every binary field name or value. + */ +function withStreamBinaryParts(decoded: DecodedStreamEntry[]): { elements: StreamEntry[]; binaryStreamParts?: BinaryStreamPart[] } { + const binaryStreamParts = decoded.flatMap(({ binaryParts }, entry) => binaryParts.map((part) => ({ entry, ...part }))) + return { + elements: decoded.map(({ value }) => value), + ...(binaryStreamParts.length > 0 ? { binaryStreamParts } : {}), + } +} + +/** + * Loads a stream with XRANGE one page at a time, resuming after the last entry ID. + * Binary field names and values are escaped and located in `binaryStreamParts`. + */ async function getPaginatedStreamInfo( client: GlideClient | GlideClusterClient, keyInfo: EnrichedKeyInfo, @@ -120,30 +311,31 @@ async function getPaginatedStreamInfo( ): Promise { try { const [firstPage, collectionSize] = await Promise.all([ - client.customCommand([...commands.elementsCmd, "-", "+", "COUNT", VALKEY_CLIENT.ELEMENT_PAGE_SIZE.toString()]), + client.customCommand( + [...commands.elementsCmd, "-", "+", "COUNT", VALKEY_CLIENT.ELEMENT_PAGE_SIZE.toString()], { decoder: Decoder.Bytes }, + ), client.customCommand([commands.sizeCmd, keyInfo.name]), - ]) as [GlideReturnType[][], number] + ]) as [GlideReturnType[], number] - const results: GlideReturnType[][] = [...firstPage] + const results = firstPage.map(decodeStreamEntry) if (firstPage.length === VALKEY_CLIENT.ELEMENT_PAGE_SIZE) { - const lastId = firstPage[firstPage.length - 1][0] as string // The prefix makes the range exclusive, so the last entry isn't re-fetched on the next page // See: https://valkey.io/commands/xrange/ - let cursor = `(${lastId}` + let cursor = `(${results[results.length - 1].id}` while (true) { const entries = await client.customCommand([ ...commands.elementsCmd, cursor, "+", "COUNT", VALKEY_CLIENT.ELEMENT_PAGE_SIZE.toString(), - ]) as GlideReturnType[][] + ], { decoder: Decoder.Bytes }) as GlideReturnType[] if (!entries || entries.length === 0) break - results.push(...entries) + results.push(...entries.map(decodeStreamEntry)) if (entries.length < VALKEY_CLIENT.ELEMENT_PAGE_SIZE) break - cursor = `(${entries[entries.length - 1][0] as string}` + cursor = `(${results[results.length - 1].id}` } } - return { ...keyInfo, collectionSize, elements: results } + return { ...keyInfo, collectionSize, ...withStreamBinaryParts(results) } } catch (err) { console.log(`Could not get elements for key ${keyInfo.name}:`, err) return { ...keyInfo, elementsWarning: VALKEY_CLIENT.MESSAGES.NOT_READABLE } @@ -209,29 +401,9 @@ async function getPaginatedJsonInfo( } } -// Valkey strings are binary-safe, so a value may not be valid UTF-8. Strict decoding tells -// text apart from binary: binary is escaped for display and flagged so edits can be blocked. -const utf8Decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }) - -function decodeToStringValue(raw: GlideReturnType): { value: string; isBinary: boolean } { - if (typeof raw === "string") return { value: raw, isBinary: false } - if (typeof raw === "number" || typeof raw === "bigint" || typeof raw === "boolean") { - return { value: String(raw), isBinary: false } - } - if (raw instanceof Error) throw raw - if (!Buffer.isBuffer(raw)) { - throw new TypeError(`Expected a string or Buffer reply, got ${typeof raw}`) - } - try { - return { value: utf8Decoder.decode(raw), isBinary: false } - } catch { - const escaped = raw.reduce((s, byte) => - s + (byte >= 0x20 && byte <= 0x7e ? String.fromCharCode(byte) : "\\x" + byte.toString(16).padStart(2, "0")), "", - ) - return { value: escaped, isBinary: true } - } -} - +/** + * Reads a whole value in one command (e.g. GET); binary values are escaped and flagged with `isBinary`. + */ async function getFullKeyInfo( client: GlideClient | GlideClusterClient, keyInfo: EnrichedKeyInfo, @@ -577,7 +749,7 @@ export async function getKeyElements( ) { const { connectionId, key, keyType, cursor } = payload try { - const page = await fetchElementPage(client, key, keyType, cursor) + const { cursor: nextCursor, ...page } = await fetchElementPage(client, key, keyType, cursor) ws.send( JSON.stringify({ type: VALKEY.KEYS.getKeyElementsFulfilled, @@ -585,9 +757,8 @@ export async function getKeyElements( connectionId, key, cursor, - nextCursor: page.cursor, - elements: page.elements, - collectionSize: page.collectionSize, + nextCursor, + ...page, // elements, collectionSize and this page's binary indexes }, }), ) @@ -890,6 +1061,10 @@ export async function addKey( // functions for updatin/editing different key types // Note : the update and add functions are quite similar MAYBE can be refactored later +/** + * Overwrites a string key, keeping its TTL unless a new one is given. + * Refuses keys holding binary data, since saving the escaped text would corrupt them. + */ async function updateStringKey( client: GlideClient | GlideClusterClient, key: string, @@ -921,6 +1096,10 @@ async function updateJsonKey( } } +/** + * Deletes and sets hash fields, then applies a new TTL if given. + * Refuses fields that currently hold binary data, since saving the escaped text would corrupt them. + */ async function updateHashKey( client: GlideClient | GlideClusterClient, key: string, @@ -930,6 +1109,13 @@ async function updateHashKey( ) { console.debug("delete hash fields:::", deletedHashFields) console.debug("update hash fields:::", fields) + const names = (fields ?? []).map(({ field }) => field) + if (names.length > 0) { + const current = await client.customCommand(["HMGET", key, ...names], { decoder: Decoder.Bytes }) as GlideReturnType[] + const binary = names.filter((_, i) => current?.[i] != null && decodeToStringValue(current[i]).isBinary) + if (binary.length > 0) throw new Error(`Fields ${binary.join(", ")} hold binary data and cannot be edited as text.`) + } + // first delete fields if any if (deletedHashFields && deletedHashFields.length > 0) { const hdelCommand = ["HDEL", key, ...deletedHashFields] @@ -950,6 +1136,10 @@ async function updateHashKey( } } +/** + * Sets, removes and appends list elements in one batch, then applies a new TTL if given. + * Refuses updates to elements that currently hold binary data, since saving the escaped text would corrupt them. + */ async function updateListKey( client: GlideClient | GlideClusterClient, key: string, @@ -958,11 +1148,27 @@ async function updateListKey( deletedListItems?: { index: number; value: string }[], newListItems?: string[], ) { + if (updates && updates.length > 0) { + const current = await Promise.all(updates.map(({ index }) => + client.customCommand(["LINDEX", key, index.toString()], { decoder: Decoder.Bytes }), + )) + const binary = updates.filter((_, i) => current[i] != null && decodeToStringValue(current[i]).isBinary) + if (binary.length > 0) { + throw new Error(`Elements at index ${binary.map(({ index }) => index).join(", ")} hold binary data and cannot be edited as text.`) + } + } if (client instanceof GlideClient) { const batch = new Batch(true) - // first delete items (sorted by index descending to avoid index shifting issues) + // first update items, while indexes still match the ones checked by LINDEX above + if (updates && updates.length > 0) { + updates.forEach(({ index, value }) => + batch.customCommand(["LSET", key, index.toString(), value]), + ) + } + + // then delete items (sorted by index descending to avoid index shifting issues) if (deletedListItems && deletedListItems.length > 0) { const sortedDeletes = [...deletedListItems].sort((a, b) => b.index - a.index) sortedDeletes.forEach(({ value }) => { @@ -970,13 +1176,6 @@ async function updateListKey( }) } - // then update items - if (updates && updates.length > 0) { - updates.forEach(({ index, value }) => - batch.customCommand(["LSET", key, index.toString(), value]), - ) - } - // then add new items to the end of the list if (newListItems && newListItems.length > 0) { batch.customCommand(["RPUSH", key, ...newListItems]) @@ -990,6 +1189,12 @@ async function updateListKey( } else if (client instanceof GlideClusterClient) { const batch = new ClusterBatch(true) + if (updates && updates.length > 0) { + updates.forEach(({ index, value }) => + batch.customCommand(["LSET", key, index.toString(), value]), + ) + } + if (deletedListItems && deletedListItems.length > 0) { const sortedDeletes = [...deletedListItems].sort((a, b) => b.index - a.index) sortedDeletes.forEach(({ value }) => { @@ -997,12 +1202,6 @@ async function updateListKey( }) } - if (updates && updates.length > 0) { - updates.forEach(({ index, value }) => - batch.customCommand(["LSET", key, index.toString(), value]), - ) - } - // then add new items to the end of the list if (newListItems && newListItems.length > 0) { batch.customCommand(["RPUSH", key, ...newListItems]) diff --git a/docs-site/src/content/docs/features/key-browser.md b/docs-site/src/content/docs/features/key-browser.md index 9178e6d24..2635fcfaf 100644 --- a/docs-site/src/content/docs/features/key-browser.md +++ b/docs-site/src/content/docs/features/key-browser.md @@ -61,6 +61,16 @@ Display entries with their scores, paginated for large collections. Hash, list, set and sorted set keys load their first 50 elements when opened. Use **Load more** at the bottom of the table to fetch the next page; the footer shows how many elements are loaded out of the total. Because only a page is loaded at a time, these keys are not subject to `KEY_VALUE_SIZE_LIMIT_BYTES`, and the browser does not block on keys with millions of members. Saving an edit keeps the elements you have already loaded. +#### Binary Data + +Valkey values are binary-safe, so a string value, hash field or value, list element, set member, sorted set member, or stream field or value may not be valid UTF-8. The Key Browser shows these escaped, with printable ASCII as-is and every other byte as `\xNN` (for example `\x80\x81field`). A notice above the value says how much of the key is binary, for example "2 of 5 fields contain binary data, shown escaped (`\xNN`) and read-only". + +- **Strings**: the value is escaped and the edit button is disabled. +- **Collections**: only the binary parts are escaped and marked with a **binary** badge. They are read-only, while text elements in the same key stay editable and you can still add new elements. In a hash, the badge goes on the field name or the value, whichever is binary; a text field holding a binary value can still be deleted. In a stream, the badge goes on each binary field name or value. +- **Saving**: only fields and elements you changed are sent. The server checks that a hash field or list element still holds text before overwriting it, so data that became binary after the key was loaded is never replaced with escaped text. + +To change binary data, use a client that can send raw bytes, such as `valkey-cli`. + ### Editing Keys - **Update Value**: Modify existing key values From e6fc0ab8e4cf8f061cb05a609756b1a6e318d3a6 Mon Sep 17 00:00:00 2001 From: phoenixphoebus <151787300+phoenixphoebus@users.noreply.github.com> Date: Thu, 26 Nov 2026 20:10:33 -0800 Subject: [PATCH 2/2] Delete list elements by index when saving Saving ran LSET for edits and then LREM key 1 for each delete. If an edit wrote a copy of a deleted value at an earlier index, LREM removed that copy instead: in [x, a, b], setting index 0 to b and deleting index 2 gave [a, b] instead of [b, a]. Now, in the same batch, each deleted index is overwritten with a unique placeholder and then one LREM key 0 removes them all. A delete no longer matches by escaped text, so the server can also remove binary elements (the UI still keeps them read-only). Co-Authored-By: Claude Opus 5.5 Signed-off-by: phoenixphoebus <151787300+phoenixphoebus@users.noreply.github.com> --- .../server/src/__tests__/keys-browser.test.ts | 70 +++++++++++++++++ apps/server/src/keys-browser.ts | 75 +++++++------------ 2 files changed, 95 insertions(+), 50 deletions(-) diff --git a/apps/server/src/__tests__/keys-browser.test.ts b/apps/server/src/__tests__/keys-browser.test.ts index 10f1912fe..4691081f3 100644 --- a/apps/server/src/__tests__/keys-browser.test.ts +++ b/apps/server/src/__tests__/keys-browser.test.ts @@ -1052,6 +1052,76 @@ describe("updateKey", () => { assert.strictEqual(failed.payload.error, "Elements at index 1 hold binary data and cannot be edited as text.") assert.strictEqual(exec.mock.calls.length, 0) }) + + // Runs the batch's LSET/LREM/RPUSH commands against an in-memory list, so tests check the saved result. + function createListClient(initial: string[]) { + const list = [...initial] + const batches: string[][][] = [] + const run = ([cmd, , ...args]: string[]) => { + if (cmd === "LSET") list[Number(args[0])] = args[1] + if (cmd === "RPUSH") list.push(...args) + if (cmd === "LREM") { + // count > 0 removes the first matches from the head; 0 removes every match (negative counts aren't used) + const [count, value] = args + let remaining = Number(count) || Infinity + for (let i = 0; i < list.length && remaining > 0;) { + if (list[i] === value) { list.splice(i, 1); remaining-- } else i++ + } + } + } + const client = { + customCommand: mock.fn(async (cmd: string[]) => { + if (cmd[0] === "LINDEX") return Buffer.from(list[Number(cmd[2])]) + if (cmd[0] === "TYPE") return "list" + if (cmd[0] === "LLEN") return list.length + if (cmd[0] === "LRANGE") return list.map((element) => Buffer.from(element)) + return null + }), + exec: mock.fn(async (batch: any) => { + const commands = batch.commands.map((command: any) => + command.argsArray.args.map((arg: Buffer | string) => arg.toString()) as string[]) + batches.push(commands) + commands.forEach(run) + return [] + }), + } + return { client, list, batches } + } + + it("deletes by index when an edit copies the deleted value to an earlier index", async () => { + // [x, a, b]: set index 0 to "b", delete index 2. LREM by value would remove the new "b" at index 0. + const { client, list, batches } = createListClient(["x", "a", "b"]) + + await updateKey(client as any, mockWs, { + connectionId: "conn-123", + key: "mylist", + keyType: "list", + listUpdates: [{ index: 0, value: "b" }], + deletedListItems: [{ index: 2, value: "b" }], + }) + + assert.deepStrictEqual(list, ["b", "a"]) + assert.strictEqual(batches.length, 1, "edits and deletes are saved in one batch") + const [, , placeholder] = batches[0].find(([cmd]) => cmd === "LREM")! + assert.ok(!["x", "a", "b"].includes(placeholder)) + assert.deepStrictEqual(batches[0].filter(([cmd]) => cmd === "LREM").length, 1) + }) + + it("edits, deletes duplicates and appends in one save", async () => { + // Index 0 becomes another copy of the deleted "a"s; only the elements at indexes 1 and 3 may go. + const { client, list } = createListClient(["x", "a", "b", "a", "c"]) + + await updateKey(client as any, mockWs, { + connectionId: "conn-123", + key: "mylist", + keyType: "list", + listUpdates: [{ index: 0, value: "a" }, { index: 4, value: "d" }], + deletedListItems: [{ index: 1, value: "a" }, { index: 3, value: "a" }], + newListItems: ["e"], + }) + + assert.deepStrictEqual(list, ["a", "b", "d", "e"]) + }) }) }) diff --git a/apps/server/src/keys-browser.ts b/apps/server/src/keys-browser.ts index e9995147d..f6f953f13 100644 --- a/apps/server/src/keys-browser.ts +++ b/apps/server/src/keys-browser.ts @@ -1,3 +1,4 @@ +import { randomUUID } from "node:crypto" import { WebSocket } from "ws" import { GlideClient, @@ -1139,6 +1140,8 @@ async function updateHashKey( /** * Sets, removes and appends list elements in one batch, then applies a new TTL if given. * Refuses updates to elements that currently hold binary data, since saving the escaped text would corrupt them. + * Deletes go by index: each deleted element is first overwritten with a unique placeholder, then every + * placeholder is removed with one LREM. Removing by value could hit an earlier copy of the same value instead. */ async function updateListKey( client: GlideClient | GlideClusterClient, @@ -1158,62 +1161,34 @@ async function updateListKey( } } - if (client instanceof GlideClient) { - const batch = new Batch(true) - - // first update items, while indexes still match the ones checked by LINDEX above - if (updates && updates.length > 0) { - updates.forEach(({ index, value }) => - batch.customCommand(["LSET", key, index.toString(), value]), - ) - } - - // then delete items (sorted by index descending to avoid index shifting issues) - if (deletedListItems && deletedListItems.length > 0) { - const sortedDeletes = [...deletedListItems].sort((a, b) => b.index - a.index) - sortedDeletes.forEach(({ value }) => { - batch.customCommand(["LREM", key, "1", value]) - }) - } - - // then add new items to the end of the list - if (newListItems && newListItems.length > 0) { - batch.customCommand(["RPUSH", key, ...newListItems]) - } - - if (ttl && ttl > 0) { - batch.customCommand(["EXPIRE", key, ttl.toString()]) - } - - await client.exec(batch, true) - } else if (client instanceof GlideClusterClient) { - const batch = new ClusterBatch(true) + const batch = client instanceof GlideClusterClient ? new ClusterBatch(true) : new Batch(true) - if (updates && updates.length > 0) { - updates.forEach(({ index, value }) => - batch.customCommand(["LSET", key, index.toString(), value]), - ) - } + // LSET never shifts elements, so updates and placeholders both use the indexes the client saw. + updates?.forEach(({ index, value }) => + batch.customCommand(["LSET", key, index.toString(), value]), + ) - if (deletedListItems && deletedListItems.length > 0) { - const sortedDeletes = [...deletedListItems].sort((a, b) => b.index - a.index) - sortedDeletes.forEach(({ value }) => { - batch.customCommand(["LREM", key, "1", value]) - }) - } + if (deletedListItems && deletedListItems.length > 0) { + const placeholder = `__valkey-admin-deleted-${randomUUID()}__` + deletedListItems.forEach(({ index }) => + batch.customCommand(["LSET", key, index.toString(), placeholder]), + ) + batch.customCommand(["LREM", key, "0", placeholder]) + } - // then add new items to the end of the list - if (newListItems && newListItems.length > 0) { - batch.customCommand(["RPUSH", key, ...newListItems]) - } + // then add new items to the end of the list + if (newListItems && newListItems.length > 0) { + batch.customCommand(["RPUSH", key, ...newListItems]) + } - if (ttl && ttl > 0) { - batch.customCommand(["EXPIRE", key, ttl.toString()]) - } + if (ttl && ttl > 0) { + batch.customCommand(["EXPIRE", key, ttl.toString()]) + } - await client.exec(batch, true) + if (client instanceof GlideClusterClient) { + await client.exec(batch as ClusterBatch, true) } else { - throw new Error("Unsupported client type") + await client.exec(batch as Batch, true) } }