All files / dal website-build-jobs.dal.ts

100% Statements 43/43
100% Branches 24/24
100% Functions 17/17
100% Lines 42/42

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                                  72x                 5x   5x 2x         5x 2x               5x             5x 3x     2x       5x         5x           2x           2x         2x                     2x             3x 3x                     3x           2x       2x             1x               1x         2x                                 2x                 1x                     1x                 3x 3x   2x   2x                         2x         2x                                     2x         2x                                 2x         2x                   2x         3x       3x                     3x                 2x              
// Data Access Layer for Website Build Jobs and Build Events
import { eq, desc, and, or, sql } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../db/schema";
import type {
	WebsiteBuildJob,
	NewWebsiteBuildJob,
	WebsiteBuildEvent,
} from "../db/schema";
 
export type BuildJobFilters = {
	proWebsiteId?: number;
	status?: string;
	statusIn?: string[];
};
 
export class WebsiteBuildJobsDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	// ==================== Build Jobs ====================
 
	async findBuildJobs(
		filters: BuildJobFilters = {},
		offset = 0,
		limit = 20,
	): Promise<WebsiteBuildJob[]> {
		const conditions = [];
 
		if (filters.proWebsiteId) {
			conditions.push(
				eq(schema.websiteBuildJobs.proWebsiteId, filters.proWebsiteId),
			);
		}
 
		if (filters.status) {
			conditions.push(
				eq(
					schema.websiteBuildJobs.status,
					filters.status as WebsiteBuildJob["status"],
				),
			);
		}
 
		const query = this.db
			.select()
			.from(schema.websiteBuildJobs)
			.orderBy(desc(schema.websiteBuildJobs.dateCreated))
			.limit(limit)
			.offset(offset);
 
		if (conditions.length > 0) {
			return query.where(and(...conditions));
		}
 
		return query;
	}
 
	async findBuildJobById(id: number): Promise<WebsiteBuildJob | undefined> {
		const result = await this.db
			.select()
			.from(schema.websiteBuildJobs)
			.where(eq(schema.websiteBuildJobs.id, id))
			.limit(1);
		return result[0];
	}
 
	async findLatestBuildJob(
		proWebsiteId: number,
	): Promise<WebsiteBuildJob | undefined> {
		const result = await this.db
			.select()
			.from(schema.websiteBuildJobs)
			.where(eq(schema.websiteBuildJobs.proWebsiteId, proWebsiteId))
			.orderBy(desc(schema.websiteBuildJobs.dateCreated))
			.limit(1);
		return result[0];
	}
 
	// Find next pending/queued job for build worker
	async findNextPendingJob(): Promise<WebsiteBuildJob | undefined> {
		const result = await this.db
			.select()
			.from(schema.websiteBuildJobs)
			.where(
				or(
					eq(schema.websiteBuildJobs.status, "pending"),
					eq(schema.websiteBuildJobs.status, "queued"),
				),
			)
			.orderBy(schema.websiteBuildJobs.dateCreated)
			.limit(1);
		return result[0];
	}
 
	// Find job that's been building for too long (stale)
	async findStaleJob(
		timeoutMinutes = 10,
	): Promise<WebsiteBuildJob | undefined> {
		const timeoutThreshold = new Date(Date.now() - timeoutMinutes * 60 * 1000);
		const result = await this.db
			.select()
			.from(schema.websiteBuildJobs)
			.where(
				and(
					eq(schema.websiteBuildJobs.status, "building"),
					sql`${schema.websiteBuildJobs.startedAt} < ${Math.floor(timeoutThreshold.getTime() / 1000)}`,
				),
			)
			.orderBy(schema.websiteBuildJobs.dateCreated)
			.limit(1);
		return result[0];
	}
 
	async createBuildJob(
		data: NewWebsiteBuildJob,
	): Promise<WebsiteBuildJob | undefined> {
		const result = await this.db
			.insert(schema.websiteBuildJobs)
			.values(data)
			.returning();
		return result[0];
	}
 
	async updateBuildJob(
		id: number,
		data: Partial<NewWebsiteBuildJob>,
	): Promise<WebsiteBuildJob | undefined> {
		const result = await this.db
			.update(schema.websiteBuildJobs)
			.set({
				...data,
				dateUpdated: new Date(),
			})
			.where(eq(schema.websiteBuildJobs.id, id))
			.returning();
		return result[0];
	}
 
	// Start a build job (claim it)
	async startBuildJob(id: number): Promise<WebsiteBuildJob | undefined> {
		const result = await this.db
			.update(schema.websiteBuildJobs)
			.set({
				status: "building",
				startedAt: new Date(),
				dateUpdated: new Date(),
			})
			.where(
				and(
					eq(schema.websiteBuildJobs.id, id),
					or(
						eq(schema.websiteBuildJobs.status, "pending"),
						eq(schema.websiteBuildJobs.status, "queued"),
					),
				),
			)
			.returning();
		return result[0];
	}
 
	// Complete a build job
	async completeBuildJob(
		id: number,
		deploymentUrl: string,
		deploymentId: string,
	): Promise<WebsiteBuildJob | undefined> {
		const result = await this.db
			.update(schema.websiteBuildJobs)
			.set({
				status: "deployed",
				completedAt: new Date(),
				deploymentUrl,
				deploymentId,
				dateUpdated: new Date(),
			})
			.where(eq(schema.websiteBuildJobs.id, id))
			.returning();
		return result[0];
	}
 
	// Fail a build job
	async failBuildJob(
		id: number,
		errorMessage: string,
		buildLogs?: string,
	): Promise<WebsiteBuildJob | undefined> {
		const job = await this.findBuildJobById(id);
		if (!job) return undefined;
 
		const shouldRetry = job.retryCount < job.maxRetries;
 
		const result = await this.db
			.update(schema.websiteBuildJobs)
			.set({
				status: shouldRetry ? "pending" : "failed",
				completedAt: shouldRetry ? null : new Date(),
				errorMessage,
				buildLogs,
				retryCount: job.retryCount + 1,
				startedAt: shouldRetry ? null : job.startedAt,
				dateUpdated: new Date(),
			})
			.where(eq(schema.websiteBuildJobs.id, id))
			.returning();
		return result[0];
	}
 
	// Cancel any active (pending/queued/building) build job for a pro website
	async cancelActiveBuild(proWebsiteId: number): Promise<number> {
		const result = await this.db
			.update(schema.websiteBuildJobs)
			.set({
				status: "cancelled",
				completedAt: new Date(),
				errorMessage: "Cancelled by user",
				dateUpdated: new Date(),
			})
			.where(
				and(
					eq(schema.websiteBuildJobs.proWebsiteId, proWebsiteId),
					or(
						eq(schema.websiteBuildJobs.status, "pending"),
						eq(schema.websiteBuildJobs.status, "queued"),
						eq(schema.websiteBuildJobs.status, "building"),
					),
				),
			)
			.returning();
		return result.length;
	}
 
	// Cancel pending/queued jobs for a pro website
	async cancelPendingJobs(proWebsiteId: number): Promise<number> {
		const result = await this.db
			.update(schema.websiteBuildJobs)
			.set({
				status: "cancelled",
				completedAt: new Date(),
				dateUpdated: new Date(),
			})
			.where(
				and(
					eq(schema.websiteBuildJobs.proWebsiteId, proWebsiteId),
					or(
						eq(schema.websiteBuildJobs.status, "pending"),
						eq(schema.websiteBuildJobs.status, "queued"),
					),
				),
			)
			.returning();
		return result.length;
	}
 
	// Cancel all building jobs (for testing/cleanup)
	async cancelAllBuildingJobs(): Promise<number> {
		const result = await this.db
			.update(schema.websiteBuildJobs)
			.set({
				status: "cancelled",
				completedAt: new Date(),
				errorMessage: "Manually cancelled - stuck job cleanup",
				dateUpdated: new Date(),
			})
			.where(eq(schema.websiteBuildJobs.status, "building"))
			.returning();
		return result.length;
	}
 
	// Get next version number for a pro website
	async getNextVersion(proWebsiteId: number): Promise<number> {
		const result = await this.db
			.select({ maxVersion: sql<number>`COALESCE(MAX(version), 0)` })
			.from(schema.websiteBuildJobs)
			.where(eq(schema.websiteBuildJobs.proWebsiteId, proWebsiteId));
		return (result[0]?.maxVersion ?? 0) + 1;
	}
 
	// ==================== Build Events ====================
 
	async logBuildEvent(
		buildJobId: number,
		event: string,
		message?: string,
		metadata?: Record<string, unknown>,
	): Promise<void> {
		await this.db.insert(schema.websiteBuildEvents).values({
			buildJobId,
			event: event as WebsiteBuildEvent["event"],
			message: message ?? null,
			metadata: metadata ?? null,
		});
	}
 
	async getBuildEvents(buildJobId: number): Promise<WebsiteBuildEvent[]> {
		return this.db
			.select()
			.from(schema.websiteBuildEvents)
			.where(eq(schema.websiteBuildEvents.buildJobId, buildJobId))
			.orderBy(schema.websiteBuildEvents.dateCreated);
	}
}