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.

Add debug logging for Upstash partner search operations

Rafi57a6fb34e39c
diff --git a/apps/web/.env.example b/apps/web/.env.example
index 9df605790c..0d09c879ea 100644
--- a/apps/web/.env.example
+++ b/apps/web/.env.example
@@ -26,6 +26,7 @@ UPSTASH_REDIS_REST_TOKEN=
# Full-text partner search
PARTNER_SEARCH_PROVIDER=
PARTNER_SEARCH_INDEX_NAME=partner-search-v1
+PARTNER_SEARCH_DEBUG=false
# Upstash QStash – required for queues and background jobs
# Get your QStash Token here: https://upstash.com/docs/qstash/overall/getstarted
diff --git a/apps/web/lib/api/partners/search/providers/upstash-redis.ts b/apps/web/lib/api/partners/search/providers/upstash-redis.ts
index e3b6ebf59f..3053327142 100644
--- a/apps/web/lib/api/partners/search/providers/upstash-redis.ts
+++ b/apps/web/lib/api/partners/search/providers/upstash-redis.ts
@@ -112,6 +112,17 @@ interface CreateUpstashRedisPartnerSearchProviderOptions {
indexName?: string;
}
+function logPartnerSearchDebug(
+ operation: "search" | "count" | "groupBy",
+ details: Record<string, unknown>,
+) {
+ if (process.env.PARTNER_SEARCH_DEBUG !== "true") {
+ return;
+ }
+
+ console.log(`[Partner Search Debug] Upstash ${operation}`, details);
+}
+
function getIndexName(indexName?: string): string {
return (
indexName ??
@@ -652,11 +663,25 @@ export function createUpstashRedisPartnerSearchProvider({
...(orderBy && { orderBy }),
}),
);
+ const hits = results.map(({ key, data, score }) => ({
+ key,
+ id: data.id,
+ partnerId: data.partnerId,
+ score,
+ }));
+
+ logPartnerSearchDebug("search", {
+ indexName: resolvedIndexName,
+ query,
+ filter,
+ resultCount: hits.length,
+ hits,
+ });
return {
- hits: results.map(({ data, score }) => ({
- id: data.id,
- partnerId: data.partnerId,
+ hits: hits.map(({ id, partnerId, score }) => ({
+ id,
+ partnerId,
score,
})),
};
@@ -666,6 +691,13 @@ export function createUpstashRedisPartnerSearchProvider({
const result = await withQueryDeadline(() =>
queryIndex.count({ filter: buildUpstashFilter(query) }),
);
+
+ logPartnerSearchDebug("count", {
+ indexName: resolvedIndexName,
+ query,
+ count: result.count,
+ });
+
return result.count;
},
@@ -696,13 +728,23 @@ export function createUpstashRedisPartnerSearchProvider({
);
}
- return buckets.flatMap(({ key, docCount }) => {
+ const groups = buckets.flatMap(({ key, docCount }) => {
const value = mapGroupValue(key);
if (field === "referredByPartnerId" && value === null) {
return [];
}
return [{ value, count: docCount }];
});
+
+ logPartnerSearchDebug("groupBy", {
+ indexName: resolvedIndexName,
+ query,
+ field,
+ groupCount: groups.length,
+ groups,
+ });
+
+ return groups;
},
async waitForIndexing() {
diff --git a/apps/web/scripts/dev/seed-100k-partners.ts b/apps/web/scripts/dev/seed-100k-partners.ts
index 34e9218e0a..98fa4e8f10 100644
--- a/apps/web/scripts/dev/seed-100k-partners.ts
+++ b/apps/web/scripts/dev/seed-100k-partners.ts
@@ -362,7 +362,7 @@ async function main() {
// Step 3: Build the stable namespace shared by every generated chunk.
// Pre-compute the password hash for 'password' once to avoid computing
- // 100,000 separate bcrypt hashes during seeding.
+ // a separate bcrypt hash for every generated partner.
const passwordHash = await hashPassword("password");
const seedNamespace = `${program.id}:${seed}`;
const seedFingerprint = createHash("sha256")
@@ -409,7 +409,7 @@ async function main() {
main()
.catch((e) => {
- console.error("❌ Error running 100K partner seed script:", e);
+ console.error("❌ Error running partner seed script:", e);
process.exit(1);
})
.finally(async () => {
diff --git a/apps/web/scripts/partners/delete-partner-search-index.ts b/apps/web/scripts/partners/delete-partner-search-index.ts
new file mode 100644
index 0000000000..57f4390fef
--- /dev/null
+++ b/apps/web/scripts/partners/delete-partner-search-index.ts
@@ -0,0 +1,133 @@
+import { chunk } from "@dub/utils";
+import { Redis } from "@upstash/redis";
+import "dotenv-flow/config";
+
+const DELETE_BATCH_SIZE = 10_000;
+const SCAN_COUNT = 10_000;
+const MAX_DELETE_PASSES = 3;
+
+interface DeletePartnerSearchIndexArguments {
+ indexName: string;
+ confirm: string;
+}
+
+function parseArguments(args: string[]): DeletePartnerSearchIndexArguments {
+ let indexName: string | undefined;
+ let confirm: string | undefined;
+
+ for (const arg of args) {
+ if (arg.startsWith("--indexName=")) {
+ indexName = arg.slice("--indexName=".length);
+ } else if (arg.startsWith("--confirm=")) {
+ confirm = arg.slice("--confirm=".length);
+ } else {
+ throw new Error(`Unknown argument: ${arg}`);
+ }
+ }
+
+ if (!indexName || !/^[a-zA-Z0-9_-]{1,100}$/.test(indexName)) {
+ throw new Error(
+ "--indexName must contain 1-100 letters, numbers, underscores, or hyphens.",
+ );
+ }
+
+ if (confirm !== indexName) {
+ throw new Error(`Pass --confirm=${indexName} to confirm deletion.`);
+ }
+
+ return { indexName, confirm };
+}
+
+function createRedisClient() {
+ const url = process.env.UPSTASH_REDIS_REST_URL;
+ const token = process.env.UPSTASH_REDIS_REST_TOKEN;
+
+ if (!url || !token) {
+ throw new Error(
+ "UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN are required.",
+ );
+ }
+
+ return new Redis({ url, token });
+}
+
+async function deleteDocumentPass(redis: Redis, documentPattern: string) {
+ let cursor = "0";
+ let deleted = 0;
+
+ do {
+ const [nextCursor, keys] = await redis.scan(cursor, {
+ match: documentPattern,
+ count: SCAN_COUNT,
+ });
+
+ for (const keyBatch of chunk(keys, DELETE_BATCH_SIZE)) {
+ deleted += await redis.del(...keyBatch);
+ }
+
+ cursor = nextCursor;
+ } while (cursor !== "0");
+
+ return deleted;
+}
+
+async function deleteDocuments(redis: Redis, indexName: string) {
+ const documentPattern = `${indexName}:*`;
+ let totalDeleted = 0;
+
+ // Repeat the scan to verify that no matching keys remain after deletion
+ for (let pass = 1; pass <= MAX_DELETE_PASSES; pass++) {
+ const deleted = await deleteDocumentPass(redis, documentPattern);
+ totalDeleted += deleted;
+
+ console.log(
+ `Deletion pass ${pass}: ${deleted.toLocaleString()} documents removed`,
+ );
+
+ if (deleted === 0) {
+ return totalDeleted;
+ }
+ }
+
+ throw new Error(
+ `Documents matching ${documentPattern} are still being created. Stop application processes using this index and run the script again.`,
+ );
+}
+
+async function main() {
+ const { indexName } = parseArguments(process.argv.slice(2));
+ const redis = createRedisClient();
+ const index = redis.search.index({ name: indexName });
+ const description = await index.describe();
+ const expectedPrefix = `${indexName}:`;
+
+ // Step 1: Verify that an existing index owns only the requested key prefix
+ if (
+ description &&
+ (description.prefixes.length !== 1 ||
+ description.prefixes[0] !== expectedPrefix)
+ ) {
+ throw new Error(
+ `Index ${indexName} does not use the expected ${expectedPrefix} prefix.`,
+ );
+ }
+
+ // Step 2: Drop the search index without affecting unrelated Redis data
+ const dropped = await index.drop();
+ console.log(
+ dropped === 1
+ ? `Dropped partner search index ${indexName}`
+ : `Partner search index ${indexName} did not exist`,
+ );
+
+ // Step 3: Delete partner and tag documents stored under this index namespace
+ const deleted = await deleteDocuments(redis, indexName);
+ console.log(
+ `Partner search cleanup complete: ${deleted.toLocaleString()} documents removed.`,
+ );
+}
+
+main().catch((error) => {
+ console.error("Failed to delete partner search index:", error);
+ process.exit(1);
+});