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
188 changes: 188 additions & 0 deletions src/components/databrowser/components/search/replace-index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
import { describe, expect, test } from "bun:test"

import { replaceIndex, ReplaceIndexError, type SearchClient } from "./replace-index"

type Operation = "list" | "create" | "wait" | "addAlias" | "deleteAlias" | "drop"

/**
* Index and alias state like redis-server keeps it: queries and SEARCH.WAITINDEXING resolve an
* alias before an index with the same name, and SEARCH.DROP ignores aliases.
*/
const fakeRedis = (
indexes: Record<string, string>,
aliases: Record<string, string> = {},
fail: (operation: Operation, name: string) => boolean = () => false
) => {
const state = { indexes: { ...indexes }, aliases: { ...aliases } }
const queried: string[] = [...Object.keys(indexes), ...Object.keys(aliases)]
// Every name that was queryable must stay queryable after every change
const outages: string[] = []
// Indexes that were waited on, so they have every write
const waited = new Set(Object.keys(indexes))
const resolve = (name: string) => state.aliases[name] ?? name
const unwaited = () => queried.filter((name) => !waited.has(resolve(name)))
const check = (operation: Operation, name: string) => {
if (fail(operation, name)) throw new Error(`${operation} ${name} failed`)
}
const changed = () => {
for (const name of queried) {
if (!Object.hasOwn(state.indexes, resolve(name))) outages.push(name)
}
}
const index = (name: string) => ({
waitIndexing: async () => {
check("wait", name)
waited.add(resolve(name))
return 1 as const
},
drop: async () => {
check("drop", name)
if (!Object.hasOwn(state.indexes, name)) return 0 as const
delete state.indexes[name]
waited.delete(name)
changed()
return 1 as const
},
})
const redis = {
search: {
index: ({ name }: { name: string }) => index(name),
alias: {
list: async () => {
check("list", "")
return { ...state.aliases }
},
add: async ({ indexName, alias }: { indexName: string; alias: string }) => {
check("addAlias", alias)
const added = !Object.hasOwn(state.aliases, alias)
state.aliases[alias] = indexName
changed()
return added ? (1 as const) : (2 as const)
},
delete: async ({ alias }: { alias: string }) => {
check("deleteAlias", alias)
const deleted = Object.hasOwn(state.aliases, alias)
delete state.aliases[alias]
changed()
return deleted ? (1 as const) : (0 as const)
},
},
},
} as unknown as SearchClient
const create = async (name: string) => {
check("create", name)
if (Object.hasOwn(state.indexes, name)) throw new Error(`Index ${name} already exists`)
state.indexes[name] = "new"
return index(name)
}
return { redis, create, state, outages, unwaited }
}

const replace = async (fake: ReturnType<typeof fakeRedis>, name = "users") => {
try {
await replaceIndex(fake.redis, name, fake.create)
} catch (error) {
if (error instanceof ReplaceIndexError) return error
throw error
}
}

const temporaryIndex = (state: { indexes: Record<string, string> }) =>
Object.keys(state.indexes).find((name) => name.startsWith("users-"))

const servedByTemporary = (temporary: string) =>
`"users" is served by the temporary index "${temporary}"`

describe("replaceIndex", () => {
test("re-creates the index under its name without an outage", async () => {
const fake = fakeRedis({ users: "old", other: "old" }, { people: "users", things: "other" })
expect(await replace(fake)).toBeUndefined()
expect(fake.state).toEqual({
indexes: { users: "new", other: "old" },
aliases: { people: "users", things: "other" },
})
expect(fake.outages).toEqual([])
expect(fake.unwaited()).toEqual([])
})

test.each([
["create", "users-"],
["wait", "users-"],
["addAlias", "users"],
["addAlias", "people"],
] as const)("changes nothing when the %s step on %s fails", async (operation, target) => {
let failed = false
const fake = fakeRedis({ users: "old" }, { people: "users" }, (op, name) => {
if (failed || op !== operation || !name.startsWith(target)) return false
if (target === "users" && name !== "users") return false
failed = true
return true
})
const error = await replace(fake)
expect(error?.message).toContain("nothing was changed")
expect(fake.state).toEqual({ indexes: { users: "old" }, aliases: { people: "users" } })
expect(fake.outages).toEqual([])
})

test("names the temporary index when undoing a failed switch fails", async () => {
const fake = fakeRedis({ users: "old" }, { people: "users" }, (op, name) =>
op === "addAlias" ? name === "people" : op === "deleteAlias"
)
const error = await replace(fake)
const temporary = temporaryIndex(fake.state)
expect(temporary).toBeDefined()
expect(error?.message).toContain(`drop the index "${temporary}"`)
expect(fake.outages).toEqual([])
})

test.each([
["drop", "users", servedByTemporary],
["create", "users", servedByTemporary],
["deleteAlias", "users", servedByTemporary],
[
"wait",
"users",
(temporary: string) =>
`so the temporary index "${temporary}" and the aliases pointing at it were left in place`,
],
[
"addAlias",
"people",
(temporary: string) =>
`the aliases "people" still point at the temporary index "${temporary}"`,
],
] as const)(
"keeps serving the new index when the %s step on %s fails",
async (operation, target, expected) => {
let switched = false
const fake = fakeRedis({ users: "old" }, { people: "users" }, (op, name) => {
if (op === "addAlias" && name === "people" && !switched) {
switched = true
return false
}
return op === operation && name === target && (op !== "addAlias" || switched)
})
const error = await replace(fake)
const temporary = temporaryIndex(fake.state)
expect(error?.message).toContain(expected(temporary!))
expect(fake.state.indexes[temporary!]).toBe("new")
expect(fake.outages).toEqual([])
}
)

test("reports a temporary index it could not drop", async () => {
const fake = fakeRedis({ users: "old" }, {}, (op, name) => op === "drop" && name !== "users")
const error = await replace(fake)
expect(error?.message).toContain(`dropping the temporary index "${temporaryIndex(fake.state)}"`)
expect(fake.state.indexes.users).toBe("new")
expect(fake.state.aliases).toEqual({})
expect(fake.outages).toEqual([])
})

test("refuses an index whose name is also an alias", async () => {
const fake = fakeRedis({ users: "old", other: "old" }, { users: "other" })
const error = await replace(fake)
expect(error?.message).toBe(`"users" is also an alias of "other", nothing was changed`)
expect(fake.state.indexes).toEqual({ users: "old", other: "old" })
})
})
130 changes: 130 additions & 0 deletions src/components/databrowser/components/search/replace-index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import type { Redis } from "@upstash/redis"

