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 | 1x 32x 32x 5x 3x 1x 2x 2x 2x 14x 1x 13x 11x 11x 2x 1x 4x 2x 2x 2x 4x 3x 1x 11x 11x 11x 49x 49x 28x 8x 8x 41x 2x 39x 39x 39x 15x 15x 15x 15x 15x 15x 12x 11x 11x 8x 8x 7x 2x 2x 1x 1x 3x 3x 8x 2x 2x 2x 6x 6x 15x 5x 5x 5x 20x 20x 20x 16x 16x 16x 1x 15x 15x 15x 12x 15x 15x 13x 15x 4x 1x 1x 3x 1x 1x 2x 1x 1x 1x | /**
* ProSiteBuilder Durable Object
*
* Manages the container lifecycle for building pro sites.
*
* Two modes:
* 1. CF Containers (production): Uses this.container API when containers config is enabled
* 2. Direct HTTP (local dev): Falls back to calling the container server at localhost:8080
* which is started via `bun run dev:container`
*/
import { DurableObject } from "cloudflare:workers";
import { signS2SRequest } from "@interioring/internal-auth";
// Type for Cloudflare Container TCP Port
interface TcpPort {
fetch: (url: string, init?: RequestInit) => Promise<Response>;
connect: (address: string) => {
opened: Promise<void>;
writable: WritableStream;
readable: ReadableStream;
};
}
// Type for Cloudflare Container's internal API
// See: https://developers.cloudflare.com/durable-objects/api/container/
interface ContainerApi {
start: (options?: {
env?: Record<string, string>;
entrypoint?: string[];
enableInternet?: boolean;
}) => Promise<void>;
destroy: (error?: Error) => void;
monitor: () => Promise<void>;
signal: (signal: string) => void;
readonly running: boolean;
getTcpPort: (port: number) => TcpPort;
}
// Default URL for the container server in local development
const LOCAL_CONTAINER_URL = "http://localhost:8080";
export interface ProSiteBuilderEnv {
PRO_SITE_BUILDER: DurableObjectNamespace<ProSiteBuilder>;
API_URL: string;
INTERNAL_API_KEY: string;
ENVIRONMENT: string;
CLOUDFLARE_API_TOKEN?: string;
CLOUDFLARE_ACCOUNT_ID?: string;
}
/**
* ProSiteBuilder Durable Object
* Manages the container lifecycle for building pro sites
*/
export class ProSiteBuilder extends DurableObject<ProSiteBuilderEnv> {
private container: ContainerApi | null;
constructor(ctx: DurableObjectState, env: ProSiteBuilderEnv) {
super(ctx, env);
this.container = (
ctx as unknown as { container: ContainerApi | null }
).container;
}
async start(): Promise<string> {
if (this.container) {
if (this.container.running) {
return "already running";
}
await this.container.start({ enableInternet: true });
return "started";
}
return "container not available";
}
/**
* Ensure the container is running with enableInternet: true.
* If already running, reuse it. If not, start fresh.
*/
private async ensureRunning(): Promise<void> {
if (!this.container) {
throw new Error("Container not available");
}
if (this.container.running) {
console.log("[DO] Container already running, reusing");
return;
}
await this.container.start({ enableInternet: true });
console.log("[DO] Container started with enableInternet: true");
}
async stop(): Promise<string> {
if (this.container) {
this.container.destroy();
return "stopped";
}
return "container not available";
}
async status(): Promise<string> {
if (this.container) {
return this.container.running ? "running" : "stopped";
}
return "unknown";
}
/**
* Wait for the container's HTTP server to become ready.
* Polls the /health endpoint with exponential backoff.
*/
private async waitForReady(port: TcpPort): Promise<void> {
const MAX_ATTEMPTS = 20;
const BASE_DELAY_MS = 500;
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
try {
const resp = await port.fetch("http://container/health");
if (resp.ok) {
console.log(`[DO] Container ready after ${attempt} attempt(s)`);
return;
}
} catch {
// Connection refused — server not listening yet
}
if (attempt === MAX_ATTEMPTS) {
throw new Error(
`Container not ready after ${MAX_ATTEMPTS} attempts (~${(MAX_ATTEMPTS * BASE_DELAY_MS) / 1000}s)`,
);
}
const delay = BASE_DELAY_MS * Math.min(attempt, 4);
console.log(
`[DO] Waiting for container (attempt ${attempt}/${MAX_ATTEMPTS}, next retry in ${delay}ms)...`,
);
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
/**
* Send a build request to the container server.
* Uses CF Containers API when available, falls back to direct HTTP for local dev.
*/
private async runBuild(
jobId: number,
projectName: string,
): Promise<{ success: boolean; error?: string }> {
try {
console.log(
`[DO] runBuild called for job #${jobId}, project: ${projectName}`,
);
console.log(
`[DO] Container available: ${!!this.container}, env: ${this.env.ENVIRONMENT}`,
);
// Sign token bound to this specific jobId (prevents cross-job replay)
const internalAuthToken = this.env.INTERNAL_API_KEY
? await signS2SRequest(this.env.INTERNAL_API_KEY, "pro-sites", String(jobId))
: "";
const buildPayload = {
apiUrl: this.env.API_URL,
internalAuthToken,
environment: this.env.ENVIRONMENT,
projectName,
cloudflareApiToken: this.env.CLOUDFLARE_API_TOKEN,
cloudflareAccountId: this.env.CLOUDFLARE_ACCOUNT_ID,
};
let response: Response;
if (this.container?.getTcpPort) {
// Production path: CF Containers
await this.ensureRunning();
const port = this.container.getTcpPort(8080);
await this.waitForReady(port);
console.log(
`[DO] Triggering build for job #${jobId} via CF Container TCP port 8080...`,
);
response = await port.fetch(`http://container/build/${jobId}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(buildPayload),
});
// If the build failed due to networking (container started without
// enableInternet), destroy and let the queue retry with a fresh container.
if (!response.ok) {
const body = await response.clone().text();
if (body.includes("typo in the url or port")) {
console.log(
"[DO] Detected networking issue, destroying container for fresh start on retry",
);
this.container.destroy();
}
}
} else {
// Local dev path: direct HTTP to container server (bun run dev:container)
console.log(
`[DO] CF Container not available, falling back to direct HTTP at ${LOCAL_CONTAINER_URL}`,
);
response = await fetch(`${LOCAL_CONTAINER_URL}/build/${jobId}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(buildPayload),
});
}
if (!response.ok) {
const errorText = await response.text();
console.error(
`[DO] Build failed for job #${jobId}: status=${response.status}, body=${errorText}`,
);
return { success: false, error: `Build failed: ${errorText}` };
}
const result = (await response.json()) as {
success: boolean;
error?: string;
};
console.log(
`[DO] Build completed for job #${jobId}: ${result.success ? "success" : "failed"}${result.error ? ` (${result.error})` : ""}`,
);
return result;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.error(`[DO] Build error for job #${jobId}: ${message}`);
return { success: false, error: message };
}
}
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
console.log(`[DO] fetch: ${request.method} ${url.pathname}`);
// Build endpoint — triggered by queue consumer
// Returns immediately after dispatching the build to the container.
// The container updates job status via the internal API when done.
if (url.pathname.startsWith("/build/") && request.method === "POST") {
const jobIdStr = url.pathname.split("/")[2];
const jobId = parseInt(jobIdStr, 10);
if (Number.isNaN(jobId)) {
return new Response(JSON.stringify({ error: "Invalid job ID" }), {
status: 400,
headers: { "Content-Type": "application/json" },
});
}
// Extract projectName from request body
let projectName = "";
try {
const body = (await request.json()) as { projectName?: string };
projectName = body.projectName || "";
} catch {
// body parse failed — projectName stays empty
}
console.log(
`[DO] Received build request for job #${jobId}, project: ${projectName}`,
);
// Dispatch the build asynchronously — don't block the queue consumer.
// The container server handles the full build lifecycle and updates
// job status via the API when it completes or fails.
this.ctx.waitUntil(
this.runBuild(jobId, projectName).then((result) => {
console.log(
`[DO] Background build for job #${jobId}: ${result.success ? "success" : `failed: ${result.error}`}`,
);
}),
);
return new Response(
JSON.stringify({ success: true, message: "Build dispatched" }),
{
status: 202,
headers: { "Content-Type": "application/json" },
},
);
}
if (url.pathname === "/start") {
const result = await this.start();
return new Response(JSON.stringify({ status: result }), {
headers: { "Content-Type": "application/json" },
});
}
if (url.pathname === "/stop") {
const result = await this.stop();
return new Response(JSON.stringify({ status: result }), {
headers: { "Content-Type": "application/json" },
});
}
if (url.pathname === "/status") {
const result = await this.status();
return new Response(JSON.stringify({ status: result }), {
headers: { "Content-Type": "application/json" },
});
}
return new Response("Not Found", { status: 404 });
}
}
|