Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | 1x 1x 36x 36x 2x 34x 1x 13x 13x 6x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 3x 3x 3x 3x 3x 3x 3x 3x 7x 7x 13x 1x 3x 3x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 3x 15x 15x 15x 8x 8x 8x 15x 15x 8x 8x 8x 15x 5x 5x 15x 2x 2x 2x 2x 2x 1x 2x 2x 2x 1x 15x 15x | // Test Cleanup - Delete test data created by E2E tests
// ONLY available in non-production environments
import { and, desc, eq, inArray, isNull, like } from "drizzle-orm";
import { Hono } from "hono";
import { getDb } from "../../db";
import * as schema from "../../db/schema";
import { createDualCache, MARKETPLACE } from "../../lib/cache";
import { invalidateEntity } from "../../lib/cache-invalidation";
import { logger } from "../../lib/logger";
import { error, success } from "../../lib/response";
type Env = {
Bindings: CloudflareBindings;
};
const testCleanup = new Hono<Env>();
// Guard: block in production
testCleanup.use("*", async (c, next) => {
const env = c.env.ENVIRONMENT || "local";
if (env === "production") {
return error(
c,
"FORBIDDEN",
"Test cleanup is not available in production",
403,
);
}
await next();
});
// DELETE /test-cleanup?emailPrefix=e2e-
// Deletes users, accounts, sessions, roles, and invitations matching the email prefix
testCleanup.delete("/", async (c) => {
// Allowlist the prefix: it becomes a LIKE pattern, so `%`/`_` would turn
// "delete my test users" into "delete every user".
const emailPrefix = c.req.query("emailPrefix");
if (!emailPrefix || !/^[A-Za-z0-9.+@-]{8,}$/.test(emailPrefix)) {
return error(
c,
"BAD_REQUEST",
"emailPrefix query param required (min 8 chars, letters/digits/.+@- only; no _ or %)",
400,
);
}
const db = getDb(c.env.DB);
const emailPattern = `${emailPrefix}%`;
// Find users matching prefix
const users = await db
.select({ id: schema.users.id, email: schema.users.email })
.from(schema.users)
.where(like(schema.users.email, emailPattern))
.all();
const userIds = users.map((u) => u.id);
let deletedUsers = 0;
let deletedRoles = 0;
let deletedInvitations = 0;
let deletedSessions = 0;
let deletedAccounts = 0;
// Delete related data for each user
for (const userId of userIds) {
// Delete sessions
const sessionResult = await db
.delete(schema.sessions)
.where(eq(schema.sessions.userId, userId))
.run();
deletedSessions += sessionResult.meta.changes ?? 0;
// Delete accounts
const accountResult = await db
.delete(schema.accounts)
.where(eq(schema.accounts.userId, userId))
.run();
deletedAccounts += accountResult.meta.changes ?? 0;
// Delete user_tenant_roles
const roleResult = await db
.delete(schema.userTenantRoles)
.where(eq(schema.userTenantRoles.userId, userId))
.run();
deletedRoles += roleResult.meta.changes ?? 0;
// Delete user
const userResult = await db
.delete(schema.users)
.where(eq(schema.users.id, userId))
.run();
deletedUsers += userResult.meta.changes ?? 0;
}
// Delete invitations matching email prefix
const invitationResult = await db
.delete(schema.teamInvitations)
.where(like(schema.teamInvitations.email, emailPattern))
.run();
deletedInvitations += invitationResult.meta.changes ?? 0;
return success(c, {
message: "Test cleanup complete",
deleted: {
users: deletedUsers,
sessions: deletedSessions,
accounts: deletedAccounts,
roles: deletedRoles,
invitations: deletedInvitations,
},
});
});
// GET /test-cleanup/invitation-token?email=...
// Look up the most recent pending invitation token for an email (for E2E test link navigation)
testCleanup.get("/invitation-token", async (c) => {
const email = c.req.query("email");
if (!email) {
return error(c, "BAD_REQUEST", "email query param required", 400);
}
const db = getDb(c.env.DB);
const invitation = await db
.select({
token: schema.teamInvitations.token,
proId: schema.teamInvitations.proId,
role: schema.teamInvitations.role,
expiresAt: schema.teamInvitations.expiresAt,
})
.from(schema.teamInvitations)
.where(
and(
eq(schema.teamInvitations.email, email.toLowerCase().trim()),
isNull(schema.teamInvitations.acceptedAt),
),
)
.orderBy(desc(schema.teamInvitations.dateCreated))
.get();
if (!invitation) {
return error(
c,
"NOT_FOUND",
"No pending invitation found for this email",
404,
);
}
return success(c, { token: invitation.token });
});
const FIXTURE_BENGALURU_PRO_ID = "fixture-bengaluru-studio";
const FIXTURE_ZONE_ID = "fixture-blr-rehearsal";
const FIXTURE_ZONE_SLUG = "rehearsal";
const FIXTURE_STASH_KEY = "test:fixture:bangalore-published";
// POST /test-cleanup/city-fixture
// { "action": "quiesce" | "publish" | "restore" }
// Local/non-prod only. The full local seed already publishes designers in
// Bengaluru, so `quiesce` drafts them (ids stashed) and `restore` puts them
// back. `publish` adds the one rehearsal designer and an empty zone.
testCleanup.post("/city-fixture", async (c) => {
const body = (await c.req.json().catch(() => null)) as {
action?: string;
} | null;
const action = body?.action;
if (action !== "quiesce" && action !== "publish" && action !== "restore") {
return error(
c,
"BAD_REQUEST",
"action must be quiesce, publish, or restore",
400,
);
}
const db = getDb(c.env.DB);
const cache = createDualCache(c.env.KV_CACHE);
if (action === "quiesce") {
const stashed = (await cache.get<string[]>(FIXTURE_STASH_KEY)) ?? [];
const published = await db
.select({ id: schema.pros.id })
.from(schema.pros)
.where(
and(
eq(schema.pros.cityId, "bangalore"),
eq(schema.pros.status, "published"),
),
);
const ids = [
...new Set([
...stashed,
...published
.map((row) => row.id)
.filter((id) => id !== FIXTURE_BENGALURU_PRO_ID),
]),
];
await cache.put(FIXTURE_STASH_KEY, ids, { l1Ttl: 60, l2Ttl: 3600 });
await db
.update(schema.pros)
.set({ status: "draft" })
.where(
and(
eq(schema.pros.cityId, "bangalore"),
eq(schema.pros.status, "published"),
),
);
await db.delete(schema.zones).where(eq(schema.zones.id, FIXTURE_ZONE_ID));
}
if (action === "publish") {
await db
.insert(schema.pros)
.values({
id: FIXTURE_BENGALURU_PRO_ID,
status: "published",
businessName: "Fixture Bengaluru Studio",
slug: FIXTURE_BENGALURU_PRO_ID,
cityId: "bangalore",
description:
"Launch rehearsal designer for Bengaluru. Not a real studio.",
})
.onConflictDoUpdate({
target: schema.pros.id,
set: {
status: "published",
cityId: "bangalore",
businessName: "Fixture Bengaluru Studio",
},
});
// Test-only zone with no designers, so the empty-city CTA can be
// exercised. Not part of the product seed and removed on restore.
await db
.insert(schema.zones)
.values({
id: FIXTURE_ZONE_ID,
cityId: "bangalore",
name: "Rehearsal",
slug: FIXTURE_ZONE_SLUG,
})
.onConflictDoUpdate({
target: schema.zones.id,
set: {
cityId: "bangalore",
name: "Rehearsal",
slug: FIXTURE_ZONE_SLUG,
isActive: true,
},
});
}
// Restore reports what it put back. A stash that expired (1 h) or never
// existed leaves the quiesced designers in draft, so say so instead of a
// bare 200 that hides broken seed data.
let restoreReport: { restored: number; stashMissing: boolean } | undefined;
if (action === "restore") {
await db
.update(schema.pros)
.set({ status: "draft" })
.where(eq(schema.pros.id, FIXTURE_BENGALURU_PRO_ID));
await db.delete(schema.zones).where(eq(schema.zones.id, FIXTURE_ZONE_ID));
const stash = await cache.get<string[]>(FIXTURE_STASH_KEY);
const ids = stash ?? [];
// D1 caps bound parameters at 100 per statement.
for (let i = 0; i < ids.length; i += 90) {
await db
.update(schema.pros)
.set({ status: "published" })
.where(inArray(schema.pros.id, ids.slice(i, i + 90)));
}
await cache.delete(FIXTURE_STASH_KEY);
restoreReport = { restored: ids.length, stashMissing: stash == null };
if (stash == null) {
logger.warn(
"[test-cleanup] city-fixture restore found no stash; quiesced designers stay draft",
);
}
}
// Raw SQL does not go through the pro write path, which is what bumps the
// public list generation. Without this, a bangalore page cached while the
// city was quiesced keeps serving an empty designer list after publish.
await Promise.all([
invalidateEntity(cache, "pro", { id: FIXTURE_BENGALURU_PRO_ID }),
invalidateEntity(cache, "locality"),
cache.delete("seo:cities:index"),
cache.delete("seo:city:bengaluru"),
cache.delete("seo:city:bangalore"),
cache.delete(`seo:zone:bangalore:${FIXTURE_ZONE_SLUG}`),
cache.delete(`seo:zone:bengaluru:${FIXTURE_ZONE_SLUG}`),
cache.delete(MARKETPLACE.taxonomyZones("bangalore")),
]);
return success(c, {
id: FIXTURE_BENGALURU_PRO_ID,
action,
cityId: "bangalore",
...restoreReport,
});
});
export default testCleanup;
|