All files / routes/marketplace homepage.ts

88% Statements 110/125
82.66% Branches 62/75
88.88% Functions 16/18
87.38% Lines 97/111

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 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453                                                      1x                               2x                             1x 38x 38x   38x 38x 38x     38x 38x   34x               5x 2x   3x       33x 4x               33x   3x                   36x   35x 3x                             32x                                                                                                 31x 31x 30x         30x 30x 11x 3x 3x               31x 36x 1x       31x 31x 30x           30x 30x 8x 2x 2x           31x                     31x       31x   31x 31x 13x 13x   13x     13x 13x 10x     13x             13x 24x 24x 21x 24x       24x       13x 13x 13x 9x   13x 10x                 13x 10x 10x 8x 8x 7x 15x       1x   1x 1x           13x 5x 1x 1x 1x 3x       1x           13x                                       31x 31x   31x                                           31x 31x 31x 31x 3x                         31x                                                                                                 2x 2x     1x       1x           1x                          
// Consolidated Homepage Endpoint - Returns all homepage data in one call
 
import { eq, sql } from "drizzle-orm";
import { Hono } from "hono";
import { createDal, type Dal } from "../../dal";
import { getDb } from "../../db";
import * as schema from "../../db/schema";
import {
	CACHE_KEYS,
	CACHE_TTL,
	createDualCache,
	type DualCache,
} from "../../lib/cache";
import { handleError, success } from "../../lib/response";
import type { ContextVariables } from "../../middleware";
import { createServices, type Services } from "../../services";
import { enrichProjectsWithTaxonomy } from "./project-enrichment";
import { resolvePortfolioCoversForPros } from "./pros/taxonomy-enrichment";
import { buildRoomCategories } from "./room-categories.shared";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: ContextVariables;
};
 
type Db = ReturnType<typeof getDb>;
 
const homepage = new Hono<Env>();
 
// Sentinel thrown by the cache fetcher when there are no published pros. We
// throw rather than return the empty payload so `cache.getOrSet` never reaches
// its `put` — the empty state is computed but NEVER persisted. Previously the
// empty payload was returned normally and cached to L1 (60s) + L2 KV (300s),
// so a single transient zero-result (D1 blip, mid-deploy, or a query error
// surfacing as an empty array) pinned a "no pros/projects" homepage for up to
// 5 min even after pros were present. Root cause of the empty-homepage
// incident. Cache HITS still short-circuit before the fetcher runs, so the hot
// path keeps its zero extra DB queries.
class EmptyHomepageError extends Error {}
 
// Factory (not a shared constant) so each empty response gets its own fresh
// arrays — a shared object with nested arrays could be mutated by an accidental
// push in a caller or test and leak across requests.
const createEmptyHomepage = () => ({
	featuredProject: null,
	featuredMedia: [] as Array<{ storageKey: string; roomName: string }>,
	latestProjects: [] as Awaited<ReturnType<typeof enrichProjectsWithTaxonomy>>,
	featuredPros: [] as Array<Record<string, unknown>>,
	roomCategories: [] as Array<{
		value: string;
		label: string;
		coverImage: string | null;
		projectCount: number;
	}>,
	stats: { prosCount: 0, projectsCount: 0 },
});
 
