All files / routes/internal/website-build build-jobs.routes.ts

79.04% Statements 83/105
97.72% Branches 43/44
100% Functions 7/7
79.8% Lines 83/104

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                                    2x     2x 15x 15x     15x 14x 4x             4x           4x 3x                 14x   14x 8x       6x   6x   2x       4x     4x 2x       2x     2x         1x         2x                 2x       19x 19x 19x 19x   19x 19x 2x             17x 6x 3x         3x             3x 3x 2x     3x                   3x   3x 3x                                                                                           11x 7x             7x 7x 2x             5x               5x 4x   4x 4x                                   4x                                                                     4x         4x             14x   5x           2x 4x 4x 4x   4x 4x 2x       2x           2x   2x         2x 4x 4x 4x   4x 4x 2x       2x           2x   2x         2x 4x 4x   4x 3x         1x          
// Internal Build Job Management Routes
import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
import type { Dal } from "../../../dal";
import type { Services } from "../../../services";
import { success, handleError } from "../../../lib/response";
import { NotFoundError, BadRequestError } from "../../../lib/errors";
import { logger } from "../../../lib/logger";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		dal: Dal;
		services: Services;
	};
};
 
const buildJobRoutes = new Hono<Env>();
 
// Get next pending build job (for worker polling)
buildJobRoutes.get("/next-job", async (c) => {
	try {
		const dal = c.get("dal");
 
		// First check for stale jobs (building for too long — 2x expected build time)
		const staleJob = await dal.websiteBuildJobs.findStaleJob(10); // 10 min = 2x of ~5 min expected
		if (staleJob) {
			await dal.websiteBuildJobs.logBuildEvent(
				staleJob.id,
				"timeout",
				"Build timed out after 10 minutes",
			);
 
			// failBuildJob handles retry logic (retryCount < maxRetries)
			const result = await dal.websiteBuildJobs.failBuildJob(
				staleJob.id,
				"Build timed out",
				staleJob.buildLogs ?? undefined,
			);
 
			if (result && result.status === "pending") {
				await dal.websiteBuildJobs.logBuildEvent(
					staleJob.id,
					"retry",
					`Retrying after timeout (attempt ${result.retryCount}/${result.maxRetries})`,
				);
			}
		}
 
		// Get next pending job
		const job = await dal.websiteBuildJobs.findNextPendingJob();
 
		if (!job) {
			return success(c, { job: null });
		}
 
		// Claim the job (atomically update status to building)
		const claimedJob = await dal.websiteBuildJobs.startBuildJob(job.id);
 
		if (!claimedJob) {
			// Job was claimed by another worker
			return success(c, { job: null });
		}
 
		// Get website info
		const website = await dal.proWebsites.findById(
			claimedJob.proWebsiteId,
		);
		if (!website) {
			await dal.websiteBuildJobs.failBuildJob(
				claimedJob.id,
				"Website not found",
			);
			return success(c, { job: null });
		}
 
		return success(c, {
			job: claimedJob,
			website,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Update job status schema
const updateStatusSchema = z.object({
	status: z.enum(["building", "deploying", "deployed", "failed"]),
	buildLogs: z.string().optional(),
	errorMessage: z.string().optional(),
	deploymentUrl: z.string().url().optional(),
	deploymentId: z.string().optional(),
});
 
// Update build job status
buildJobRoutes.post(
	"/:jobId/status",
	zValidator("json", updateStatusSchema),
	async (c) => {
		try {
			const dal = c.get("dal");
			const jobId = parseInt(c.req.param("jobId"), 10);
			const body = c.req.valid("json");
 
			const job = await dal.websiteBuildJobs.findBuildJobById(jobId);
			if (!job) {
				throw new NotFoundError("Build job not found");
			}
 
			let updatedJob:
				| Awaited<ReturnType<typeof dal.websiteBuildJobs.completeBuildJob>>
				| undefined;
 
			if (body.status === "deployed") {
				if (!body.deploymentUrl || !body.deploymentId) {
					throw new BadRequestError(
						"deploymentUrl and deploymentId required for deployed status",
					);
				}
 
				updatedJob = await dal.websiteBuildJobs.completeBuildJob(
					jobId,
					body.deploymentUrl,
					body.deploymentId,
				);
 
				// Also update website status
				const website = await dal.proWebsites.findById(job.proWebsiteId);
				if (website) {
					await dal.proWebsites.markPublished(website.id, job.version);
				}
 
				await dal.websiteBuildJobs.logBuildEvent(
					jobId,
					"deployed",
					`Deployed successfully`,
					{
						deploymentUrl: body.deploymentUrl,
						deploymentId: body.deploymentId,
					},
				);
 
				c.executionCtx.waitUntil(
					(async () => {
						try {
							const { CommunicationGateway } = await import(
								"../../../lib/communication/gateway"
							);
							const { WebsiteBuildResultHandler } = await import(
								"../../../lib/communication/handlers/website-build-result.handler"
							);
							const gateway = new CommunicationGateway(dal, c.env);
							const handler = new WebsiteBuildResultHandler(
								gateway,
								dal,
							);
							const proId = website?.proId;
							/* v8 ignore start -- defensive guard: proId always exists */
							if (!proId) return;
							/* v8 ignore stop */
							const pro = await dal.pros.findById(proId);
							await handler.handle({
								proId,
								success: true,
								websiteUrl: body.deploymentUrl,
								/* v8 ignore start -- V8 artifact: ?? fallback */
								businessName: pro?.businessName ?? "",
								/* v8 ignore stop */
							});
							try {
								await c.get("services").notification.notify({
									proId,
									eventType: "website_build_success",
									title: "Your website is live!",
									body: "Your professional website has been published successfully",
									data: { url: "/website" },
								});
							} catch (notifErr) {
								logger.error(
									"[BUILD] Failed to send push notification for success:",
									notifErr,
								);
							}
						} catch (err) {
							logger.error(
								"[BUILD] Failed to send build success notification:",
								err,
							);
						}
					})(),
				);
			} else if (body.status === "failed") {
				updatedJob = await dal.websiteBuildJobs.failBuildJob(
					jobId,
					body.errorMessage ?? "Build failed",
					body.buildLogs,
				);
 
				// failBuildJob may retry (set status back to pending) or mark as failed
				const shouldRetry = updatedJob && updatedJob.status === "pending";
				if (shouldRetry) {
					await dal.websiteBuildJobs.logBuildEvent(
						jobId,
						"retry",
						`Retrying (attempt ${updatedJob?.retryCount}/${updatedJob?.maxRetries})`,
						{ errorMessage: body.errorMessage },
					);
				} else {
					await dal.websiteBuildJobs.logBuildEvent(
						jobId,
						"failed",
						body.errorMessage ?? "Build failed",
						{ retryCount: updatedJob?.retryCount },
					);
 
					// Only notify on terminal failure (not retried)
					if (updatedJob && updatedJob.status === "failed") {
						c.executionCtx.waitUntil(
							(async () => {
								try {
									const { CommunicationGateway } = await import(
										"../../../lib/communication/gateway"
									);
									const { WebsiteBuildResultHandler } = await import(
										"../../../lib/communication/handlers/website-build-result.handler"
									);
									const gateway = new CommunicationGateway(
										dal,
										c.env,
									);
									const handler = new WebsiteBuildResultHandler(
										gateway,
										dal,
									);
									const website = await dal.proWebsites.findById(
										job.proWebsiteId,
									);
									const proId = website?.proId;
									Iif (!proId) return;
									const pro = await dal.pros.findById(proId);
									await handler.handle({
										proId,
										success: false,
										errorMessage: body.errorMessage,
										/* v8 ignore start -- V8 artifact: ?? fallback */
										businessName: pro?.businessName ?? "",
										/* v8 ignore stop */
									});
									try {
										await c.get("services").notification.notify({
											proId,
											eventType: "website_build_failed",
											title: "Website build failed",
											body: "There was an issue publishing your website. Please try again.",
											data: { url: "/website" },
										});
									} catch (notifErr) {
										logger.error(
											"[BUILD] Failed to send push notification for failure:",
											notifErr,
										);
									}
								} catch (err) {
									logger.error(
										"[BUILD] Failed to send build failure notification:",
										err,
									);
								}
							})(),
						);
					}
				}
			} else {
				updatedJob = await dal.websiteBuildJobs.updateBuildJob(jobId, {
					status: body.status,
					buildLogs: body.buildLogs,
				});
 
				await dal.websiteBuildJobs.logBuildEvent(
					jobId,
					body.status,
					`Status changed to ${body.status}`,
				);
			}
 
			return success(c, updatedJob);
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
// Reset a job to pending status (for testing/retry)
buildJobRoutes.post("/:jobId/reset", async (c) => {
	try {
		const dal = c.get("dal");
		const jobId = parseInt(c.req.param("jobId"), 10);
 
		const job = await dal.websiteBuildJobs.findBuildJobById(jobId);
		if (!job) {
			throw new NotFoundError("Build job not found");
		}
 
		// Reset job to pending
		const updatedJob = await dal.websiteBuildJobs.updateBuildJob(jobId, {
			status: "pending",
			buildLogs: null,
			errorMessage: null,
		});
 
		return success(c, updatedJob);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Cancel a job (for stuck/building jobs - testing only)
buildJobRoutes.post("/:jobId/cancel", async (c) => {
	try {
		const dal = c.get("dal");
		const jobId = parseInt(c.req.param("jobId"), 10);
 
		const job = await dal.websiteBuildJobs.findBuildJobById(jobId);
		if (!job) {
			throw new NotFoundError("Build job not found");
		}
 
		// Cancel the job (works for any status including "building")
		const updatedJob = await dal.websiteBuildJobs.updateBuildJob(jobId, {
			status: "cancelled",
			completedAt: new Date(),
			errorMessage: "Manually cancelled",
		});
 
		return success(c, updatedJob);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Cancel all building jobs (for testing/cleanup of stuck jobs)
buildJobRoutes.post("/cancel-all-building", async (c) => {
	try {
		const dal = c.get("dal");
		const cancelledCount =
			await dal.websiteBuildJobs.cancelAllBuildingJobs();
		return success(c, {
			message: `Cancelled ${cancelledCount} building job(s)`,
			count: cancelledCount,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default buildJobRoutes;