Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
estimateExport,
estimateExportBytes,
exportSearchResults,
MAX_EXPORT_RESULTS,
} from "@/lib/export-search-results"
import { parseJSObjectLiteral } from "@/lib/utils"
import { Button } from "@/components/ui/button"
Expand Down Expand Up @@ -46,13 +47,15 @@ export const ExportResultsButton = () => {
const [progress, setProgress] = useState<{ count: number; bytes: number }>({ count: 0, bytes: 0 })
const [estimate, setEstimate] = useState<{ count: number; sampleDocs: SampleDoc[] }>()
const [errorMsg, setErrorMsg] = useState<string>()
const [truncated, setTruncated] = useState(false)

const exportControllerRef = useRef<AbortController | undefined>()
const estimateControllerRef = useRef<AbortController | undefined>()

const isExporting = status === "exporting"
const exportCount = estimate && Math.min(estimate.count, MAX_EXPORT_RESULTS)
const estimatedBytes = estimate
? estimateExportBytes(estimate.count, estimate.sampleDocs, format)
? estimateExportBytes(exportCount ?? 0, estimate.sampleDocs, format)
: undefined

const getFilter = () => parseJSObjectLiteral<Record<string, unknown>>(valuesSearch.query) ?? {}
Expand Down Expand Up @@ -90,6 +93,7 @@ export const ExportResultsButton = () => {
setStatus("idle")
setProgress({ count: 0, bytes: 0 })
setErrorMsg(undefined)
setTruncated(false)
setEstimate(undefined)
setOpen(true)
void runEstimate()
Expand All @@ -107,13 +111,14 @@ export const ExportResultsButton = () => {

setStatus("exporting")
setErrorMsg(undefined)
setTruncated(false)
setProgress({ count: 0, bytes: 0 })

const controller = new AbortController()
exportControllerRef.current = controller

try {
const { content, count, bytes } = await exportSearchResults({
const { content, count, bytes, truncated } = await exportSearchResults({
searchRedis: redisNoPipeline,
readRedis: redis,
indexName,
Expand All @@ -131,8 +136,13 @@ export const ExportResultsButton = () => {
)

setProgress({ count, bytes })
setTruncated(truncated)
setStatus("done")
toast({ description: `Exported ${formatResults(count)}` })
toast({
description: truncated
? `Exported the first ${formatResults(count)}, the search limit`
: `Exported ${formatResults(count)}`,
})
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
setStatus("idle")
Expand Down Expand Up @@ -206,11 +216,18 @@ export const ExportResultsButton = () => {

{status === "idle" && estimate && estimate.count > 0 && (
<div className="text-sm text-zinc-600">
Estimated output: ~{formatResults(estimate.count)}
Estimated output: ~{formatResults(exportCount ?? 0)}
{estimatedBytes ? ` · ~${bytesLib(estimatedBytes)}` : ""}
</div>
)}

{status === "idle" && estimate && estimate.count > MAX_EXPORT_RESULTS && (
<div className="text-sm text-amber-600">
Search can only page through the first {formatResults(MAX_EXPORT_RESULTS)}, so the
export will stop there. Narrow the query to export the rest.
</div>
)}

{status === "idle" && estimate?.count === 0 && (
<div className="text-sm text-zinc-500">This index has no results to export.</div>
)}
Expand All @@ -225,6 +242,13 @@ export const ExportResultsButton = () => {
</div>
)}

{status === "done" && truncated && (
<div className="text-sm text-amber-600">
Stopped at the search limit of {formatResults(MAX_EXPORT_RESULTS)}. Narrow the query
to export the rest.
</div>
)}

{status === "error" && errorMsg && (
<div className="w-full break-words text-sm text-red-500">{errorMsg}</div>
)}
Expand Down
45 changes: 36 additions & 9 deletions src/lib/export-search-results.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
import type { Redis } from "@upstash/redis"
import { describe, expect, test } from "bun:test"

import { exportSearchResults } from "./export-search-results"
import { exportSearchResults, MAX_EXPORT_RESULTS } from "./export-search-results"

// Mimics the app's client (automaticDeserialization: false): JSON and string values are raw text.
// SEARCH.QUERY rejects OFFSET above 10,000 like the server does.
const fakeRedis = (opts: { total: number; values: Record<string, unknown> }) => {
const keys = Array.from({ length: opts.total }, (_, i) => `k:${i}`)
const raw = (key: string) => opts.values[key] ?? opts.values["*"]
return {
search: {
index: () => ({
query: async ({ limit, offset }: { limit: number; offset: number }) =>
keys.slice(offset, offset + limit).map((key) => ({ key, score: 1 })),
query: async ({ limit, offset }: { limit: number; offset: number }) => {
if (offset > 10_000) throw new Error("ERR value is not an integer or out of range")
return keys.slice(offset, offset + limit).map((key) => ({ key, score: 1 }))
},
count: async () => ({ count: opts.total }),
}),
},
json: { get: async (key: string) => raw(key) },
Expand Down Expand Up @@ -40,27 +44,50 @@ describe("exportSearchResults", () => {
const redis = fakeRedis({ total: 1, values: { "*": '{"name":"Ann","meta":{"age":3}}' } })

expect(JSON.parse(await content(redis, "json"))).toEqual([
{ key: "k:0", name: "Ann", meta: { age: 3 } },
{ key: "k:0", score: 1, data: { name: "Ann", meta: { age: 3 } } },
])
expect(await content(redis, "json", "csv")).toBe("key,meta.age,name\nk:0,3,Ann")
expect(await content(redis, "json", "csv")).toBe(
"key,score,data.meta.age,data.name\nk:0,1,3,Ann"
)
})

test("keeps every digit of integers past 2^53", async () => {
const redis = fakeRedis({ total: 1, values: { "*": '{"big":12345678901234567890,"n":1.5}' } })

expect(await content(redis, "json")).toContain('"big": 12345678901234567890,')
expect(await content(redis, "json", "csv")).toBe("key,big,n\nk:0,12345678901234567890,1.5")
expect(await content(redis, "json", "csv")).toBe(
"key,score,data.big,data.n\nk:0,1,12345678901234567890,1.5"
)
})

test("keeps a top-level big integer as the value", async () => {
const redis = fakeRedis({ total: 1, values: { "*": "12345678901234567890" } })

expect(await content(redis, "string")).toContain('"value": 12345678901234567890')
expect(await content(redis, "string", "csv")).toBe("key,value\nk:0,12345678901234567890")
expect(await content(redis, "string")).toContain('"data": 12345678901234567890')
expect(await content(redis, "string", "csv")).toBe("key,score,data\nk:0,1,12345678901234567890")
})

test("keeps non-json string values as-is", async () => {
const redis = fakeRedis({ total: 1, values: { "*": "plain" } })
expect(await content(redis, "string", "csv")).toBe("key,value\nk:0,plain")
expect(await content(redis, "string", "csv")).toBe("key,score,data\nk:0,1,plain")
})

test("hash fields named key or score don't overwrite the document key", async () => {
const redis = fakeRedis({ total: 1, values: { "*": { key: "field", score: "x" } } })

expect(JSON.parse(await content(redis, "hash"))).toEqual([
{ key: "k:0", score: 1, data: { key: "field", score: "x" } },
])
})

test("stops at the search offset limit instead of failing", async () => {
const exact = await run(
fakeRedis({ total: MAX_EXPORT_RESULTS, values: { "*": "v" } }),
"string"
)
expect(exact).toMatchObject({ count: MAX_EXPORT_RESULTS, truncated: false })

const over = await run(fakeRedis({ total: 12_345, values: { "*": "v" } }), "string")
expect(over).toMatchObject({ count: MAX_EXPORT_RESULTS, truncated: true })
})
})
59 changes: 31 additions & 28 deletions src/lib/export-search-results.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ export type ExportFormat = "csv" | "json"

const PAGE_SIZE = 1000
const SAMPLE_SIZE = 50
// SEARCH.QUERY rejects OFFSET above 10,000 and has no cursor, so only the first
// MAX_OFFSET + PAGE_SIZE results of a query can be read.
const MAX_OFFSET = 10_000
export const MAX_EXPORT_RESULTS = MAX_OFFSET + PAGE_SIZE

type IndexDataType = "string" | "hash" | "json"

Expand Down Expand Up @@ -65,15 +69,15 @@ export const exportSearchResults = async (opts: {
format: ExportFormat
signal?: AbortSignal
onProgress?: (p: { count: number; bytes: number }) => void
}): Promise<{ content: string; count: number; bytes: number }> => {
}): Promise<{ content: string; count: number; bytes: number; truncated: boolean }> => {
const { searchRedis, readRedis, indexName, filter, dataType, format, signal, onProgress } = opts

const index = searchRedis.search.index({ name: indexName })
const docs: SearchDoc[] = []
let offset = 0
let bytes = 0

for (;;) {
while (offset <= MAX_OFFSET) {
if (signal?.aborted) throw new DOMException("Aborted", "AbortError")

// `select: {}` -> NOCONTENT -> returns just { key, score } for each match (the proven path).
Expand Down Expand Up @@ -103,11 +107,21 @@ export const exportSearchResults = async (opts: {
if (rows.length < PAGE_SIZE) break
}

// Reading up to the offset cap means there may be more matches.
const truncated =
docs.length === MAX_EXPORT_RESULTS &&
(await index.count({ filter }).then(
({ count }) => count > docs.length,
() => true
))

if (signal?.aborted) throw new DOMException("Aborted", "AbortError")

const content = format === "csv" ? serializeCsv(docs) : serializeJson(docs)

// Report the actual serialized output size (the running `bytes` above is a raw
// approximation used only for live progress and won't match the final file).
return { content, count: docs.length, bytes: new Blob([content]).size }
return { content, count: docs.length, bytes: new Blob([content]).size, truncated }
}

/**
Expand Down Expand Up @@ -163,16 +177,14 @@ export const estimateExportBytes = (
return Math.round(perRow * count)
}

const serializeJson = (docs: SearchDoc[]): string => {
const rows = docs.map((d) => ({
key: d.key,
// A top-level big integer is a rawJSON object, but it's a value, not fields
...(d.data && typeof d.data === "object" && !isRawJSON?.(d.data)
? (d.data as Record<string, unknown>)
: { value: d.data }),
}))
return JSON.stringify(rows, undefined, 2)
}
// Same { key, score, data } shape as SDK query results, so document fields can't
// clobber `key` or `score`.
const serializeJson = (docs: SearchDoc[]): string =>
JSON.stringify(
docs.map(({ key, score, data }) => ({ key, score, data })),
undefined,
2
)

const flatten = (
value: unknown,
Expand Down Expand Up @@ -205,32 +217,23 @@ const escapeCsvCell = (value: unknown): string => {
return str
}

// Columns mirror the JSON rows flattened with dot paths: key, score, data.<field>...
const serializeCsv = (docs: SearchDoc[]): string => {
const flatRows = docs.map((d) => {
const out: Record<string, unknown> = {}
if (d.data && typeof d.data === "object" && !isRawJSON?.(d.data)) {
flatten(d.data, "", out)
} else {
out.value = d.data
}
return out
})
const flatRows = docs.map((d) => flatten(d.data, "data", {}))

const dataColumns = new Set<string>()
for (const row of flatRows) {
for (const col of Object.keys(row)) dataColumns.add(col)
}
const columns = ["key", ...[...dataColumns].sort()]
const columns = [...dataColumns].sort()

const lines: string[] = []
lines.push(columns.map((c) => escapeCsvCell(c)).join(","))
lines.push(["key", "score", ...columns].map((c) => escapeCsvCell(c)).join(","))

for (const [i, doc] of docs.entries()) {
const row = flatRows[i]
const cells = columns.map((col) =>
col === "key" ? escapeCsvCell(doc.key) : escapeCsvCell(row[col])
)
lines.push(cells.join(","))
const cells = [doc.key, doc.score, ...columns.map((col) => row[col])]
lines.push(cells.map((c) => escapeCsvCell(c)).join(","))
}

return lines.join("\n")
Expand Down
Loading