Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Wait for partner search indexing and validate index schema

Rafie0281ad65248
diff --git a/apps/web/lib/api/partners/search/backfill.ts b/apps/web/lib/api/partners/search/backfill.ts
index c4b7d92a14..8846d62241 100644
--- a/apps/web/lib/api/partners/search/backfill.ts
+++ b/apps/web/lib/api/partners/search/backfill.ts
@@ -77,6 +77,8 @@ export async function backfillPartnerSearch({
}
}
+ await searchProvider.waitForIndexing();
+
return {
processed,
lastDocumentId: lastDocumentId ?? null,
diff --git a/apps/web/lib/api/partners/search/mock-provider.ts b/apps/web/lib/api/partners/search/mock-provider.ts
index af235734a7..5835dacdc3 100644
--- a/apps/web/lib/api/partners/search/mock-provider.ts
+++ b/apps/web/lib/api/partners/search/mock-provider.ts
@@ -173,7 +173,6 @@ export function createMockPartnerSearchProvider(
id: document.id,
partnerId: document.partnerId,
})),
- total: matches.length,
};
},
@@ -196,6 +195,8 @@ export function createMockPartnerSearchProvider(
return Array.from(groups, ([value, count]) => ({ value, count }));
},
+ async waitForIndexing() {},
+
async upsert(updatedDocuments) {
for (const document of updatedDocuments) {
documents.set(document.id, document);
diff --git a/apps/web/lib/api/partners/search/types.ts b/apps/web/lib/api/partners/search/types.ts
index fc719f9138..dea2f68d35 100644
--- a/apps/web/lib/api/partners/search/types.ts
+++ b/apps/web/lib/api/partners/search/types.ts
@@ -126,7 +126,6 @@ export interface PartnerSearchHit {
export interface PartnerSearchResult {
hits: PartnerSearchHit[];
- total: number;
}
export interface PartnerSearchProvider {
@@ -136,6 +135,7 @@ export interface PartnerSearchProvider {
query: PartnerSearchCountQuery,
field: PartnerSearchGroupField,
): Promise<PartnerSearchGroup[]>;
+ waitForIndexing(): Promise<void>;
upsert(documents: PartnerSearchDocument[]): Promise<void>;
delete(documentIds: string[]): Promise<void>;
}
diff --git a/apps/web/lib/api/partners/search/upstash-redis-provider.ts b/apps/web/lib/api/partners/search/upstash-redis-provider.ts
index 421725d819..361c6db30b 100644
--- a/apps/web/lib/api/partners/search/upstash-redis-provider.ts
+++ b/apps/web/lib/api/partners/search/upstash-redis-provider.ts
@@ -24,6 +24,8 @@ const DEFAULT_INDEX_NAME = "partner-search-v1";
const NULL_VALUE = "__none__";
const MAX_GROUPS = 1_000;
const TRANSIENT_RETRY_ATTEMPTS = 2;
+const QUERY_REQUEST_TIMEOUT_MS = 400;
+const WRITE_REQUEST_TIMEOUT_MS = 10_000;
const WRITE_BATCH_SIZE = 100;
const DOCUMENT_TYPE_PARTNER = "partner";
const DOCUMENT_TYPE_TAG = "tag";
@@ -95,6 +97,7 @@ interface UpstashPartnerSearchDocument extends Record<string, unknown> {
interface CreateUpstashRedisPartnerSearchProviderOptions {
redisClient?: Redis;
+ queryRedisClient?: Redis;
indexName?: string;
}
@@ -122,7 +125,7 @@ function getTagDocumentKey(
return `${getDocumentPrefix(indexName)}tag:${documentId}:${partnerTagId}`;
}
-function createRedisClient(): Redis {
+function createRedisClient(requestTimeoutMs: number): Redis {
const url = process.env.UPSTASH_REDIS_REST_URL;
const token = process.env.UPSTASH_REDIS_REST_TOKEN;
@@ -132,7 +135,13 @@ function createRedisClient(): Redis {
);
}
- return new Redis({ url, token });
+ return new Redis({
+ url,
+ token,
+ // The provider wrapper owns the retry budget
+ retry: { retries: 0 },
+ signal: () => AbortSignal.timeout(requestTimeoutMs),
+ });
}
function getEmailNgrams(email: string | null): string {
@@ -363,6 +372,52 @@ function mapGroupValue(value: string): string | null {
return value === NULL_VALUE ? null : value;
}
+function getSchemaSignature(schema: Record<string, Record<string, unknown>>) {
+ return JSON.stringify(
+ Object.fromEntries(
+ Object.entries(schema)
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([field, options]) => [
+ field,
+ Object.fromEntries(
+ Object.entries(options).sort(([left], [right]) =>
+ left.localeCompare(right),
+ ),
+ ),
+ ]),
+ ),
+ );
+}
+
+function validateIndexDescription(
+ description: NonNullable<
+ Awaited<ReturnType<UpstashPartnerSearchIndex["describe"]>>
+ >,
+ indexName: string,
+) {
+ const expectedPrefix = getDocumentPrefix(indexName);
+ const hasExpectedPrefix =
+ description.prefixes.length === 1 &&
+ description.prefixes[0] === expectedPrefix;
+ const hasExpectedSchema =
+ getSchemaSignature(
+ description.schema as Record<string, Record<string, unknown>>,
+ ) ===
+ getSchemaSignature(
+ upstashPartnerSearchSchema as Record<string, Record<string, unknown>>,
+ );
+
+ if (
+ description.dataType !== "json" ||
+ !hasExpectedPrefix ||
+ !hasExpectedSchema
+ ) {
+ throw new Error(
+ `Partner search index ${indexName} does not match the configured schema. Create a new versioned index.`,
+ );
+ }
+}
+
function getStoredDocument(
value: UpstashPartnerSearchDocument[] | null,
): UpstashPartnerSearchDocument | null {
@@ -475,12 +530,14 @@ async function deleteDocumentBatch(
}
export async function createUpstashRedisPartnerSearchIndex({
- redisClient = createRedisClient(),
+ redisClient,
indexName,
}: CreateUpstashRedisPartnerSearchProviderOptions = {}) {
+ const resolvedRedisClient =
+ redisClient ?? createRedisClient(WRITE_REQUEST_TIMEOUT_MS);
const resolvedIndexName = getIndexName(indexName);
- return redisClient.search.createIndex({
+ const index = await resolvedRedisClient.search.createIndex({
name: resolvedIndexName,
dataType: "json",
prefix: getDocumentPrefix(resolvedIndexName),
@@ -488,17 +545,40 @@ export async function createUpstashRedisPartnerSearchIndex({
skipInitialScan: true,
existsOk: true,
});
+ const description = await index.describe();
+
+ if (!description) {
+ throw new Error(
+ `Partner search index ${resolvedIndexName} was not created.`,
+ );
+ }
+
+ validateIndexDescription(description, resolvedIndexName);
+ return index;
}
export function createUpstashRedisPartnerSearchProvider({
- redisClient = createRedisClient(),
+ redisClient,
+ queryRedisClient,
indexName,
}: CreateUpstashRedisPartnerSearchProviderOptions = {}): PartnerSearchProvider {
+ const resolvedRedisClient =
+ redisClient ?? createRedisClient(WRITE_REQUEST_TIMEOUT_MS);
+ const resolvedQueryRedisClient =
+ queryRedisClient ??
+ redisClient ??
+ createRedisClient(QUERY_REQUEST_TIMEOUT_MS);
const resolvedIndexName = getIndexName(indexName);
- const index: UpstashPartnerSearchIndex = redisClient.search.index({
- name: resolvedIndexName,
- schema: upstashPartnerSearchSchema,
- });
+ const queryIndex: UpstashPartnerSearchIndex =
+ resolvedQueryRedisClient.search.index({
+ name: resolvedIndexName,
+ schema: upstashPartnerSearchSchema,
+ });
+ const writeIndex: UpstashPartnerSearchIndex =
+ resolvedRedisClient.search.index({
+ name: resolvedIndexName,
+ schema: upstashPartnerSearchSchema,
+ });
return {
async search(query: PartnerSearchQuery) {
@@ -510,18 +590,15 @@ export function createUpstashRedisPartnerSearchProvider({
} as Record<string, "ASC" | "DESC">)
: undefined;
- const [results, { count }] = await Promise.all([
- withTransientRetry(() =>
- index.query({
- filter,
- limit: query.pageSize,
- offset,
- select: { id: true, partnerId: true },
- ...(orderBy && { orderBy }),
- }),
- ),
- withTransientRetry(() => index.count({ filter })),
- ]);
+ const results = await withTransientRetry(() =>
+ queryIndex.query({
+ filter,
+ limit: query.pageSize,
+ offset,
+ select: { id: true, partnerId: true },
+ ...(orderBy && { orderBy }),
+ }),
+ );
return {
hits: results.map(({ data, score }) => ({
@@ -529,13 +606,12 @@ export function createUpstashRedisPartnerSearchProvider({
partnerId: data.partnerId,
score,
})),
- total: count,
};
},
async count(query) {
const result = await withTransientRetry(() =>
- index.count({ filter: buildUpstashFilter(query) }),
+ queryIndex.count({ filter: buildUpstashFilter(query) }),
);
return result.count;
},
@@ -545,7 +621,7 @@ export function createUpstashRedisPartnerSearchProvider({
const documentType =
field === "partnerTagId" ? DOCUMENT_TYPE_TAG : DOCUMENT_TYPE_PARTNER;
const result = await withTransientRetry(() =>
- index.aggregate({
+ queryIndex.aggregate({
filter: buildUpstashFilter(query, documentType),
aggregations: {
groups: {
@@ -567,10 +643,19 @@ export function createUpstashRedisPartnerSearchProvider({
});
},
+ async waitForIndexing() {
+ const result = await withTransientRetry(() => writeIndex.waitIndexing());
+ if (result === 0) {
+ throw new Error(
+ `Partner search index ${resolvedIndexName} was not found.`,
+ );
+ }
+ },
+
async upsert(documents) {
for (const documentBatch of chunk(documents, WRITE_BATCH_SIZE)) {
await upsertDocumentBatch(
- redisClient,
+ resolvedRedisClient,
resolvedIndexName,
documentBatch,
);
@@ -580,7 +665,7 @@ export function createUpstashRedisPartnerSearchProvider({
async delete(documentIds) {
for (const documentIdBatch of chunk(documentIds, WRITE_BATCH_SIZE)) {
await deleteDocumentBatch(
- redisClient,
+ resolvedRedisClient,
resolvedIndexName,
documentIdBatch,
);
diff --git a/apps/web/tests/partners/get-partners-count-search.test.ts b/apps/web/tests/partners/get-partners-count-search.test.ts
index a3e476a941..a62c0e6929 100644
--- a/apps/web/tests/partners/get-partners-count-search.test.ts
+++ b/apps/web/tests/partners/get-partners-count-search.test.ts
@@ -9,6 +9,7 @@ function createSearchProvider(): PartnerSearchProvider {
search: vi.fn(),
count: vi.fn().mockResolvedValue(2),
groupBy: vi.fn().mockResolvedValue([{ value: "approved", count: 2 }]),
+ waitForIndexing: vi.fn(),
upsert: vi.fn(),
delete: vi.fn(),
};
diff --git a/apps/web/tests/partners/get-partners-search.test.ts b/apps/web/tests/partners/get-partners-search.test.ts
index c017e9e772..6f7cbf9a20 100644
--- a/apps/web/tests/partners/get-partners-search.test.ts
+++ b/apps/web/tests/partners/get-partners-search.test.ts
@@ -47,10 +47,10 @@ describe("getPartners search", () => {
{ id: "pge_2", partnerId: "pn_2" },
{ id: "pge_1", partnerId: "pn_1" },
],
- total: 2,
}),
count: vi.fn(),
groupBy: vi.fn(),
+ waitForIndexing: vi.fn(),
upsert: vi.fn(),
delete: vi.fn(),
};
@@ -93,6 +93,7 @@ describe("getPartners search", () => {
.mockRejectedValue(new Error("Provider Connection Timeout")),
count: vi.fn(),
groupBy: vi.fn(),
+ waitForIndexing: vi.fn(),
upsert: vi.fn(),
delete: vi.fn(),
};
diff --git a/apps/web/tests/partners/partner-search-backfill.test.ts b/apps/web/tests/partners/partner-search-backfill.test.ts
index 0f581309b7..127b128aed 100644
--- a/apps/web/tests/partners/partner-search-backfill.test.ts
+++ b/apps/web/tests/partners/partner-search-backfill.test.ts
@@ -62,6 +62,7 @@ function createProvider(): PartnerSearchProvider {
search: vi.fn(),
count: vi.fn(),
groupBy: vi.fn(),
+ waitForIndexing: vi.fn(),
upsert: vi.fn(),
delete: vi.fn(),
};
@@ -102,6 +103,7 @@ describe("backfillPartnerSearch", () => {
take: 2,
});
expect(searchProvider.upsert).toHaveBeenCalledTimes(2);
+ expect(searchProvider.waitForIndexing).toHaveBeenCalledOnce();
expect(onProgress).toHaveBeenLastCalledWith({
batchSize: 1,
processed: 3,
diff --git a/apps/web/tests/partners/partner-search-provider.test.ts b/apps/web/tests/partners/partner-search-provider.test.ts
index 991cd15dda..90ee67c7dc 100644
--- a/apps/web/tests/partners/partner-search-provider.test.ts
+++ b/apps/web/tests/partners/partner-search-provider.test.ts
@@ -63,7 +63,7 @@ describe("partner search provider contract", () => {
pageSize: 10,
});
- expect(result.total).toBe(1);
+ expect(result.hits).toHaveLength(1);
expect(result.hits[0]?.partnerId).toBe(partnerDocument.partnerId);
});
@@ -77,7 +77,7 @@ describe("partner search provider contract", () => {
pageSize: 10,
});
- expect(result).toEqual({ hits: [], total: 0 });
+ expect(result).toEqual({ hits: [] });
});
it("combines search with filters", async () => {
@@ -96,7 +96,7 @@ describe("partner search provider contract", () => {
},
});
- expect(result.total).toBe(1);
+ expect(result.hits).toHaveLength(1);
});
it("sorts filtered search results", async () => {
diff --git a/apps/web/tests/partners/partner-search-sync.test.ts b/apps/web/tests/partners/partner-search-sync.test.ts
index ac7f282c5a..975f7288c9 100644
--- a/apps/web/tests/partners/partner-search-sync.test.ts
+++ b/apps/web/tests/partners/partner-search-sync.test.ts
@@ -65,6 +65,7 @@ function createProvider(): PartnerSearchProvider {
search: vi.fn(),
count: vi.fn(),
groupBy: vi.fn(),
+ waitForIndexing: vi.fn(),
upsert: vi.fn(),
delete: vi.fn(),
};
diff --git a/apps/web/tests/partners/upstash-redis-partner-search-provider.test.ts b/apps/web/tests/partners/upstash-redis-partner-search-provider.test.ts
index ca26df50de..617f608345 100644
--- a/apps/web/tests/partners/upstash-redis-partner-search-provider.test.ts
+++ b/apps/web/tests/partners/upstash-redis-partner-search-provider.test.ts
@@ -2,6 +2,7 @@ import {
createUpstashRedisPartnerSearchIndex,
createUpstashRedisPartnerSearchProvider,
type PartnerSearchDocument,
+ upstashPartnerSearchSchema,
} from "@/lib/api/partners/search";
import type { Redis } from "@upstash/redis";
import { beforeEach, describe, expect, it, vi } from "vitest";
@@ -47,20 +48,25 @@ const mocks = vi.hoisted(() => ({
count: vi.fn(),
createIndex: vi.fn(),
del: vi.fn(),
+ describe: vi.fn(),
index: vi.fn(),
jsonMget: vi.fn(),
jsonMset: vi.fn(),
query: vi.fn(),
+ waitIndexing: vi.fn(),
}));
function createRedisMock(): Redis {
const searchIndex = {
aggregate: mocks.aggregate,
count: mocks.count,
+ describe: mocks.describe,
query: mocks.query,
+ waitIndexing: mocks.waitIndexing,
};
mocks.index.mockReturnValue(searchIndex);
+ mocks.createIndex.mockReturnValue(searchIndex);
return {
del: mocks.del,
@@ -82,11 +88,17 @@ describe("Upstash Redis partner search provider", () => {
groups: { buckets: [], sumOtherDocCount: 0 },
});
mocks.count.mockResolvedValue({ count: 0 });
- mocks.createIndex.mockResolvedValue(undefined);
mocks.del.mockResolvedValue(0);
+ mocks.describe.mockResolvedValue({
+ name: "test-index",
+ dataType: "json",
+ prefixes: ["test-index:"],
+ schema: upstashPartnerSearchSchema,
+ });
mocks.jsonMget.mockResolvedValue([]);
mocks.jsonMset.mockResolvedValue("OK");
mocks.query.mockResolvedValue([]);
+ mocks.waitIndexing.mockResolvedValue(1);
});
it("searches within the program and supports partial email matching", async () => {
@@ -97,7 +109,6 @@ describe("Upstash Redis partner search provider", () => {
data: { id: document.id, partnerId: document.partnerId },
},
]);
- mocks.count.mockResolvedValue({ count: 1 });
const provider = createUpstashRedisPartnerSearchProvider({
redisClient: createRedisMock(),
indexName: "test-index",
@@ -113,8 +124,8 @@ describe("Upstash Redis partner search provider", () => {
expect(result).toEqual({
hits: [{ id: document.id, partnerId: document.partnerId, score: 2 }],
- total: 1,
});
+ expect(mocks.count).not.toHaveBeenCalled();
expect(mocks.query).toHaveBeenCalledWith(
expect.objectContaining({
limit: 25,
@@ -314,6 +325,17 @@ describe("Upstash Redis partner search provider", () => {
);
});
+ it("waits for pending index updates", async () => {
+ const provider = createUpstashRedisPartnerSearchProvider({
+ redisClient: createRedisMock(),
+ indexName: "test-index",
+ });
+
+ await provider.waitForIndexing();
+
+ expect(mocks.waitIndexing).toHaveBeenCalledOnce();
+ });
+
it("creates the index explicitly with the partner-search prefix", async () => {
const redisClient = createRedisMock();
@@ -332,4 +354,20 @@ describe("Upstash Redis partner search provider", () => {
}),
);
});
+
+ it("rejects an existing index with a stale schema", async () => {
+ mocks.describe.mockResolvedValue({
+ name: "test-index",
+ dataType: "json",
+ prefixes: ["test-index:"],
+ schema: { id: { type: "KEYWORD" } },
+ });
+
+ await expect(
+ createUpstashRedisPartnerSearchIndex({
+ redisClient: createRedisMock(),
+ indexName: "test-index",
+ }),
+ ).rejects.toThrow("Create a new versioned index");
+ });
});