All files / routes/admin pros-imports.routes.ts

100% Statements 31/31
100% Branches 26/26
100% Functions 2/2
100% Lines 31/31

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                                                                    1x   1x 20x 20x 20x 20x 20x   20x 20x 1x     19x             1x 19x 2x   17x 1x                       16x 16x         16x                                   15x         2x               13x 20x       13x   13x                     12x           12x   12x         7x       1x             6x          
// Admin enqueue endpoint for pro imports.
//
// `POST /admin/pros/:proId/imports` — body `{ sourceUrl, consentAt? }`.
// Validates pro exists, normalizes URL, hashes idempotency key, inserts
// `pro_imports` row, sends an `IMPORT_QUEUE` message.
//
// Trust model: this router is mounted *inside* /admin and inherits
// `requirePlatformAdmin` from `admin/index.ts`. No per-route guard needed.
 
import { and, desc, eq } from "drizzle-orm";
import { Hono } from "hono";
import type { Dal } from "../../dal";
import type { getDb } from "../../db";
import * as schema from "../../db/schema";
import type { ImportQueueMessage } from "../../import-agent";
import { ConflictError, NotFoundError, ValidationError } from "../../lib/errors";
import {
	hashIdempotencyKey,
	normalizeUrl,
} from "../../lib/imports/url-normalize";
import { handleError, success } from "../../lib/response";
import type { Services } from "../../services";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		db: ReturnType<typeof getDb>;
	};
};
 
const prosImportsRoutes = new Hono<Env>();
 
prosImportsRoutes.post("/:proId/imports", async (c) => {
	try {
		const proId = c.req.param("proId");
		const dal = c.get("dal");
		const db = c.get("db");
		const user = c.get("user");
 
		const pro = await dal.pros.findById(proId);
		if (!pro) {
			throw new NotFoundError("Pro");
		}
 
		const body = await c.req
			.json<{
				sourceUrl?: string;
				consentAt?: number;
				/** When true, bypass idempotency by salting the key with a timestamp. */
				force?: boolean;
			}>()
			.catch(() => null);
		if (!body || !body.sourceUrl) {
			throw new ValidationError("sourceUrl is required");
		}
		if (!c.env.IMPORT_QUEUE) {
			return c.json(
				{
					success: false,
					error: {
						code: "SERVER_MISCONFIGURED",
						message: "IMPORT_QUEUE binding is not available",
					},
				},
				500,
			);
		}
 
		const normalized = normalizeUrl(body.sourceUrl);
		const nowMs = Date.now();
 
		// Look up the latest import for this (pro, URL). Match on sourceUrl, not
		// the idempotency key — forced re-scrapes carry a salted key but must
		// still count as "in progress" here.
		const [existing] = await db
			.select({
				id: schema.proImports.id,
				status: schema.proImports.status,
			})
			.from(schema.proImports)
			.where(
				and(
					eq(schema.proImports.proId, proId),
					eq(schema.proImports.sourceUrl, normalized),
				),
			)
			.orderBy(desc(schema.proImports.createdAt))
			.limit(1);
 
		// A prior import that's still in-flight blocks a fresh submit (unless the
		// caller explicitly forces a concurrent re-scrape). Terminal imports
		// (completed/failed/cancelled) auto re-scrape via a salted key below.
		if (
			existing &&
			(existing.status === "queued" || existing.status === "running") &&
			!body.force
		) {
			throw new ConflictError(
				`An import for this URL is already ${existing.status}. Open import ${existing.id} to monitor it.`,
			);
		}
 
		// Salt the idempotency key whenever a prior row exists (terminal
		// re-scrape) or the caller forces it, so the unique constraint accepts a
		// new row for the same (proId, URL). First-time imports use the base key.
		const shouldSalt = !!body.force || existing != null;
		const idempotencyKey = await hashIdempotencyKey(
			proId,
			shouldSalt ? `${normalized}|force=${nowMs}` : normalized,
		);
		const importId = `imp_${crypto.randomUUID()}`;
 
		await db.insert(schema.proImports).values({
			id: importId,
			proId,
			sourceUrl: normalized,
			sourceType: "website",
			status: "queued",
			consentAt: body.consentAt ?? nowMs,
			idempotencyKey,
			submittedBy: user?.id ?? null,
		});
 
		const queueMessage: ImportQueueMessage = {
			importId,
			proId,
			sourceUrl: normalized,
			timestamp: nowMs,
		};
		await c.env.IMPORT_QUEUE.send(queueMessage);
 
		return success(c, { importId, status: "queued" });
	} catch (err) {
		// Race fallback: a concurrent double-submit can slip past the pre-check
		// and collide on the unique idempotency key. Map that to a clear 409
		// instead of the opaque generic 500 from handleError.
		if (
			err instanceof Error &&
			err.message.includes("UNIQUE constraint failed")
		) {
			return handleError(
				c,
				new ConflictError(
					"An import for this URL was just submitted. Please try again in a moment.",
				),
			);
		}
		return handleError(c, err);
	}
});
 
export default prosImportsRoutes;