import { formatUpstashErrorMessage } from "@/lib/utils"

export type SearchClient = { search: Pick<Redis["search"], "index" | "alias"> }

type CreatedIndex = { waitIndexing: () => Promise<unknown>; drop: () => Promise<unknown> }

/** Thrown when saving fails */
export class ReplaceIndexError extends Error {
constructor(message: string) {
super(message)
this.name = "ReplaceIndexError"
}
}

const errorMessage = (error: unknown) =>
formatUpstashErrorMessage(error instanceof Error ? error : new Error(String(error)))

const attempt = async <T>(
run: () => Promise<T>,
message: (error: string) => string
): Promise<T> => {
try {
return await run()
} catch (error) {
throw new ReplaceIndexError(message(errorMessage(error)))
}
}

/** Runs `run` for every target, waiting for all of them, and returns the targets it failed for */
const failedFor = async (targets: string[], run: (target: string) => Promise<unknown>) => {
const results = await Promise.allSettled(targets.map((target) => run(target)))
const failed = targets.filter((_, i) => results[i].status === "rejected")
const reason = results.find((result) => result.status === "rejected")?.reason
return { failed, reason }
}

/**
* Replaces an index with one created by `create`, keeping its name and aliases.
*
* The new index is built under a temporary name first, so a schema the server rejects leaves the
* original untouched. While the index is re-created under its own name, aliases point its name
* and its aliases at the temporary index, so queries keep working. This relies on an alias
* taking precedence over an index with the same name, and on SEARCH.DROP ignoring aliases.
*/
export const replaceIndex = async (
redis: SearchClient,
name: string,
create: (name: string) => Promise<CreatedIndex>,
onStep: (step: string) => void = () => {}
) => {
const { alias } = redis.search

const aliases = await attempt(
() => alias.list(),
(error) => `Could not read the index aliases, nothing was changed: ${error}`
)
if (Object.hasOwn(aliases, name)) {
throw new ReplaceIndexError(
`"${name}" is also an alias of "${aliases[name]}", nothing was changed`
)
}
const names = [name, ...Object.keys(aliases).filter((other) => aliases[other] === name)]
let temporary: string
do {
temporary = `${name}-${Math.random().toString(36).slice(2, 8)}`
} while (Object.hasOwn(aliases, temporary))

onStep("Building the new index...")
const built = await attempt(
() => create(temporary),
(error) => `Could not create the index, nothing was changed: ${error}`
)

const pointBack = (target: string) =>
target === name ? alias.delete({ alias: name }) : alias.add({ indexName: name, alias: target })

try {
await built.waitIndexing()
const { reason } = await failedFor(names, (target) =>
alias.add({ indexName: temporary, alias: target })
)
if (reason !== undefined) throw reason
} catch (error) {
const { failed } = await failedFor(names, pointBack)
const undone =
failed.length === 0 &&
(await built.drop().then(
() => true,
() => false
))
throw new ReplaceIndexError(
undone
? `Could not switch to the new index, nothing was changed: ${errorMessage(error)}`
: `Could not switch to the new index: ${errorMessage(error)}. Undoing it failed too, so check the aliases of "${name}" and drop the index "${temporary}".`
)
}

// From here on, queries to the index and its aliases reach the temporary index
const servedByTemporary = (error: string) =>
`The new schema is saved, but "${name}" is served by the temporary index "${temporary}" through an alias: ${error}`

onStep("Re-creating the index...")
await attempt(() => redis.search.index({ name }).drop(), servedByTemporary)
await attempt(() => create(name), servedByTemporary)
await attempt(() => alias.delete({ alias: name }), servedByTemporary)

// Other aliases still reach the temporary index
const others = names.slice(1)
const aliasesLeft = (left: string[], error: string) =>
left.length === 0
? `The new schema is saved, but dropping the temporary index "${temporary}" failed: ${error}`
: `The new schema is saved, but the aliases ${left.map((other) => `"${other}"`).join(", ")} still point at the temporary index "${temporary}": ${error}`

// Until the alias was deleted, waiting on the name waited on the temporary index
await attempt(
() => redis.search.index({ name }).waitIndexing(),
(error) =>
`The new schema is saved, but waiting for "${name}" to finish indexing failed, so the temporary index "${temporary}"${others.length > 0 ? " and the aliases pointing at it were" : " was"} left in place: ${error}`
)
const { failed, reason } = await failedFor(others, pointBack)
if (reason !== undefined) {
throw new ReplaceIndexError(aliasesLeft(failed, errorMessage(reason)))
}
await attempt(
() => built.drop(),
(error) => aliasesLeft([], error)
)
}
Loading
Loading