// GET /api/marketplace/homepage — all homepage data in one call
homepage.get("/", async (c) => {
	try {
		const cache = c.get("cache");
 
		const services = c.get("services");
		const dal = c.get("dal");
		const db = c.get("db");
 
		let data: Awaited<ReturnType<typeof buildHomepageData>>;
		try {
			data = await cache.getOrSet(
				CACHE_KEYS.MARKETPLACE_HOMEPAGE,
				() => buildHomepageData(services, dal, db),
				{
					l1Ttl: CACHE_TTL.MARKETPLACE_HOMEPAGE_L1,
					l2Ttl: CACHE_TTL.MARKETPLACE_HOMEPAGE_L2,
				},
			);
		} catch (err) {
			// No published pros — return the empty homepage WITHOUT caching it.
			if (err instanceof EmptyHomepageError) {
				return success(c, createEmptyHomepage());
			}
			throw err;
		}
 
		// Pre-warm room-categories cache from homepage data (background, non-blocking)
		if (data.roomCategories?.length > 0) {
			c.executionCtx.waitUntil(
				cache.put(CACHE_KEYS.MARKETPLACE_ROOM_CATEGORIES, data.roomCategories, {
					l1Ttl: CACHE_TTL.MARKETPLACE_ROOM_CATEGORIES_L1,
					l2Ttl: CACHE_TTL.MARKETPLACE_ROOM_CATEGORIES_L2,
				}),
			);
		}
 
		return success(c, data);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Builds the populated homepage payload. Throws EmptyHomepageError when no
// pros are published so the caller can return an uncached empty response.
// Takes explicit deps (not a Hono Context) so the scheduled warmer can call it
// outside a request.
async function buildHomepageData(services: Services, dal: Dal, db: Db) {
	// Step 1: Get published pro IDs (needed for all queries)
	const publishedProIds = await dal.pros.findIdsByStatus("published");
 
	if (publishedProIds.length === 0) {
		throw new EmptyHomepageError();
	}
 
	// Step 2: Run all independent queries in parallel.
	// Curation flow:
	//   - heroResult           — admin-pinned singleton; null fallback below.
	//   - latestProjectsResult — prefer isFeatured=true first; backfilled
	//     below if fewer than 12 featured projects exist.
	const [
		heroResult,
		latestProjectsResult,
		featuredProsResult,
		prosCountResult,
		projectsCountResult,
		allRoomTypes,
	] = await Promise.all([
		// Admin-pinned hero (singleton). Falls back to algorithm if empty.
		services.project.list(
			{
				status: "published",
				requirePublishedPro: true,
				isHero: true,
			},
			1,
			1,
		),
		// Featured projects first; backfill with latest below if < 12.
		// Use requirePublishedPro instead of passing publishedProIds as
		// a bind list so this filter stays safe as the pro roster grows
		// past D1's 100-parameter limit (see error-reports/2026-04-20).
		services.project.list(
			{
				status: "published",
				requirePublishedPro: true,
				isFeatured: true,
			},
			1,
			12,
		),
		// Featured pros: 6 published pros, preferring isFeatured=true
		services.pro.list(
			{
				status: "published",
				isFeatured: true,
			},
			1,
			6,
		),
		// Stats: total published pros
		db
			.select({ count: sql<number>`count(*)` })
			.from(schema.pros)
			.where(eq(schema.pros.status, "published")),
		// Stats: total published projects
		db
			.select({ count: sql<number>`count(*)` })
			.from(schema.projects)
			.where(eq(schema.projects.status, "published")),
		// All room types for categories
		db.select().from(schema.roomTypes),
	]);
 
	// If we didn't get 12 featured projects, backfill with non-featured
	// (latest-by-date). Mirrors the featured-pros backfill below.
	const projectsData = latestProjectsResult.projects;
	if (projectsData.length < 12) {
		const backfill = await services.project.list(
			{ status: "published", requirePublishedPro: true },
			1,
			12,
		);
		const seenIds = new Set(projectsData.map((p) => p.id));
		for (const project of backfill.projects) {
			if (!seenIds.has(project.id) && projectsData.length < 12) {
				projectsData.push(project);
				seenIds.add(project.id);
			}
		}
	}
 
	// Admin hero override (singleton). Ensure the hero row is enriched
	// + present in the rooms/media fetch even when it would otherwise
	// fall outside the latest-12 window.
	const adminHero = heroResult.projects[0] ?? null;
	if (adminHero && !projectsData.some((p) => p.id === adminHero.id)) {
		projectsData.unshift(adminHero);
	}
 
	// If we didn't get 6 featured pros, backfill with non-featured
	const prosData = featuredProsResult.pros;
	if (prosData.length < 6) {
		const backfillResult = await services.pro.list(
			{ status: "published" },
			1,
			6,
		);
		// Merge: featured first, then non-featured, deduplicated
		const seenIds = new Set(prosData.map((p) => p.id));
		for (const pro of backfillResult.pros) {
			if (!seenIds.has(pro.id) && prosData.length < 6) {
				prosData.push(pro);
				seenIds.add(pro.id);
			}
		}
	}
 
	// Step 3: Enrich projects with taxonomy data (includes pro info, covers)
	const enrichedProjects = await enrichProjectsWithTaxonomy(
		db,
		services,
		dal,
		projectsData,
	);
 
	// Step 4: Find featured project.
	// If admin pinned a hero, prefer it (no minimum-media gate — the
	// admin chose explicitly). Otherwise fall back to the algorithm:
	// first project with 3+ media items, then any project with media.
	let featuredProject = null;
	let featuredMedia: Array<{
		storageKey: string;
		roomName: string;
	}> = [];
 
	const projectIds = projectsData.map((p) => p.id);
	if (projectIds.length > 0) {
		const allRooms = await dal.rooms.findByProjectIds(projectIds);
		const allRoomIds = allRooms.map((r) => r.id);
		const allMedia =
			allRoomIds.length > 0 ? await dal.media.findByRoomIds(allRoomIds) : [];
 
		// Group media by project (via rooms)
		const roomToProject = new Map<number, string>();
		for (const room of allRooms) {
			roomToProject.set(room.id, room.projectId);
		}
 
		const mediaByProject = new Map<
			string,
			Array<{
				storageKey: string;
				roomId: number;
			}>
		>();
		for (const m of allMedia) {
			const projId = roomToProject.get(m.roomId);
			if (!projId) continue;
			const existing = mediaByProject.get(projId) ?? [];
			existing.push({
				storageKey: m.storageKey,
				roomId: m.roomId,
			});
			mediaByProject.set(projId, existing);
		}
 
		// Build room name lookup
		const roomNameMap = new Map<number, string>();
		const roomTypeMap = new Map<string, string>();
		for (const rt of allRoomTypes) {
			roomTypeMap.set(rt.code, rt.displayName);
		}
		for (const room of allRooms) {
			roomNameMap.set(
				room.id,
				room.name ?? roomTypeMap.get(room.roomType) ?? room.roomType,
			);
		}
 
		// Admin hero override: prefer room media; fall back to
		// project.coverImage when no rooms exist (e.g. seed data,
		// freshly-created projects). Admin intent always wins.
		if (adminHero) {
			const enrichedHero = enrichedProjects.find((p) => p.id === adminHero.id);
			if (enrichedHero) {
				const heroMedia = mediaByProject.get(adminHero.id);
				if (heroMedia && heroMedia.length > 0) {
					featuredProject = enrichedHero;
					featuredMedia = heroMedia.map((m) => ({
						storageKey: m.storageKey,
						roomName: roomNameMap.get(m.roomId) ?? "",
					}));
				E} else if (adminHero.coverImage) {
					// No room media — use the project cover image directly.
					featuredProject = enrichedHero;
					featuredMedia = [{ storageKey: adminHero.coverImage, roomName: "" }];
				}
			}
		}
 
		// Algorithm fallback: first project with 3+ media items.
		if (!featuredProject) {
			for (const project of enrichedProjects) {
				const projectMedia = mediaByProject.get(project.id);
				Eif (projectMedia && projectMedia.length >= 3) {
					featuredProject = project;
					featuredMedia = projectMedia.map((m) => ({
						storageKey: m.storageKey,
						roomName: roomNameMap.get(m.roomId) ?? "",
					}));
					break;
				}
			}
		}
 
		// Fallback: use first project with any media
		Iif (!featuredProject && enrichedProjects.length > 0) {
			for (const project of enrichedProjects) {
				const projectMedia = mediaByProject.get(project.id);
				if (projectMedia && projectMedia.length > 0) {
					featuredProject = project;
					featuredMedia = projectMedia.map((m) => ({
						storageKey: m.storageKey,
						roomName: roomNameMap.get(m.roomId) ?? "",
					}));
					break;
				}
			}
		}
	}
 
	// Step 5: Build featured pros with portfolio covers.
	// Uses the same rooms→media cascade as `/api/marketplace/pros`
	// so pros whose photos live only in rooms/media (NULL
	// `projects.coverImage`) still render a hero instead of the
	// "No portfolio yet" placeholder. See PR #740.
	const proIds = prosData.map((p) => p.id);
	const coversByProId = await resolvePortfolioCoversForPros(db, dal, proIds);
 
	const featuredPros = prosData.map((pro) => ({
		id: pro.id,
		businessName: pro.businessName,
		slug: pro.slug,
		profileImage: pro.profileImage,
		logoUrl: pro.logoUrl,
		isFeatured: pro.isFeatured,
		portfolioCovers: coversByProId.get(pro.id) ?? [],
	}));
 
	// Step 6: Build room categories with cover images and project counts.
	// Delegates to the shared cheap builder (sample-room + media pick, no
	// correlated per-room-type subqueries) — the same code path the standalone
	// `/api/marketplace/room-categories` endpoint uses. The previous inline
	// 3-tier correlated COALESCE was O(room_types × media_rows) and timed out at
	// prod scale (the homepage 503 incident). Fault-isolated: a slow/failed
	// categories build degrades to [] instead of sinking the whole homepage.
	let roomCategories: Array<{
		value: string;
		label: string;
		coverImage: string | null;
		projectCount: number;
	}> = [];
	try {
		const built = await buildRoomCategories(db, dal);
		roomCategories = built.map(
			({ value, label, coverImage, projectCount }) => ({
				value,
				label,
				coverImage,
				projectCount,
			}),
		);
	} catch {
		// Degrade gracefully — room categories are non-critical, so a failed
		// build leaves them empty while the rest of the homepage still renders.
		roomCategories = [];
	}
 
	return {
		featuredProject,
		featuredMedia,
		latestProjects: enrichedProjects,
		featuredPros,
		roomCategories,
		stats: {
			prosCount: prosCountResult[0]?.count ?? 0,
			projectsCount: projectsCountResult[0]?.count ?? 0,
		},
	};
}
 
/**
 * Keep the homepage cache hot from the scheduled (cron) worker.
 *
 * The consolidated homepage payload is cheap-ish but still ~10 D1 reads
 * (enrichment + rooms/media + pro covers). On a *cold* cache miss — every L2 TTL
 * expiry, or under D1 contention from the faceted-listing crawl — a user-facing
 * rebuild can exceed the marketplace SSR's 4s fetch timeout and 503 the homepage
 * (incident 2026-06-22). The cron has no 4s budget, so it can rebuild slowly and
 * write KV; user requests then always hit the warm L2 entry (~0ms D1).
 *
 * Pairs with an L2 TTL longer than the cron interval so the entry never lapses
 * between warms. No-ops gracefully on an empty platform (no published pros) so
 * we never pin an empty homepage.
 */
export async function warmHomepageCache(
	env: CloudflareBindings,
): Promise<void> {
	const db = getDb(env.DB);
	const cache = createDualCache(env.KV_CACHE);
	const dal = createDal(db, cache, env);
	const services = createServices(dal, env);
	await warmHomepageInto(cache, services, dal, db);
}
 
/**
 * Testable core of the warmer: build the homepage payload and write it (plus the
 * room-categories entry) to the given cache. No-ops on an empty platform so an
 * empty homepage is never pinned.
 */
export async function warmHomepageInto(
	cache: DualCache,
	services: Services,
	dal: Dal,
	db: Db,
): Promise<void> {
	let data: Awaited<ReturnType<typeof buildHomepageData>>;
	try {
		data = await buildHomepageData(services, dal, db);
	} catch (err) {
		// Empty platform — don't cache an empty homepage (mirrors the route).
		Eif (err instanceof EmptyHomepageError) return;
		throw err;
	}
 
	await cache.put(CACHE_KEYS.MARKETPLACE_HOMEPAGE, data, {
		l1Ttl: CACHE_TTL.MARKETPLACE_HOMEPAGE_L1,
		l2Ttl: CACHE_TTL.MARKETPLACE_HOMEPAGE_L2,
	});
 
	// Also refresh the room-categories cache the homepage pre-warms on the hot path.
	Iif (data.roomCategories.length > 0) {
		await cache.put(
			CACHE_KEYS.MARKETPLACE_ROOM_CATEGORIES,
			data.roomCategories,
			{
				l1Ttl: CACHE_TTL.MARKETPLACE_ROOM_CATEGORIES_L1,
				l2Ttl: CACHE_TTL.MARKETPLACE_ROOM_CATEGORIES_L2,
			},
		);
	}
}
 
export default homepage;